关于css:css中width的小九九
<article class=“article fmt article-content”><h4>一、width话题引入</h4><p>width属性定义元素内容区的宽度,在内容区里面能够减少内边距、边框和外边距。那别离设置 width:auto、width:100% 有什么区别呢?设置box-sizing: border-box对元素宽度有什么影响?</p><h4>二、代码demo</h4><pre><code><!DOCTYPE html><html lang=“en”> <head> <meta charset=“UTF-8” /> <meta name=“viewport” content=“width=device-width, initial-scale=1.0” /> <title>css中width的小九九</title> </head> <style> .parent { width: 500px; height: 560px; background-color: #fff; border: 10px solid #eee; padding: 20px; } .child { background-color: #ccc; border: 10px solid #eee; margin: 20px; height: 100px; text-align: center; } .child2 { width: auto; } .child3 { width: 100%; } .child4 { width: 100%; box-sizing: border-box; } </style> <body> <div class=“parent”> parent <div class=“child child1”>child1: default</div> <div class=“child child2”>child2: width:auto</div> <div class=“child child3”>child3: width:100%</div> <div class=“child child4”>child4: width:100% 并且 box-sizing:border-box</div> </div> </body></html></code></pre><p></p><h4>三、剖析</h4><ol><li>child1:宽度默认auto,和child2统一<br/><br/></li><li>child2:设置width:auto<br/><br/> 最终宽度:document.getElementsByClassName(‘child2’)[0].clientWidth = 440<br/> <strong>即</strong> 500(父元素宽度) - 20(子元素margin)∗2 - 10(子元素border)∗2 = 440<br/><br/></li><li>child3:设置width:100%<br/><br/> 最终宽度:document.getElementsByClassName(‘child3’)[0].clientWidth = 500<br/> <strong>即</strong> 500(父元素宽度)<br/><br/></li><li><p>child4:设置width:100%; box-sizing: border-box;</p><pre><code>box-sizing:border-box;盒子width = 内容的宽度 + padding + border盒子height = 内容的高度 + padding + borderbox-sizing:content-box;盒子width = 内容的宽度盒子height = 内容的高度</code></pre><p><br/>最终宽度:document.getElementsByClassName(‘child4’)[0].clientWidth = 480<br/><strong>即</strong> 500 - 子元素padding - 子元素border = 子元素width</p></li></ol><h4>四、论断</h4><ul><li>width:auto 是子元素的 content + padding + border + margin 撑满父元素的 content。<br/><br/></li><li>width:100% 是子元素的 content 撑满父元素的 content。<br/><br/></li><li>在开发中尽量抉择设置 width: auto,防止子元素设置 padding、border、margin等导致子元素溢出父元素。<br/><br/></li><li>在开发中能够抉择在根元素设置 box-sizing:border-box</li></ul></article> ...