Search code examples
javascripthtmlcssoverflowcentering

child div align center on parent div with overflow?


Hello Stackoverflow Team,

How can the child div inside the parent div with overflow have a right and left margin? I'm trying to solve the issue but it does not give a clean solution for it.

Attempt:

margin-right wont work

div {
  border: 1px solid black;
}

.parent {
  width: 300px;
  height: 300px;
  margin: auto;
  position: relative;
  overflow: auto;
}

.child {
  width: 350px;
  height: 150px;
  top: 50px;
  margin-left: 20px;
  margin-right: 20px;
  position: absolute;
  display: inline-block;
}
<div class="parent">
  <div class="child"></div>
</div>

My unclean Solution:

div {
  border: 1px solid black;
}

.parent {
  width: 300px;
  height: 300px;
  margin: auto;
  position: relative;
  overflow: auto;
}

.child {
  width: 350px;
  height: 150px;
  top: 50px;
  margin-left: 20px;
  border-right: 20px solid red;
  position: absolute;
  display: inline-block;
}
<div class="parent">
  <div class="child"></div>
</div>

any better way to solve the issue?


Solution

  • Since you are using position: absolute for the child, best way to achieve what you want is remove position: absolute then add the margins you need.

    div{
      border: 1px solid black;
    }
    .parent {
        width:300px;
        height:300px;
        margin:auto;
        position: relative;
        overflow: auto;
    }
    
    .child {
        width:350px;
        height:150px;
        top: 50px;
        margin: 50px 20px 0;
        display: inline-block;
    }
    <div class="parent">
        <div class="child"></div>
    </div>

    Update

    If you need the child div to be position: absolute you will have to wrap it in another div as follow:

    div{
      border: 1px solid black;
    }
    .parent {
      width:300px;
      height:300px;
      margin:auto;
      position: relative;
      overflow: auto;
    }
    .child {
      border-color: red;
      position: absolute;
      top: 20px;
      height: 150px;
    }
    .sub-child {
      width:350px;
      height:150px;
      margin: 0 20px;
      display: inline-block;
    }
    <div class="parent">
      <div class="child">
        <div class="sub-child"></div>
      </div>
    </div>