关于css:css中width的小九九

7次阅读

共计 1544 个字符,预计需要花费 4 分钟才能阅读完成。

一、width 话题引入

width 属性定义元素内容区的宽度,在内容区里面能够减少内边距、边框和外边距。那别离设置 width:auto、width:100% 有什么区别呢?设置 box-sizing: border-box 对元素宽度有什么影响?

二、代码 demo

<!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>

三、剖析

  1. child1:宽度默认 auto,和 child2 统一
  2. child2:设置 width:auto

    最终宽度:document.getElementsByClassName(‘child2’)[0].clientWidth = 440
    500(父元素宽度) – 20(子元素 margin)∗2 – 10(子元素 border)∗2 = 440

  3. child3:设置 width:100%

    最终宽度:document.getElementsByClassName(‘child3’)[0].clientWidth = 500
    500(父元素宽度)

  4. child4:设置 width:100%; box-sizing: border-box;

    box-sizing:border-box;
    盒子 width = 内容的宽度 + padding + border
    盒子 height = 内容的高度 + padding + border
    
    box-sizing:content-box;
    盒子 width = 内容的宽度
    盒子 height = 内容的高度 

    最终宽度:document.getElementsByClassName(‘child4’)[0].clientWidth = 480
    500 – 子元素 padding – 子元素 border = 子元素 width

四、论断

  • width:auto 是子元素的 content + padding + border + margin 撑满父元素的 content。
  • width:100% 是子元素的 content 撑满父元素的 content。
  • 在开发中尽量抉择设置 width: auto,防止子元素设置 padding、border、margin 等导致子元素溢出父元素。
  • 在开发中能够抉择在根元素设置 box-sizing:border-box
正文完
 0