一. 水平居中
- margin: 0 auto
<div class="box"></div>
<style>
.box {
width: 200px;
height: 100px;
margin: 0 auto;
background-color: pink;
}
</style>
- 當(dāng)子元素
display: inline-block
時(shí)与涡,父元素text-align: center
,可控制子元素水平居中持偏。
<div class="wrap">
<div class="box"></div>
</div>
<style>
.wrap {
text-align: center;
}
.box {
display: inline-block;
width: 100px;
height: 100px;
background-color: pink;
}
</style>
text-align: center
在塊級父容器中讓行內(nèi)元素居中驼卖,inline
/inline-block
/inline-table
/inline
/flex
等類型的元素實(shí)現(xiàn)居中。
二. 垂直居中
單行鸿秆,對于單行行內(nèi)或文本元素酌畜,只需為它們添加等值的
padding-top
和padding-bottom
。在已知文本不會(huì)換行的時(shí)候卿叽,可以 line-height = height 來實(shí)現(xiàn)垂直居中桥胞。
-
多行文本垂直居中
3.1 方法一
3.2 方法二:使用 flex
.box {
display: flex;
align-items: center;
width: 100px;
height: 100px;
background-color: #ccc;
}
- 當(dāng)父元素沒有固定高度時(shí),可以采用
幽靈元素(ghost element)
的非常規(guī)解決方式:在垂直居中的元素上添加偽元素考婴,設(shè)置偽元素的高等于父元素的高贩虾,然后為子元素添加vertical-align: middle;
。
// 待定
三. 水平垂直居中
絕對定位元素的水平垂直居中
- 寬高固定沥阱,絕對定位缎罢,
top: 50%; left: 50%;
左上 margin 為自身寬高一半
<div class="box"></div>
<style>
.box {
width: 200px;
height: 100px;
position: absolue;
left: 50%;
top: 50%;
margin-top: -50px;
margin-left: -100px;
background-color: pink;
}
</style>
- 同上,使用 css3 里的 transform 代替 margin考杉〔呔可以不設(shè)寬高。
<div class="box"></div>
<style>
.box {
position: absolue;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background-color: pink;
}
</style>
transform
里的translate
偏移的百分比值是相對于自身大小的translate()
方法崇棠,根據(jù)左(X軸)
和頂部(Y軸)
位置給定的參數(shù)陪毡,從當(dāng)前元素位置移動(dòng)坝辫,如:translate
值(50px雕憔,100px)
是從左邊元素移動(dòng) 50 個(gè)像素萧吠,并從頂部移動(dòng) 100 像素及老。
margin:auto
.box {
position: absolute;
background: red;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 200px;
height: 100px;
}
利用 flex 布局的水平垂直居中
需要注意抽莱,flex 垂直居中相對于父元素高度范抓。
<div class="wrap">
<div class="box"></div>
</div>
<style>
.wrap {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
.box {
width: 200px;
height: 100px;
background-color: red;
}
</style>
利用 grid 布局的水平垂直居中
方法一:父元素設(shè)置 display: grid; justify-items: center; align-items: center;
方法二:父元素設(shè)置 display: grid;
,子元素設(shè)置 justify-self: center; align-self: center;
.wrap {
display: grid;
height: 100vh;
background-color: #ee3;
/* justify-items: center;
align-items: center; */
}
.box {
background-color: #c9c;
width: 100px;
justify-self: center;
align-self: center;
}