7.3尺寸与适配系列——盒子的宽、高、padding、margin、background背景范围、line-height、font-size

140 阅读3分钟

本人已参与新人「创作礼活动」,一起开启掘金创作之路。

position 定位会产生影响,是否脱离文档流,包含块;position: static | relative 包含块为父元素;其他定位方式,其包含块为具有定位的最近的祖先元素

  • 百分比,如:80%
  • 倍数 如:1.5
  • 是相对于包含块content内容区的大小
  • 额外补充: vertical-align的百分比值不是相对于字体大小或者其他什么属性计算的,而是相对于line-height计算的
{
  line-height: 30px;
  vertical-align: -3px;    /* 30 * -10% = -3 */  
}

二、宽/高

  • 宽/高: 其包含块宽高的百分比 width*80%height*80%

image.png

.box { width: 200px; height: 200px;  border: 5px dashed gold; box-sizing: border-box;}
.box1 { width: 80%; height: 50%; background-color: lightgreen; }

<div class="box">
    <div class="box1"></div>
</div>

二、padding/margin

均左、右、上、下均等于包含块宽度的百分比 width*80%

image.png

image.png

.box { width: 300px; height: 200px; border: 5px dashed gold; box-sizing: border-box;}
.box1 { 
        width: 50px; height: 50px; 
        margin: 10%; padding: 10%; 
        background-color: lightgreen; 
      }

三、background 背景范围

background-clip: border-box (默认值);
background-origin: padding-box (默认值);
background-size: 50% 25% 背景图片的大小相对背景区的百分比
background-repeat: roud(缩放) | space(均匀分布)
background-attachment: 决定背景图像的位置是在视口内固定,或者随着包含它的区块滚动。fixed——背景相对于视口和包含块均不跟随滚动;local——背景相对于视口和包含块跟随滚动;scroll——背景相对于视口跟随滚动,相对于包含块不跟随滚动;
background-position: 25% 75% 表示图像上的左侧 25% 和顶部 75% 的位置将放置在距容器左侧 25% 和距容器顶部 75% 的容器位置,两个点发生重叠

image.png

.box { width: 300px; height: 200px; padding: 10px; border: 5px dashed gold; box-sizing: border-box;}
.box1 { 
    width: 100px;
    height: 100px;
    border: 5px solid rgba(0, 0, 0, 0.1);
    padding: 5px;
    background-color: red;
    /* background-clip: border-box; 默认值 */
    /* background-clip: padding-box; */
    background-clip: content-box;
}

<div class="box">
    <div class="box1"></div>
</div>

image.png

.box { width: 300px; height: 200px; padding: 10px; border: 5px dashed gold; box-sizing: border-box;}
.box1 { 
    width: 100px;
    height: 100px;
    border: 5px solid rgba(0, 0, 0, 0.1);
    padding: 5px;
    background-image: url('./2.webp');
    /* background-repeat: no-repeat; 会导致background-clip强制变为padding-box */
    background-repeat: no-repeat;
    background-size: 50% 80%;
    background-clip: border-box;
}

四、line-height 与 font-size

image.png

  • font-size 继承父元素大小乘以百分比;有百分比、无倍数;决定容器空间大小的是line-height,而不是font-size见下图一

  • line-height倍数、百分比、em,都是根据元素自身font-size字体的大小计算的;当没有显式的写出line-height时,子元素的行高会继承父元素的行高,当显式的写出来时,倍数、百分比、em的计算优先

  • line-heightfont-size的关系,当font-size大于line-height时,即行间距为负值,文字会杂糅在一起;见下图二

  • line-heightheight的关系,在给定元素高度时,高度等于行高,文字会垂直居中。当行高值减小时,字体会向上运动。当行高值增大时,字体会向下运动。见下图三

  1. 图一 image.png
.test1{font-size:20px; line-height:0; border:1px solid #cccccc; background:#eeeeee;}
.test2{font-size:20px; line-height:20px; border:1px solid #cccccc; background:#eeeeee;}
  1. 图二 image.png

  2. 图三 image.png