可以使用flex布局来实现,具体步骤如下:

  1. 在父元素上设置display: flex;和align-items: center;,使其成为一个flex容器,并将子元素垂直居中。
  2. 子元素的高度和宽度设置为auto,即不确定大小。
  3. 如果需要子元素水平居中,可以再设置justify-content: center;。

示例代码如下:

HTML:

<div class="parent">
  <div class="child"></div>
</div>

CSS:

.parent {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
  background-color: #eee;
}

.child {
  height: auto;
  width: auto;
  background-color: #ccc;
}

在上述示例中,父元素高度为300px,子元素的高度和宽度都设置为auto,且通过flex布局使子元素垂直和水平居中

怎么设置子元素高度和宽度不确定要在父div中垂直居中

原文地址: https://www.cveoy.top/t/topic/dT8L 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录