可以使用以下方法让子元素在父元素中水平垂直居中:

  1. 使用flexbox布局,设置父元素的display属性为flex,同时设置justify-content和align-items属性为center。
<div class="parent">
  <div class="child">子元素</div>
</div>

<style>
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
  /* 设置父元素宽高 */
  width: 300px;
  height: 300px;
  background-color: #eee;
}

.child {
  /* 设置子元素宽高 */
  width: 100px;
  height: 100px;
  background-color: #ccc;
}
</style>
  1. 使用绝对定位,设置子元素的position属性为absolute,同时设置top、bottom、left和right属性为0,以及margin为auto。
<div class="parent">
  <div class="child">子元素</div>
</div>

<style>
.parent {
  /* 设置父元素宽高 */
  width: 300px;
  height: 300px;
  background-color: #eee;
  position: relative;
}

.child {
  /* 设置子元素宽高 */
  width: 100px;
  height: 100px;
  background-color: #ccc;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}
</style>
  1. 使用表格布局,设置父元素的display属性为table,同时设置子元素的display属性为table-cell和vertical-align属性为middle,以及text-align属性为center。
<div class="parent">
  <div class="child">子元素</div>
</div>

<style>
.parent {
  display: table;
  /* 设置父元素宽高 */
  width: 300px;
  height: 300px;
  background-color: #eee;
}

.child {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  /* 设置子元素宽高 */
  width: 100px;
  height: 100px;
  background-color: #ccc;
}
</style>
html如何让子元素在父元素中水平垂直居中?

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

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