I've a div and want it to be centered horizontally - although I'm giving it margin:0 auto;
it's not centered...
.container {
position: absolute;
top: 15px;
z-index: 2;
width:40%;
max-width: 960px;
min-width: 600px;
height: 60px;
overflow: hidden;
background: #fff;
margin:0 auto;
}
Although above answers are correct but to make it simple for newbies, all you need to do is set margin, left and right. following code will do it provided that width is set and position is absolute:
margin: 0 auto;
left: 0;
right: 0;
Demo:
.centeredBox {_x000D_
margin: 0 auto;_x000D_
left: 0;_x000D_
right: 0;_x000D_
_x000D_
_x000D_
/** Position should be absolute */_x000D_
position: absolute;_x000D_
/** And box must have a width, any width */_x000D_
width: 40%;_x000D_
background: #faebd7;_x000D_
_x000D_
}
_x000D_
<div class="centeredBox">Centered Box</div>
_x000D_
Flexbox? You can use flexbox.
.box {_x000D_
display: -ms-flexbox;_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
_x000D_
-webkit-justify-content: center;_x000D_
justify-content: center;_x000D_
_x000D_
}_x000D_
_x000D_
.box div {_x000D_
border:1px solid grey;_x000D_
flex: 0 1 auto;_x000D_
align-self: auto;_x000D_
background: grey;_x000D_
}
_x000D_
<div class="box">_x000D_
<div class="A">I'm horizontally centered.</div>_x000D_
</div>
_x000D_
so easy, only use margin and left, right properties:
.elements {
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
}
You can see more in this tip => How to set div element to center in html- Obinb blog
You can't use margin:auto;
on position:absolute;
elements, just remove it if you don't need it, however, if you do, you could use left:30%;
((100%-40%)/2) and media queries for the max and min values:
.container {
position: absolute;
top: 15px;
left: 30%;
z-index: 2;
width:40%;
height: 60px;
overflow: hidden;
background: #fff;
}
@media all and (min-width:960px) {
.container {
left: 50%;
margin-left:-480px;
width: 960px;
}
}
@media all and (max-width:600px) {
.container {
left: 50%;
margin-left:-300px;
width: 600px;
}
}
.centerDiv {
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
text-align:center;
}
Here is a link please use this to make the div in the center if position is absolute.
HTML:
<div class="bar"></div>
CSS:
.bar{
width:200px;
border-top:4px solid red;
position:absolute;
margin-left:auto;
margin-right:auto;
left:0;
right:0;
}
This doesn't work in IE8 but might be an option to consider. It is primarily useful if you do not want to specify a width.
.element
{
position: absolute;
left: 50%;
transform: translateX(-50%);
}
Centering div with position: absolute and width: unknown:
HTML:
<div class="center">
<span></span>
<div>
content...
</div>
</div>
CSS:
.center{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: grid;
grid-template-columns: auto auto;
overflow: auto;
}
Source: Stackoverflow.com