css - 如何使用 CSS 将绝对 div 水平居中?

标签 css html center absolute

我有一个 div 并希望它水平居中 - 尽管我给它 margin:0 auto; 它没有居中...

.container {
    position: absolute;
    top: 15px;
    z-index: 2;
    width:40%;
    max-width: 960px;
    min-width: 600px;
    height: 60px;
    overflow: hidden;
    background: #fff; 
    margin:0 auto;
}

最佳答案

你需要设置left: 0right: 0

这指定从窗口边缘偏移边缘边缘的距离。

Like 'top', but specifies how far a box's right margin edge is offset to the [left/right] of the [right/left] edge of the box's containing block.

来源: http://www.w3.org/TR/CSS2/visuren.html#position-props

Note: The element must have a width smaller than the window or else it will take up the entire width of the window.

You could use media queries to specify a minimum margin, and then transition to auto for larger screen sizes.


.container {
  left:0;
  right:0;

  margin-left: auto;
  margin-right: auto;

  position: absolute;
  width: 40%;

  outline: 1px solid black;
  background: white;
}
<div class="container">
  Donec ullamcorper nulla non metus auctor fringilla.
  Maecenas faucibus mollis interdum.
  Sed posuere consectetur est at lobortis.
  Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.
  Sed posuere consectetur est at lobortis.
</div>

关于css - 如何使用 CSS 将绝对 div 水平居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17976995/

相关文章:

html - Bootstrap 导航栏 : navbar-right

jquery - 此代码在任何地方都有效,但在 safari 中除外

javascript - Visual Studio Code - 将 Javascript 文件链接到 HTML 文件

jQuery 不显示谷歌地图

使用中心插件将 jQuery 中心元素设置为视口(viewport)

css - 以字间距和背景图像居中文本

css - 我的 Angular router-outlet 元素上的这个样式属性来自哪里?

javascript - 使用 javascript 根据选定的组合框动态更改图像

html - 确保标题保留在图片下方

android - Horizo​​ntal RecyclerView 项目居中