css absolute position will not work with margin-left:auto margin-right:auto [英] css absolute position won't work with margin-left:auto margin-right: auto
问题描述
假设您将以下css应用于div标签
Say you have the following css applied to a div tag
.divtagABS {
position: absolute;
margin-left: auto;
margin-right:auto;
}
左边距和右边距不生效
但如果你有亲戚,它工作正常
ie
but if you have relative, it works fine i.e.
,divtagREL {
position: relative;
margin-left: auto;
margin-right:auto;
}
为什么?我只是想将一个元素居中
why is that? i just want to center an element
有人可以解释为什么在绝对位置将边距设置为auto不起作用。
can someone explain why setting margins to auto in absolute position does not work?
推荐答案
编辑:这个答案曾经声称不可能以 margin:auto;
,但这根本不是真的。
EDIT : this answer used to claim that it isn't possible to center an absolutely positioned element with margin: auto;
, 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应用到
When you apply the following CSS to an element
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
然后给元素一个固定的宽度和高度,如200px或40%
And then give the element a fixed width and height, such as 200px or 40%, the element will center itself.
这里是一个小提琴,演示效果。
这篇关于css absolute position will not work with margin-left:auto margin-right:auto的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!