我发现了以下 css 片段。它为 ID 为 search bar 的元素提供绝对位置,300px
的宽度,27px 的高度,并将搜索栏设置为 50%
这是正常位置
#search_bar {
position:relative;
width: 300px;
left:50%;
height:27px;
}
但我没有看到 搜索栏 居中对齐。这是为什么 ?但是,如果我将代码片段更改为:
#search_bar {
position:relative;
width: 300px;
margin-left:-150px;
left:50%;
height:27px;
}
它与页面的中心对齐。那个怎么样 ? margin-left:-150px
属性如何将其设置为中心?
最佳答案
这是因为您使用的是绝对位置,所以负边距是元素宽度的一半,因此它会将元素向后移动其总宽度的 1/2
position: absolute;
left: 50%; /* This shifts the element 50% from left, if you
don't want to use negative margins you can use 45%, 40% but you need
to fiddle with the measurements first */
所以计算是这样的
容器总宽度1000px
元素宽度300px
left: 50%
表示将从左边500px
开始到800px
所以这不是居中的吗?
所以 -150px
from 500px
/* 这里的 500 还剩:50% */
你得到的元素从 350px
到 650px
关于html - 负边距如何将元素设置在页面中央?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14795423/