I want a horizontally centered "floating" div, i.e. one that always is on top of the screen even if the user scrolls around.
With the following CSS I get the div centered completely on the left:
#guiBar {
margin-left: auto;
margin-right: auto;
position: fixed;
}
margin: 0 auto doesn't help either (presumably because that doesn't work together with position: fixed ?
I don't really care how the solution works so javascript or some html5 trickery would be just as fine as pure css. I already tried the solution found here from starx but that also doesn't seem to work with position: fixed. there's also this which doesn't work either (i.e. it's left centered - not sure if a number of <input class="guiButton" type="image" src="/icons/some.png" /> have a fixed size by his definition.)
If your element is a fixed width (for instance width:400px) you can use the left and top attributes along with the margin attributes:
#guiBar
{
position:fixed;
left:50%;
margin-left:-200px; /*half the width*/
}
Demo: http://jsfiddle.net/VtqQD/1/show
Source: http://jsfiddle.net/VtqQD/1
EDIT: Thanks to Xander for pointing out the question was about horizontal positioning only.
html
<div id="subject">
<div id="predicate">
Read Me!
</div>
</div>
css
#subject {
position:fixed;
top:0px;
left:0px;
width:100%;
height:100%;
}
#predicate {
position:relative;
top:50%;
margin:-20px auto auto auto; /*half of height*/
width:140px;
height:40px;
background:#b4da55;
}
try it out http://jsfiddle.net/RfRAb/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With