• 重新认识布局:百分比单位


    本文首发于知乎:https://www.zhihu.com/people/xiao-chong-10-60

    布局中,常见单位,除了px,还有百分比。那么写不同地方的百分比代表什么呢?

    看一个选择题:

    margin-top:50%,这里的百分比是参考谁的?

    A、盒子自身的宽

    B、盒子自身的高

    C、父盒子的宽

    D、父盒子的高

     

    你的答案是?心里默念,答案解析在文末。

    1.参考父级盒子大小的情况

    width和height都会参考父级盒子的宽和高。准确的讲,会参考父盒子盒子模型里内容的宽和高。

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
    	<meta charset="UTF-8">
    	<meta http-equiv="X-UA-Compatible" content="IE=edge">
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    	<title>Document</title>
    	<style>
    		.father {
    			 600px;
    			height: 400px;
    			padding: 100px;
    			background-color: skyblue;
    		}
    
    		.son {
    			/* 子盒子的大小是:300px*200px。跟100px的padding没关系 */
    			 50%;
    			height: 50%;
    			background-color: pink;
    		}
    	</style>
    </head>
    
    <body>
    	<div class="father">
    		<div class="son"></div>
    	</div>
    </body>
    
    </html>
    

      子绝父相,绝对定位里的子盒子,边偏移left,top等也会参考父盒子的大小,具体来讲,水平方向的left,right值会参考父盒子的宽,竖直方向的top,bottom会参考父盒子的高。

    2.参考盒子自身大小的情况

    圆角边框border-radius和2d转换位移的translate()函数里的百分比,参考盒子自身的大小。

    圆角边框border-radius有8个值,横向上参考盒子自身的宽,纵向上参考盒子自身的高。

    参见下面的例子:最终的结果是一个椭圆。如果只是参考宽,那么结果是横向和纵向上的圆角值相等,会是一个圆角矩形而不是椭圆。实际上,这个椭圆的长轴就是宽,纵轴是高。

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
    	<meta charset="UTF-8">
    	<meta http-equiv="X-UA-Compatible" content="IE=edge">
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    	<title>Document</title>
    	<style>
    		div {
    			 600px;
    			height: 200px;
    			background-color: skyblue;
    			border-radius: 50%;
    		}
    	</style>
    </head>
    
    <body>
    	<div></div>
    </body>
    
    </html>
    

      

    3.盒子模型里的margin,padding会参考父盒子的宽

    margin,padding写百分比,会参考父盒子的宽,跟父盒子的高没关系。这点确实匪夷所思。

    回答文章前面提出的问题:答案是margin-top:50%,这个百分比是参考父盒子的宽,答案是C。

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
    	<meta charset="UTF-8">
    	<meta http-equiv="X-UA-Compatible" content="IE=edge">
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    	<title>Document</title>
    	<style>
    		.father {
    			 600px;
    			height: 200px;
    			background-color: skyblue;
    		}
    
    		.son {
    			margin: 50%;
    		}
    	</style>
    </head>
    
    <body>
    	<div class="father">
    		<div class="son"></div>
    	</div>
    </body>
    
    </html>
    

      

  • 相关阅读:
    nginx http和https共存
    jQuery prop方法替代attr方法
    idea内置tomcat中java代码热更新
    Linux磁盘空间查看、磁盘被未知资源耗尽
    Mysql order by与limit混用陷阱
    IIS 架构解析
    asp.net MVC 应用程序的生命周期
    Linq专题之var关键字
    ThoughtWorks 2016年第1期DNA活动总结
    对象的深拷贝--反射
  • 原文地址:https://www.cnblogs.com/xiaochongchong/p/14930645.html
Copyright © 2020-2023  润新知