元素竖向的百分比设定是相对于容器的宽度or高度

相对于父元素宽度的:
[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;
		}







  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值