html - 在不知道宽度的情况下,仅使用 css 以绝对位置居中 div

标签 html css

我想根据用户点击的方式将显示和隐藏的不同图像居中。 我为使图像居中所做的是:

img { 
  margin-left: auto; 
  margin-right: auto; 
  display: block;
}

效果很好。但它不适用于 position: absolute; 是否有一种 css 方法可以将 position: absolute div 在 body 中间水平居中> 或 parent 不知道 width

最佳答案

对于绝对定位的元素,您可以将 margin:autoleft:0right:0 组合设置(水平居中) 或 top:0bottom:0(垂直居中):

img {
  position:absolute;
  left:0;
  right:0;
  margin:auto;
}

Demo.

关于html - 在不知道宽度的情况下,仅使用 css 以绝对位置居中 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23475514/

相关文章:

css - 将 rem 减少一个百分比?

html - 100%高度的div定位

html - <li> 子元素的行高问题

javascript - jQuery UI .tabs() 无内容选项卡?

html - CSS 文件路径在浏览器上发生变化

javascript - 使用 PHP 检测输入内容以重定向到特定页面

css - 并非所有字体都应用了 CSS3

css - 有漂亮的gwt css/主题吗?

html - ListView 的响应式设计代码

html - 如何更改下拉列表中选项值的颜色