1. 程式人生 > 實用技巧 >css常用居中方式

css常用居中方式

一、水平居中

1.內聯元素

父級元素加 text-align: center 即可

html

<div class="container">
  <a>內聯元素</a>
</div>

css

.container {
  text-align: center;
}

2.塊級元素

給定寬度,然後 margin 上下為 0,左右 auto 即可

html

<div class="container">
  塊級元素
</div>

css

.container {
  width: 200px;
  margin: 0 auto;
}

3.多個塊級元素

第一種方式

子元素設定成內聯,父級元素加 text-align:center即可

html

<div class="container">
  <div>
    第一個塊
  </div>
  <div>
    第二個塊
  </div>
  <div>
    第三個塊
  </div>
</div>

css

.container {
  text-align: center;
}
.container div {
  display: inline-block;
}

第二種方式

利用 flexbox 彈性佈局

html

<div class="container">
  <div>
    第一個塊
  </div>
  <div>
    第二個塊
  </div>
  <div>
    第三個塊
  </div>
</div>

css

.container {
  display: flex;
  justify-content: center;
}

二、垂直居中

1.內聯元素

第一種方式

設定 padding

html

<div class="container">
  需要垂直居中的內容(內聯)
</div>

css

.container {
  padding: 40px 40px;
}

第二種方式

按照父級元素的高度,設定子元素的行高

html

<div class="container">
  需要垂直居中的內容(內聯)
</div>

css

.container {
  height: 100px;
  line-height: 100px;
}

第三種方式

利用 flexbox,父級元素需給定高度

html

<div class="container">
  <a href="">爺要垂直居中</a>
  <a href="">爺要垂直居中</a>
  <a href="">爺要垂直居中</a>
</div>

css

.container {
  width: 200px;
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

2.塊級元素

第一種方式

父元素相對定位 position:relative,子元素絕對定位 position: absolute

html

<div class="container">
  <div>爺要垂直居中</div>
</div>

css

.container {
  position: relative;
  width: 200px;
  height: 200px;
}
.container div {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

第二種方式

利用 flexbox

html

<div class="container">
  <div>爺要垂直居中</div>
</div>

css

.container {
  width: 200px;
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

三、水平和垂直居中

第一種方式

父元素相對定位 position:relative,子元素絕對定位 position: absolute

html

<div class="container">
  <div>爺要水平和垂直居中</div>
</div>

css

.container {
  position: relative;
  width: 200px;
  height: 200px;
}
.container div {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: red;
}

第二種方式

使用 flexbox

html

<div class="container">
  <div>我要垂直居中啊a我要垂直居中啊a我要垂直居中啊</div>
</div>

css

.container {
  width: 200px;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.container div {
  width: 100px;
  height: 100px;
}

最後說一點,如果具體寬高已知,給定具體數值就可以直接實現

The_End