如何将一个div内的图片居中(垂直和水平),并在另一个div内居中(水平)。

问题描述 投票:-1回答:2

我想让一个图像在水平和垂直方向上居中,在一个 div 也在另一个div中居中(水平)。

就像这样。image showing what I want to achieve

我想象着这样做。

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

https:/codepen.iolucasactimopenqBOzjwb。

但我无法找到正确的CSS规则来实现这种安排。如果能得到帮助,我将非常感激

html css centering
2个回答
-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>

-1
投票

justify-content: center; 给你水平居中,而 align-items: center; 给你垂直的。把它们结合在一起,就是这样:)

html,
body,
.grandad {
  height: 100%;
}

.grandad {
  display: flex;
  justify-content: center;
  align-items: center;
}

img {
  width: 100px;
}
<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>
© www.soinside.com 2019 - 2024. All rights reserved.