中心div与位置绝对只是css不知道的宽度 [英] center div with position absolute with just css without knowing the width
问题描述
我想将显示和隐藏的不同图片对中,具体取决于用户点击的方式。
我做了一个图像的中心是:
I would like to center different images which are shown and hidden, depending on how the user clicks. What I did to center an image was:
img {
margin-left: auto;
margin-right: auto;
display: block;
}
但它不适用于 position:absolute;
有一个css只有一个方法来中心位置:absolute
div而不知道 width
body 或 >
which worked fine. But it does not work for a position: absolute;
Is there a css only way to center a position: absolute
div horizontally in the middle of body
or parent
without knowing the width
?
推荐答案
对于绝对定位的元素,可以设置 margin:auto
与 left:0
和 right:0
(用于水平居中)或 top:0
和 bottom:0
(垂直居中):
For absolutely positioned element, you can set the margin:auto
in combination with left:0
and right:0
(for horizontally centered) or top:0
and bottom:0
(for vertically centered):
img {
position:absolute;
left:0;
right:0;
margin:auto;
}
这篇关于中心div与位置绝对只是css不知道的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!