The fixed element is aligned to the left of the main column
I'm not sure if this can be done with pure CSS. The site structure looks like this:
<body style="text-align:center;">
<div style="max-width:1000px; margin: 0 auto;" id="mainWraper">
<div id="fixedBox" style="position:fixed; top:100px; left:0;"></div>
</div>
</body>
I want to make the fixedBox be pushed out always 100px from the top screen and aligned to the left side of the mainWraper. mainWraper reacts with a maximum width of 1000px;
I know it can be done with JS, but can I only do it with css?
+3
source to share
3 answers
If the width of the container is lower 1000px
, the margin will be left aligned to the viewport. Otherwise, it will be aligned to the left of the container:
#fixedBox {
position: fixed;
left: 50%;
/* move it back half the width of your mainWrapper */
margin-left: -500px;
}
@media screen and (max-width: 999px) {
#fixedBox {
left: 0;
margin-left: 0;
}
}
Demo
+3
source to share
the gray square is yours fixedBox
and it will always be 100px from the top and left aligned to the main column
<body style="text-align:center;">
<div style="width:1000px; margin: 0 auto; height:1000px; position: relative;" id="mainWraper">
<div id="fixedBox" style="position:fixed; top:100px; left:0; width: 20px; height: 20px; background-color: #aaa;"></div>
</div>
</body>
questions:
- always set the width and height of the fixed element
- added
top: 100px
tofixedBox
stay 100px on top - enter some height in
mainwrapper
0
source to share