Center fixed div with dynamic width (CSS)
Solution 1:
You can center a fixed
or absolute
positioned element setting right
and left
to 0
, and then margin-left
& margin-right
to auto
as if you were centering a static
positioned element.
#example {
position: fixed;
/* center the element */
right: 0;
left: 0;
margin-right: auto;
margin-left: auto;
/* give it dimensions */
min-height: 10em;
width: 90%;
}
See this example working on this fiddle.
Solution 2:
Here's another method if you can safely use CSS3's transform
property:
.fixed-horizontal-center
{
position: fixed;
top: 100px; /* or whatever top you need */
left: 50%;
width: auto;
-webkit-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-o-transform: translateX(-50%);
transform: translateX(-50%);
}
...or if you want both horizontal AND vertical centering:
.fixed-center
{
position: fixed;
top: 50%;
left: 50%;
width: auto;
height: auto;
-webkit-transform: translate(-50%,-50%);
-moz-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
-o-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}