元素垂直水平居中的多种方案

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

宽高固定的元素如何进行垂直水平居中

1.使用绝对定位与负边距实现

  

.parent {
      position: relative;
      width: 400px;
      height: 400px;
      margin: auto;
      border: 1px solid yellow;
    }

.child {
      position: absolute;
      top: 50%;
      left: 50%;
      margin: -100px 0 0 -100px;
      width: 200px;
      height: 200px;
      border: 1px solid green;
    }

  这个的实现方法原理: 相对父元素定位,距上边和左边框一半,然后margin在减去子元素的一半。

2.绝对定位与margin:auto实现水平垂直居中

.parent {
  position: relative;
  width: 400px;
  height: 400px;
  margin: auto;
  border: 1px solid yellow;
}
.child {
  position: absolute;
  margin: auto;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 200px;
  height: 200px;
  border: 1px solid green;
}

  

未知宽高的元素如何进行水平垂直居中

1.css3来实现

 .parent {
      position: relative;
      width: 400px;
      height: 400px;
      margin: auto;
      border: 1px solid yellow;
    }
.child {
      position: absolute;
      width: 200px;
      height: 200px;
      border: 1px solid green;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

2.flex实现

.parent {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 400px;
    height: 400px;
    margin: auto;
    border: 1px solid yellow;
}

.child {
    width: 200px;
    height: 200px;
    border: 1px solid green;
}

猜你喜欢

转载自www.cnblogs.com/liushenga/p/11331804.html