首頁  >  文章  >  web前端  >  6種CSS水平垂直居中解決方案

6種CSS水平垂直居中解決方案

小云云
小云云原創
2018-02-23 09:32:001931瀏覽

本文主要和大家介紹了CSS水平垂直居中解決方案(6種)的相關資料,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧,希望能幫助大家。

準備

建立元素

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

垂直水平居中方案一:知道寬度的情況下absolute+margin負值

.parent {
  width:400px;
  height:400px;
  background: red;
  position: relative;
}
.child {
  position: absolute;
  left:50%;
  top:50%;
  background: yellow;
  width:50px;
  height:50px;
  margin-left:-25px;
  margin-top:-25px;
}

垂直水平居中方案二:不知道寬高的情況下absolute+transform

.parent {
  width:400px;
  height:400px;
  background: red;
  position: relative;
}
.child {
  position: absolute;
  left:50%;
  top:50%;
  transform: translate(-50%,-50%);
}

垂直居中方案三:position+margin:auto

.parent {
  position:relative;
  width:200px;
  height:200px;
  background: red;
}
.child {
  width:80px;
  height:40px;
  background: yellow;
  position: absolute;
  left:0;
  top:0;
  right:0 ;
  bottom:0;
  margin:auto;
}

垂直居中方案四:+ 多行文本的垂直居中:table-cell+vertical-align:middle;

.parent {
    height: 300px;
    width:400px;
    border: 1px solid red;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
.child {
  display: inline-block;
  width:50px;
  height:50px;
  background: blue;
}
/* 或者 */
.parent {
    width: 400px;
    height: 300px;
    display: table-cell;
    vertical-align: middle;
    border: 1px solid red;
    text-align: center;
}
.child {
    display: inline-block;
    vertical-align: middle;
    background: blue;
}

垂直居中方案五:display: flex

.parent {
  width:400px;
  height:200px;
  background:red;
  display: flex;
  justify-content:center;
  align-items:center;
}
.child {
  height:100px;
  width:100px;
  background:green;
}

垂直居中方案六:偽元素

.parent {
  width:200px;
  height:200px;
  background:red;
  text-align: center;
}
.child {
  height:100px;
  width:100px;
  background:yellow;
  display: inline-block;
  vertical-align: middle;
}
.parent:before {
  content:"";
  height:100%;
  vertical-align: middle;
  display: inline-block;
}

相關推薦:

css水平垂直居中的4種實現方法

#html的元素水平垂直居中應該怎麼設定

css如何實現水平垂直居中以及兩端對齊的程式碼分享

#

以上是6種CSS水平垂直居中解決方案的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn