假设您将以下CSS应用于div标记

.divtagABS {
    position: absolute;
    margin-left: auto;  
    margin-right: auto;
}

margin-leftmargin-right不生效

但如果你有亲戚的话,效果很好

.divtagREL {
    position: relative;
    margin-left: auto;  
    margin-right: auto;
}

为什么会这样呢?我只想把一个元素居中.

有人能解释一下为什么在绝对位置将边距设置为自动不起作用吗?

推荐答案

EDIT : this answer used to claim that it isn't possible to center an absolutely positioned element with 100, but this simply isn't true. Because this is the most up-voted and accepted answer, I guessed I'd just change it to be correct.

将以下CSS应用于元素时

position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;

然后给元素一个固定的宽度和高度,例如200px或40%,元素will本身居中.

这里有a Fiddle个演示效果.

Html相关问答推荐

html中背景色的全单元格R中的Rmarkdown表

如何将值从Google Sheets侧边栏中的表单中的输入传递到Google Sheets单元格中使用Textile()

在Apps Script中连接CSS与HTML

输入表单在奇怪的地方舍入的标签

Angular Project中的星级 Select

Firefox和Chrome在文字装饰和文字阴影方面的不同优先顺序

当溢出到滚动条中时, bootstrap 按钮样式会更改

Tailwind CSS:overflow-y Property Not Scrolling Unreliably to Bottom with top-[63px]

不能以Angular 更改输入的S边框 colored颜色

如何用等宽字体固定数字在有序列表中的位置

有没有什么方法可以很容易地给一个SVG一个插框阴影?

div 中的垂直中心表格

为什么要添加换行符(至少在 Google Chrome 中)

Div 容器不会遵守边距、填充或间隙

如何用js和CSS在两点之间画一条线

如何在滚动行中显示一张图片和下一张图片的一半?

如何使用 CSS 制作蜂窝状网格?

如何在react 中向按钮添加禁用属性?

flex-box 中的图像在 Chrome 和 Firefox 中看起来不同 - 如何使它们在 Firefox 中看起来像?

我的卡片内容无法在 bootstrap 5 中正确居中