我想根据用户点击的方式将显示和隐藏的不同图像居中。 我为使图像居中所做的是:
img {
margin-left: auto;
margin-right: auto;
display: block;
}
效果很好。但它不适用于 position: absolute;
是否有一种 css 方法可以将 position: absolute
div 在 body
中间水平居中> 或 parent
不知道 width
?
最佳答案
对于绝对定位的元素,您可以将 margin:auto
与 left:0
和 right:0
组合设置(水平居中) 或 top:0
和 bottom:0
(垂直居中):
img {
position:absolute;
left:0;
right:0;
margin:auto;
}
Demo.
关于html - 在不知道宽度的情况下,仅使用 css 以绝对位置居中 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23475514/