当使用 top, right, bottom, left
css
值时,为什么有时我可以使用百分比,但有时我必须使用像素 ( px
),否则 元素
不会响应。
例如(在给定元素上):
top: 25%
- 没有响应
top: 150px
- 有效
我通常会使用百分比而不是像素 (px
) 来保持响应,但为什么百分比 (%
) 有时不起作用?每种情况在什么情况下效果最好?谢谢。
最佳答案
根据 the WC3 specification对于百分比单位 ( <percentage>
( ref )):
Percentage values are always relative to another value, for example a length unit.
长度单位 ( <length>
( ref )) 是一种 CSS 数据类型,表示距离值,或以相对 ( em
) 或绝对 ( px
) 长度单位定义的值。
百分比单位 ( <percentage>
( ref )) 是一种表示百分比值的 CSS 数据类型。
top: 50%
)值,则在嵌套元素上使用的百分比单位(例如:height: 200px
)将不适用已定义,因为百分比值总是相对于另一个值。
可以在下面嵌入的代码片段中观察到这种行为。
代码片段演示:
.fixed-height {
height: 200px;
background: #4cbd2f;
}
.auto-height {
background: #d04f38;
}
.nested {
top: 50%;
position: relative;
}
hr {
border: 2px dashed #d4d4d4;
margin: 25px 0px;
}
.fixed-height, .auto-height {
padding: 10px;
box-sizing: border-box;
border: 2px dashed rgba(0, 0, 0, 0.3);
}
<h3>Fixed Height</h3>
<h4><code>height: 200px</code></h4>
<div class="fixed-height">
<div class="nested"><code>top: 50%</code></div>
</div>
<hr>
<h3>Auto Height</h3>
<h4><code>height: auto</code></h4>
<div class="auto-height">
<div class="nested"><code>top: 50%</code></div>
</div>
如上面的代码片段所示,百分比值 将取决于长度值。因此,尽管两个嵌套元素都有一个 top
50%
的属性(property)声明,只有嵌套在包含元素中的元素带有 height
使用 length 值明确定义的属性将产生预期的行为。
Note: Although
<percentage>
values are also CSS dimensions, and are usable in some of the same properties that accept<length>
values, they are not themselves<length>
values. ref
Note: Only calculated values can be inherited. Thus, even if a percentage value is used on the parent property, a real value (such as a width in pixels for a
<length>
value) will be accessible on the inherited property, not the percentage value. ref
关于css - 使用 'px' 与 '%' 时顶部、右侧、底部、左侧 css 值的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47580928/