这篇笔记是根据小薇导师提供的参考资料完成的
附上原网址:https://css-tricks.com/centering-css-complete-guide/
1.水平居中
for inline, inline-block, inline-table, inline-flex……
(前提:该元素的父元素为块级元素)
element {
text-align: center;
}
for block-level elements(前提:该元素的width值确定)
element {
margin: 0 auto;
}
for 两个及以上的块级元素需要在一行中居中显示
parent element {
text-align: center;
}
element {
display: inline-block;
}
2 .垂直居中
(当该元素的父元素高度确定时)
for inline, inline-block, inline-table, inline-flex……
- for 单行
- 该元素的padding-top值=该元素的padding-bottom值
- 该元素的line-height值=该元素的height值
- for 多行
- 该元素的padding-top值=该元素的padding-bottom值
- display: table-cell(前提该元素的height值确定)
parent element { display: table; } element { display: table-cell; vertical-align: middle; }
使用flexbox(前提该元素的父元素height值确定
parent element { display: flex; flex-direction: column; justify-content: center; }
在该元素的父元素前创建一个垂直校准元素
parent element { position: relative; } parent element::before { content: " "; height: 100%; width: 1%; display: inline-block; vertical-align: middle; } element { display: inline-block; vertical-align: middle; }
for block-level element
该元素的height值确定
parent element { position: relative; }
element {
position: absolute;
top: 50%;
height: 100px;
margin-top: -50px; /* account for padding and border if not using box-sizing: border-box; */
}
该元素的height值不确定
parent element { position: relative; } element { position: absolute; top: 50%; transform: translateY(-50%); }
使用flexbox
parent element { display: flex; flex-direction: column; justify-content: center; }
3 .水平垂直居中
该元素的width值、height值确定
- 方法一
parent element { position: relative; } element { width: 300px; height: 100px; padding: 20px; position: absolute; top: 50%; left: 50%; margin: -70px 0 0 -170px; /* account for padding and border if not using box-sizing: border-box; */ }
margin值的计算方法
margin-top = -( height/2 + padding-top+ border-top-width )
margin-right = 0
margin-bottom = 0
margin-left = -( width/2+ padding-left + border-left-width ) - 方法二
element { position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; }
该元素的width值、height值不确定
parent element {
position: relative;
}
element {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
使用flexbox
parent element {
display: flex;
justify-content:
center; align-items: center;
}
转载自http://ife.baidu.com/note/detail/id/1085