實現元素垂直水平居中的幾種方式

假設:

<div class="content-wrap" >
    <div class="content">
    </div>
</div>

第一種:

.content-wrap{
    width:300px;
    height:300px;
    position:relative;
}
.content{
    width: 100px;
    /*這裏的width和height可以使用百分比,那麼margin也應該設置爲百分比,並且滿足爲自身高度的一半*/
    height: 100px;
    position: absolute;
    background: lightcoral;
    margin-top: -50px;
    margin-left: -50px;
    /*margin爲自身高度的一半*/
    top: 50%;
    left: 50%;
}

第二種:使用flex

.content-wrap{
   display: flex;
   align-items: center; /*定義body的元素垂直居中*/
   justify-content: center; /*定義body的裏的元素水平居中*/
}

第三種:

.content-wrap {
  height: 800px;
  background: lightblue;
}
.child {
  background: orange;
  position: relative;
  margin: 0 auto;
  width: 200px;
  height: 200px;
  transform: translateY(-50%);
  top: 50%;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章