使用边框时伪元素未充满容器宽度

Joh*_*ara 5 html css

我有一段 html/css 代表一个带边框的按钮。

该按钮具有覆盖按钮的伪元素 - 这个简单的示例显示了其中之一。

伪元素比原始元素高(使用 px 设置高度),但宽度相同(设置为 100%)。

在当前的设计中,有两个问题没有按照我的预期工作:

  1. 尽管使用了 box-sizing: border-box,伪宽度不包括边框。
  2. 伪元素是绝对定位的(顶部、左侧),但该参考位置位于父边框内。

这在 Chrome 和 Edge 中似乎是相同的,这表明我没有做正确的事情 - 然而,我对盒子大小特别困惑。

.container {
  padding: 50px;
}

.button {
  border: solid 4px red;
  box-sizing: border-box;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  height: 36px;
  padding: 0 16px;
  position: relative;
  z-index: 1;
}

.button::before {
  background-color: rgba(76, 255, 0, 0.8);
  box-sizing: inherit;
  content: "";
  display: block;
  position: absolute;
  top: -4px;
  left: 0;
  height: 44px;
  width: 100%;
  z-index: -1;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <a class="button">Button</a>
</div>
Run Code Online (Sandbox Code Playgroud)

Tem*_*fif 7

规格来看

元素框的位置和大小有时是相对于某个矩形(称为元素的包含块)来计算的。元素的包含块定义如下:

....

  1. 如果元素具有 'position:absolute',则包含块由最近的祖先建立,其 'position' 为 'absolute'、'relative' 或 'fixed',如下所示:
    1. 如果祖先是内联元素,则包含块是为该元素生成的第一个和最后一个内联框的填充框周围的边界框。在 CSS 2.1 中,如果内联元素被拆分为多行,则包含块未定义。
    2. 否则,包含块由祖先的填充边缘形成

然后

填充边缘围绕框填充。如果填充的宽度为 0,则填充边缘与内容边缘相同。四个填充边缘定义了框的填充框。

这解释了为什么您的元素在定位时不使用边框框作为参考,而是使用填充框。百分比宽度1也是如此。usingwidth:100%表示包含块的填充和内容。边界不计算在内。


关于box-sizing

... ,元素上指定的任何填充或边框都会在此指定的宽度和高度内进行布局和绘制。

因此,边框需要属于元素而不是父元素,以便考虑box-sizing哪一个不属于您的情况,因为边框不适用于伪元素:


1对于其包含块基于块容器元素的绝对定位元素,百分比是根据该元素的填充框的宽度计算的。参考

.box {
  border:5px solid;
  padding:10px;
  background:red;
  min-height:100px;
  position:relative;
}
span:first-child {
  display:inline-block;
  width:100%;
  background:blue;
}
span:last-child {
  position:absolute;
  bottom:0;
  left:0;
  width:100%;
  background:green;
}
Run Code Online (Sandbox Code Playgroud)
<div class="box">
  <span>I am a static element</span>
  <span>I am a absolute element</span>
</div>
Run Code Online (Sandbox Code Playgroud)

获得所需内容的一个想法是使用 inset box-shadow 而不是 border:

.container {
  padding: 50px;
}

.button {
  box-shadow: inset 0 0 0 4px red;
  box-sizing: border-box;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  height: 36px;
  padding: 0 16px;
  position: relative;
  z-index: 1;
}
.button::before {
  background-color: rgba(76, 255, 0, 0.8);
  box-sizing: inherit;
  content: "";
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  z-index: -1;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
    <a class="button">Button</a>
</div>
Run Code Online (Sandbox Code Playgroud)