简体   繁体   English

如何在合并滚动条宽度的主体内将div精确水平居中?

[英]How to exactly horizontally center a div inside a body integrating the scrollbar-width?

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. 我正在尝试将div置于主体的中心,以便左侧的边距和右侧的边距(滚动条的边距)相同。

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... 但是当我尝试自己编写代码时,scrollbarwidth正在操纵边距和大小...

 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 ? 在上面创建该页面的那个孩子似乎并没有使用任何更大的CSS,那么诀窍在哪里呢?

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. 这是我对自己问题的回答,我不确定是否应该像这样使用它,但我只是从身体上去除了100% width

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. 不知道为什么css会这样,但是我检查了网站资源,它没有任何宽度,所以我尝试了。

You can use viewport widths instead of percentage and set margins like this: 您可以使用视口宽度而不是百分比,并按如下所示设置边距:

body {width:100vw}
div {margin:0 auto}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM