css水平垂直居中

效果图:

方法一:flex布局实现水平垂直居中

html:
<div class="container">
  <div class="box"></div>
</div>

css:
.container {
  width: 100%;
  height: 400px;
  background: #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
}

.container .box {
  width: 100px;
  height: 100px;
  background: yellow;
}

法二:行内元素 text-align 搭配 line-height(父级元素高度已知,子元素宽高度未知)

html:
<div class="container">
  <div class="box"></div>
</div>

css:
.container {
  width: 100%;
  height: 400px;
  line-height: 400px;
  background: #ccc;
  text-align: center;
}

.container .box {
  width: 100px;
  height: 100px;
  background: yellow;
  display: inline-block;
  vertical-align: middle;
}

法三:绝对定位实现水平垂直居中(需要知道子元素的宽高)

html:
<div class="container">
  <div class="box"></div>
</div>

css:
.container {
   width: 100%;
   height: 400px;
   background: #ccc;
   position: relative;
 }

.container .box {
  width: 100px;
  height: 100px;
  background: yellow;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -50px;
}

法四:绝对定位实现水平垂直居中(不需要知道子元素的宽高)

html:
<div class="container">
  <div class="box"></div>
</div>

css:
.container {
  width: 100%;
  height: 400px;
  background: #ccc;
  position: relative;
}

.container .box {
  width: 100px;
  height: 100px;
  background: yellow;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

法五:通过父元素使用display: table子元素使用vertical-align: middle实现水平垂直居中

html:
<div class="container">
  <div class="box">
    <div class="box2"></div>
  </div>
</div>

css:
.container {
  width: 100%;
  height: 400px;
  background: #ccc;
  display: table;
}

.container .box {
  text-align: center;
  display: table-cell;
  vertical-align: middle;
}

.container .box2 {
  width: 100px;
  height: 100px;
  background: yellow;
  display: inline-block;
  vertical-align: middle;
}

法六:table-cell嵌套两层用法

html:
<div class="container">
  <div class="box"></div>
</div>

css:
.container {
  width: 400px;
  height: 400px;
  background: #ccc;
  display: table-cell;
  vertical-align: middle;
}

.container .box {
  width: 100px;
  height: 100px;
  background: yellow;
  margin: 0 auto;
}

法七:绝对定位加四边定位为0,margin 为 auto(子元素高度未知时无效)

html:
<div class="container">
  <div class="box"></div>
</div>

css:
.container {
  width: 100%;
  height: 400px;
  background: #ccc;
  position: relative;
}

.container .box {
  width: 100px;
  height: 100px;
  background: yellow;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

法八:利用flex或grid布局结合 margin: auto;

html:
<div class="container">
  <div class="box"></div>
</div>

css:
.container {
  width: 100%px;
  height: 400px;
  background: #ccc;
  display: flex;
  /* display: grid; */
}

.container .box {
  width: 100px;
  height: 100px;
  background: yellow;
  margin: auto;
}

 

posted @ 2023-03-13 14:44  CodeFan*  阅读(37)  评论(0编辑  收藏  举报