I\'m trying to get a div that has position:fixed
center aligned on my page.
I\'ve always been able to do it with absolutely positioned divs using this \
From the post above, I think the best way is
width: 100%
margin-left: auto
and margin-right: auto
, or for table make it align="center"
.Hope this will help.
Normal divs should use margin-left: auto
and margin-right: auto
, but that doesn't work for fixed divs. The way around this is similar to Andrew's answer, but doesn't use the deprecated <center>
thing. Basically, just give the fixed div a wrapper.
#wrapper {
width: 100%;
position: fixed;
background: gray;
}
#fixed_div {
margin-left: auto;
margin-right: auto;
position: relative;
width: 100px;
height: 30px;
text-align: center;
background: lightgreen;
}
<div id="wrapper">
<div id="fixed_div"></div>
</div
This will center a fixed div within a div while allowing the div to react with the browser. i.e. The div will be centered if there's enough space, but will collide with the edge of the browser if there isn't; similar to how a regular centered div reacts.
If you know the width is 400px this would be the easiest way to do it I guess.
left: calc(50% - 200px);
This works if you want the element to span across the page like another navigation bar.
width: calc (width: 100% - width whatever else is off centering it)
For example if your side navigation bar is 200px:
width: calc(100% - 200px);
A solution using flex box; fully responsive:
parent_div {
position: fixed;
width: 100%;
display: flex;
justify-content: center;
}
child_div {
/* whatever you want */
}
It is quite easy using width: 70%; left:15%;
Sets the element width to 70% of the window and leaves 15% on both sides