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 \
I used the following with Twitter Bootstrap (v3)
<footer id="colophon" style="position: fixed; bottom: 0px; width: 100%;">
<div class="container">
<p>Stuff - rows - cols etc</p>
</div>
</footer>
I.e make a full width element that is fixed position, and just shove a container in it, the container is centered relative to the full width. Should behave ok responsively too.
Koen's answer doesn't exactly centers the element.
The proper way is to use CCS3 transform
property. Although it's not supported in some old browsers. And we don't even need to set a fixed or relative width
.
.centered {
position: fixed;
left: 50%;
transform: translate(-50%, 0);
}
Working jsfiddle comparison here.
if you don't want to use the wrapper method. then you can do this:
.fixed_center_div {
position: fixed;
width: 200px;
height: 200px;
left: 50%;
top: 50%;
margin-left: -100px; /* 50% of width */
margin-top: -100px; /* 50% of height */
}
You could use flexbox for this as well.
.wrapper {
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 100%;
/* this is what centers your element in the fixed wrapper*/
display: flex;
flex-flow: column nowrap;
justify-content: center; /* aligns on vertical for column */
align-items: center; /* aligns on horizontal for column */
/* just for styling to see the limits */
border: 2px dashed red;
box-sizing: border-box;
}
.element {
width: 200px;
height: 80px;
/* Just for styling */
background-color: lightyellow;
border: 2px dashed purple;
}
<div class="wrapper"> <!-- Fixed element that spans the viewport -->
<div class="element">Your element</div> <!-- your actual centered element -->
</div>
If you want to center aligning a fixed position div both vertically and horizontally use this
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
<div class="container-div">
<div class="center-div">
</div>
</div>
.container-div {position:fixed; left: 0; bottom: 0; width: 100%; margin: 0;}
.center-div {width: 200px; margin: 0 auto;}
This should do the same.