I´m trying to center a div in the center of a body so the margin to the left and the margin to the right (margin to scrollbar) are the same.
This is what I mean: Website The Top blue header is centered in the middle with same margin left and right.
But when I try to code it myself, the scrollbarwidth is manipulating the margin and sizes...
body{ width: 100%; height: 100em; background-color: aqua; } div{ width: 100%; height: 100%; background-color: grey; margin-left: auto; margin-right: auto; }
<div></div>
Even if I smaller the width it still has not the same margins:
body{ width: 98%; height: 100em; background-color: aqua; } div{ width: 100%; height: 100%; background-color: grey; margin-left: auto; margin-right: auto; }
<div></div>
That kid who created that page above did not seem to use any greater css, so wheres the trick ?
This is my Answer to my own Question, I'm not sure if it should be used likes this but I just removed the 100% width
from the body.
No idea why css acts like this but I checked that websites source and it did not has any body width so I just tried that.
You can use viewport widths instead of percentage and set margins like this:
body {width:100vw}
div {margin:0 auto}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.