【问题标题】:How to vertically center image without :before如何在没有 :before 的情况下垂直居中图像
【发布时间】:2014-11-02 17:04:39
【问题描述】:

我想知道是否有另一种方法可以在不使用伪元素 :before 的情况下使动态大小的图像居中。谢谢!

【问题讨论】:

标签: html css css-position centering pseudo-element


【解决方案1】:

我喜欢CSS-Tricks 的这个选项。首先,将图像定位在容器的top: 50%left: 50% 处,将图像的左上角置于容器的中心。然后通过添加transform: translate(-50%, -50%) 来固定它的位置,这会将图像向后移动图像大小的一半。

.container {
  position: relative;
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
  margin: 0 auto;
}

.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="container">
  <img src="http://placekitten.com/g/200/150" class="center" />
</div>

【讨论】:

    猜你喜欢
    • 2013-02-28
    • 2014-08-15
    • 2012-01-29
    • 2021-04-02
    • 2011-07-23
    • 1970-01-01
    • 2012-07-02
    • 2017-07-06
    • 1970-01-01
    相关资源
    最近更新 更多