使用 'px' 与 '%' 时顶部、右侧、底部、左侧 css 值的行为

Behavior of top, right, bottom, left css values when using 'px' vs '%'

当使用 top, right, bottom, left css 值时,为什么有时我可以使用百分比,但有时我必须使用像素 (px),或者 element 不会回应。

例如(在给定元素上):

top: 25% - 没有反应

top: 150px - 有效

我通常会在像素 (px) 上使用百分比来保持响应,但为什么百分比 (%) 有时不起作用?每种情况在什么情况下效果最好?谢谢。

尝试:

.example {
    margin-top: 10px;
    display:inline-block;
}

这有时为我解决了问题。您显然需要对其进行配置以满足您的需求,但通过添加 display:inline-block 通常可以解决问题。

根据the WC3 specification for percentage units (<percentage>(ref)):

Percentage values are always relative to another value, for example a length unit.

一个长度单位(<length>(ref))是一个CSS数据表示 距离值 relative (em) 或 absolute[=70] 中定义的值的类型=] (px) 长度单位。

一个百分比单位(<percentage>(ref))是一个CSS数据表示 百分比值的类型 .

如果包含元素没有 长度单位[=70,则嵌套元素上使用的

百分比单位(例如: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 属性 of 50%,但只有嵌套在包含 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