Last active
February 1, 2018 03:38
-
-
Save simonid/319e46fc0cc7fa0079c6a6e117389579 to your computer and use it in GitHub Desktop.
CSS笔记
.parent{
position : relative;
}
.child{
position : absolute;
left : 50%;
transform : translateX(-50%);
}
.parent{
display : flex;
jueify-content : center;
}
适用于子元素为浮动、绝对定位、内联元素,均可水平居中
常见的内联元素有:span
、a
、img
、input
、label
等
.parent{
text-align : center;
}
该方法通用适用于display:inline-block
的元素
常见的块元素有:div
、h1~h6
、table
、p
、ul
、li
等
.parent{
width : 100%;
}
.child{
width : 600px;
height : 50px;
margin : 0 auto;
background : #555;
}
该方法只能进行水平居中,对浮动元素或绝对定位元素无效
.parent{
text-align : center;
}
.child{
display : inline-block;
}
.child{
width : 100px;
float : left;
position : relative;
left : 50%;
margin-left : -50px;
}
.parent{
position : relative;
}
.child{
position : absolute;
width : 100px;
left : 50%;
margin-left : -50%;
}
.parent{
position : relative;
}
.child{
position : absolute;
width : 100px;
left : 0;
right : 0;
margin : 0 auto;
}
.parent{
position : relative;
}
.child{
position : absolute;
top : 50%;
transform : translateY(-50%);
}
.parent{
display : flex;
align-items : center;
}
适用于子元素浮动、绝对定位、内联元素
.text{
line-height : 200px;
height : 200px;
}
将文字的line-height
属性设置为其父容器的高度,适用于单行文字
.parent{
position : relative;
}
.child{
position : absolute;
top : 50%;
height : 100px;
margin-top : -50px;
}
.parent{
position : relative;
}
.child{
position : absolute;
top : 0;
bottom : 0;
height : 100px;
margin : auto 0;
}
div{
width : 100px;
height : 100px;
margin : auto;
position : fixed;
top : 0;
right : 0;
bottom : 0;
left : 0;
}
优点:
- 不仅可以实现在正中间,还可以在正左方、正右方
- 元素的宽高支持百分比%属性值和min-/max-属性
- 可以封装为一个公共类,可作为弹出层
- 兼容性好
.child{
width : 100px;
height : 100px;
position : absolute;
top : 50%;
left : 50%;
margin-left : -50px;
margin-top : -50px;
}
特点:
- 兼容性好,兼容IE6/7
- 灵活性差,不能自适应,宽高不支持百分比和min-/max-属性
.child{
width : 100px;
height : 100px;
position : absolute;
top : 50%;
left : 50%;
transform : translate(-50%,-50%);
}
特点:
- 内容可自适应,可以封装为一个公共类,可以做弹出层
- 可能干扰其他transform效果
.parent{
display : flex;
justify-content : center;
align-items : center;
}
这种方式是css布局的趋势
.parent{
display : table-cell;
vertical-align : middle;
text-align : center;
width : 200px;
height : 200px;
border : 1px solid red;
}
.child{
width : 100px;
height : 100px;
display : inline-block;
background-color : #424;
}
适用于子元素display:inline-block、inline
类型的元素,需要已知父元素宽高,且父元素宽高不能设置百分比
.parent {
font-size: 175.4px;
height: 200px;
text-align: center;
}
.child {
vertical-align: middle;
display: inline-block;
font-size: 12px;
width: 50px;
height: 50px;
background-color: #00f;
}
该方法的要点是给父元素设一个合适的 font-size 的值,这个值的取值为该父元素的高度除以 1.14 得到的值,并且子元素必须 是一个 inline 或 inline-block 元素,需要加上 vertical-align: middle 属性。
使用这种方法,子元素的宽度或高度都不必知道
text {
height: 100px;
line-height: 100px;
text-align: center;
}
参考自:
知乎-详解 CSS 居中布局技巧
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment