01_css垂直居中的几种实现方法

2020-04-16  本文已影响0人  沐向

一、position 子元素已知宽度

要点:子元素距上50%,距左50%,外边距设置为自身宽高的一半

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

.parent {
  background: #f00;
  width: 400px;
  height: 400px;
  position: relative;
}
.child {
  background: #00f;
  width: 200px;
  height: 100px;
  position: absolute;
  left: 50%;
  top: 50%;
  margin: -50px 0 0 -100px;
}

二、position+transform 子元素已知宽度

要点:子元素添加 transform: translate(-50%,-50%);

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

.parent {
  background: #f00;
  width: 400px;
  height: 400px;
  position: relative;
}
.child {
  background: #00f;
  width: 200px;
  height: 100px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
}

三、flex布局

要点:父元素添加 display: flex; justify-content: center; align-items: center;

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

.parent {
  background: #f00;
  width: 400px;
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.child {
   background: #00f;
   width: 200px;
   height: 100px;
}

四、table-cell布局

要点:

<div class="box">
    <div class="content">
        <div class="inner"></div>
    </div>
</div>

.box {
    background: #f00;
    width: 400px;
    height: 400px;
    display: table;
}
.content {
    background: #00f;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
.inner {
    background: #000;
    display: inline-block;
    width: 200px;
    height: 100px;
}
上一篇 下一篇

猜你喜欢

热点阅读