相對於父元素寬度的:
[max/min-]width、left、right、padding、margin 等;
相對於父元素高度的:
[max/min-]height、top、bottom 等;
相對於繼承字號的:
font-size 等;
相對於自身字號的:
line-height 等;
相對於自身寬高的:
border-radius、background-size、transform: translate()、transform-origin、zoom、clip-path 等;
特殊算法的:
background-position(方向長度 / 該方向除背景圖之外部分總長度 * 100)、
filter 系列函數等;
例子1: margin子元素百分比 height子元素百分比
從圖中可以看出 content中的height:50% 是父元素的height 400*0.5=200px;
content的margin-top確是 父元素的width 600*0.25=150px;
例子2:line-height:相對於自身字號
原因:
line-height與height相等垂直居中原理可參見http://www.jianshu.com/p/6e4d683f6cf2
垂直水平居中的方法有很多,上面用了css3的新方法,利用flex,flex可以嵌套使用,這裏這樣即可簡單達到效果:
[max/min-]width、left、right、padding、margin 等;
相對於父元素高度的:
[max/min-]height、top、bottom 等;
相對於繼承字號的:
font-size 等;
相對於自身字號的:
line-height 等;
相對於自身寬高的:
border-radius、background-size、transform: translate()、transform-origin、zoom、clip-path 等;
特殊算法的:
background-position(方向長度 / 該方向除背景圖之外部分總長度 * 100)、
filter 系列函數等;
例子1: margin子元素百分比 height子元素百分比
<body>
<div class="box">
<div class="content">我要垂直居中</div>
</div>
</body>
div,body{
padding: 0;
margin: 0;
}
body{
background-color: darkgrey;
}
.box{
width: 600px;
height: 400px;
margin: 50px auto;
background-color: palegreen;
overflow: hidden;
}
.content {
width: 50%;
height: 50%; /*父元素的height 400*0.5*/
margin-top: 25%; /*margin-top用百分比用的是父元素的width 600*0.25=150*/
background-color: tomato;
}
從圖中可以看出 content中的height:50% 是父元素的height 400*0.5=200px;
content的margin-top確是 父元素的width 600*0.25=150px;
例子2:line-height:相對於自身字號
<body>
<div class="box">
<div class="content">我要垂直居中</div>
</div>
</body>
div,body{
padding: 0;
margin: 0;
}
body{
background-color: darkgrey;
}
.box{
width: 600px;
height: 400px;
margin: 50px auto;
background-color: palegreen;
display: flex;/*這裏用了css3的flex新特性垂直水平居中*/
justify-content: center;/*水平居中*/
align-items: center;/*垂直居中*/
}
.content {
width: 50%;
height: 20%;
line-height: 20%; /*這裏的line-height與height相等,使其垂直居中*/
vertical-align: middle;
text-align: center;
background-color: tomato;
}
原因:
line-height
的百分比是相對font-size的,所以你如果需要使用line-height
居中的話就使用絕對的px
值。line-height與height相等垂直居中原理可參見http://www.jianshu.com/p/6e4d683f6cf2
垂直水平居中的方法有很多,上面用了css3的新方法,利用flex,flex可以嵌套使用,這裏這樣即可簡單達到效果:
div,body{
padding: 0;
margin: 0;
}
body{
background-color: darkgrey;
}
.box{
width: 600px;
height: 400px;
margin: 50px auto;
background-color: palegreen;
display: flex;/*這裏用了css3的flex新特性垂直水平居中*/
justify-content: center;/*水平居中*/
align-items: center;/*垂直居中*/
}
.content {
width: 50%;
height: 20%;
display: flex;
justify-content: center;
align-items: center;
background-color: tomato;
}