3

I want to center the div (container) horizontaly. I tried margin: 0px auto; but it didn't work.

#container {
  position: relative;
}
#abs1{
  width:350px;
  height:230px;
  position: absolute;
  left: 0px;
  top: 0px;
  border:2px solid black;
  }
#abs2{
  width:250px;
  height:100px;
  position: absolute;
  left: 380px;
  top: 0px;
  border:2px solid black;
  }
<div id="container">
    <div id="abs1" ></div>
    <div id="abs2" ></div>
</div>

4 Answers4

4

If you want to center a container using margin: 0 auto; you need to also give that container a width.

#container {
  position: relative;
  margin: 0 auto;
  width: 530px;
}
#abs1{
  width:350px;
  height:230px;
  position: absolute;
  left: 0px;
  top: 0px;
  border:2px solid black;
  }
#abs2{
  width:250px;
  height:100px;
  position: absolute;
  left: 380px;
  top: 0px;
  border:2px solid black;
  }
<div id="container">
    <div id="abs1" ></div>
    <div id="abs2" ></div>
</div>
Steve
  • 8,609
  • 6
  • 40
  • 54
0

As Steve says you need to give a width to the parent container

#container {
  position: absolute;
  -webkit-transform: translateX(-50%) ;
  -moz-transform: translateX(-50%) ;
  transform: translateX(-50%) ;
  left:50%;
  top: 10px;
  width: 600px;
}
#abs1{
  width:350px;
  height:230px;
  position: absolute;
  left: 0px;
  top: 0px;
  border:2px solid black;
  }
#abs2{
  width:250px;
  height:100px;
  position: absolute;
  left: 380px;
  top: 0px;
  border:2px solid black;
  }
<div id="container">
    <div id="abs1" ></div>
    <div id="abs2" ></div>
</div>
ahPo
  • 374
  • 3
  • 9
0

A very cool solution can be found here.

https://css-tricks.com/centering-in-the-unknown

Its using pseudo elements for centering any content regardless of it box modal dimensions.

CodeWizard
  • 128,036
  • 21
  • 144
  • 167
0

You can achieve the layout that you need without using absolute positioning.

On the containing block, use display: table to get a shrink to fit width on the block level element, which will allow you to use margin: 0 auto to center the block.

Within the containing block, float the two child elements and adjust the margins as needed.

#container {
  overflow: auto;
  border: 1px dotted blue;
  display: table;
  margin: 0 auto;
}
#abs1{
  width: 150px;
  height:230px;
  border:2px solid black;
  float: left;
  margin-right: 20px;
  }
#abs2{
  width: 150px;
  height:100px;
  border:2px solid black;
  float: left;
  }
<div id="container">
    <div id="abs1" ></div>
    <div id="abs2" ></div>
</div>
Marc Audet
  • 46,011
  • 11
  • 63
  • 83