CSS 盒子模型|青训营笔记

91 阅读1分钟

这是我参与【第五届青训营】伴学笔记创造活动的第3天

盒子模型

盒子模型.jpg

  • width

    • 指定content box 宽度
    • 取值为长度、百分数、auto
    • auto 由浏览器根据其它属性确定
    • 百分数相对于容器的centent box 宽度
  • height

    • 指定content box 高度
    • 取值为长度、百分数、auto
    • auto 由内容计算得来
    • 百分数相对于容器的centent box 高度
    • 容器有指定的高度时,百分数才生效
  • padding

    • 指定元素四个方向的内边距
    • 百分数相对于容器宽度
    • 四个值时分别为(上、右、下、左)(顺时针) padding.jpg
  • border

    • 指定容器边框样式、粗细和颜色
    • 三种属性:
      • border-width
      • border-style
      • border-color
    • 四个方向:
      • border-top
      • border-right
      • border-bottom
      • border-left
  • margin

    • 指定元素四个方向的外边距
    • 取值为长度、百分数、auto
    • 百分数相对于容器宽度
    • 使用margin:auto水平居中
      <style>
      div {
          width: 200px;
          height: 200px;
          background: coral;
          margin-left: auto;
          margin-right: auto;         <!-- 左右边距相等,水平居中 -->
        }                    
      </style>
      
    • margin collapse 外边距重叠
      • 块的上边距(margin-top)和下边距(margin-bottom)有时合并折叠为单个边距,其大小为单个边距的最大值(若相等,则取其中一个)。
      <div class="a"></div>
      <div class="b"></div>
      
      <style>
        .a {
          background: lightblue;
          height: 100px;
          margin-bottom: 100px;
        }
      
        .b {
          background: coral;
          height: 100px;
          margin-top: 100px;
        }
      </style>
      
  • box-sizing:border-box

    • 设置大小时,包含padding
    <p class="a">content box</p>
    <p class="b">border box</p>
    
    <style>
    .a {
      width: 100%;
      padding: 1em;
      border: 3px solid #ccc;
    }
    
    .b {
      box-sizing: border-box;
      width: 100%;
      padding: 1em;
      border: 3px solid #ccc;
    }
    </style> 
    
  • overflow 设置元素溢出时行为

    • overflow属性可以设置水平、垂直方向(即x,y轴)
      • overflow-x、overflow-y
    • 属性值:
      • visible 内容可能溢出到外部,不会剪裁。
      • hiddden 溢出时,不提供滚动条,内容剪裁。但可以编程的方式滚动。
      • scroll 无论是否溢出,总是显示滚动条
      • auto 若内容适应边距(padding)盒,则与visible相同,若溢出,则浏览器提供滚动条
      • overlay 与auto 相同,但滚动条绘制在内容上,不额外占据空间