如何使用 CSS 将绝对 div 水平居中? [英] How to center absolute div horizontally using CSS?

查看:27
本文介绍了如何使用 CSS 将绝对 div 水平居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

.container {位置:绝对;顶部:15px;z-索引:2;宽度:40%;最大宽度:960px;最小宽度:600px;高度:60px;溢出:隐藏;背景:#fff;保证金:0 自动;}

解决方案

需要设置left: 0right: 0.

这指定边距边缘从窗口的侧面偏移多远.

<块引用>

与'top'类似,但指定框的右边距边缘与框包含块的[右/左]边缘的[左/右]偏移多远.

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

<块引用>

注意:元素的宽度必须小于窗口,否则它将占据窗口的整个宽度.

如果您可以使用媒体查询指定最小边距,然后过渡到 auto 以获得更大的屏幕尺寸.

<小时>

.container {左:0;右:0;左边距:自动;右边距:自动;位置:绝对;宽度:40%;轮廓:1px纯黑色;背景:白色;}

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.

I've a div and want it to be centered horizontally - although I'm giving it margin:0 auto; it's not centered...

.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;
}

解决方案

You need to set left: 0 and right: 0.

This specifies how far to offset the margin edges from the sides of the window.

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.

Source: 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.

If 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 将绝对 div 水平居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆