CSS中百分比是相对于谁?

本文详细介绍了CSS中百分比布局的原理及应用,包括不同属性如何使用百分比值,containing block的概念及其对元素尺寸的影响,并解释了特殊情况下百分比值的计算方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 用到百分比的属性:

  1. width, height
  2. margin, padding
  3. top, right, bottom, left
  4. transform - translate
  5. background-position, background-size

2. containing block

2.1 为什么要知道containing block

MDN:

The size and position of an element are often impacted by its containing block. Most often, the containing block is the content area of an element's nearest block-level ancestor, but this is not always the case. In this article, we examine the factors that deterime an element's containing block.

所以百分比都是相对于其containing block来计算的

2.2 containing block的定义

翻译自MDN:

containing block的定义和元素的postion属性有关:

  1. static 或 relative时:

    最近的__block container__(比如inline-block, block, list-item)或者创建了__formatting context__(比如table container, flex container, grid container或block container)的祖先元素的__context box__

  2. absolute:

    最近的position属性不是static的祖先元素的__padding box__

  3. fixed:

    窗口

  4. 特殊情况, fixed或absolute时, 当其父元素有以下情况出现时, containing block为其父元素的__padding box__:

    1). transformperspective属性的值不是none

    2). will-change属性的值是transformperspective

    3). filter属性不是nonewill-change属性的值是filter(只在Firefox中有效)

3. 如何计算

  1. height, top, bottom根据其containing block的height进行计算, 如果该height没有指定(根据内容自适应), 那么计算值为0
  2. width, left, right, padding, margin根据其containing block的width进行计算
  3. transform - translate, translateX, translateY, 根据__自身元素__的实际宽度计算
  4. background:

    4.1 background-position根据__自身元素(不是containing block)__的宽高计算

    4.2 background-size根据图片的大小进行计算. 需要注意的时, 当使用单个百分比(比如background-size: 50%;)计算时, height会隐式设为auto, 当其height计算出来的值大于容器的高度时, 超出部分会隐藏. 如果需要全部显示, 需要明确设置宽和高的值(比如, background-size: 50% 50%;)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值