【问题标题】:How to center (vertically and horizontally) an image inside a div centered (horizontally) in another div如何将 div 中的图像居中(垂直和水平)在另一个 div 中居中(水平)
【发布时间】:2020-09-16 00:57:03
【问题描述】:

我希望在div 中水平和垂直居中的图像在另一个div 中也居中(水平)。

类似这样的:

我想这是这样完成的:

<div class="grandad">
  <div class="parent">
    <img src="someUrl"/>
  </div>
</div>

https://codepen.io/lucasactimo/pen/qBOzjwb

但我无法找到正确的 CSS 规则来实现这种安排。非常感谢您的帮助!

【问题讨论】:

    标签: html css centering


    【解决方案1】:

    对内部容器和外部容器使用 flexbox 两次,这些设置使(唯一的)子容器居中:

      display: flex;
      justify-content: center;
      align-items: center;
    

    .grandad {
      height: 300px;
      border: 1px solid #bbb;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .parent {
      height: 200px;
      width: 200px;
      border-radius: 50%;
      background-color: red;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    img {
      height: 64px;
      width: 64px;
    }
    <div class="grandad">
      <div class="parent">
        <img src="https://p0.pikist.com/photos/915/114/flower-macro-nature-flora-wild-flowers-blossomed-summer-flowers-white-flowers-pollen.jpg" />
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-29
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      • 2017-08-04
      • 2014-05-10
      相关资源
      最近更新 更多