html - 负边距如何将元素设置在页面中央?

标签 html css

我发现了以下 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 */

enter image description here

所以计算是这样的

容器总宽度1000px

元素宽度300px

left: 50% 表示将从左边500px开始到800px

所以这不是居中的吗?

所以 -150px from 500px/* 这里的 500 还剩:50% */

你得到的元素从 350px650px

关于html - 负边距如何将元素设置在页面中央?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14795423/

相关文章:

html - 如何在我的自定义导航栏中将我的 anchor 元素居中?

html - 如何在导航栏中平均间隔元素

javascript - ExtJS updateLayout 不起作用

html - 无法应用 CSS 元素使表单右对齐

jquery - 在css中如何在没有空格的情况下加入两个div类?

css - 选择的初始宽度以及调整大小的机会

html - 如何让行元素占据整个宽度?

javascript - CSS3 属性 'backface-visibility' 不适用于任何 IE 版本

javascript - $(this).children() 不工作

html - 网格系统中不一致的网格线