【问题标题】:Absolute child element with size equal to parent's size plus borders大小等于父级大小加上边框的绝对子元素
【发布时间】:2020-04-07 14:45:32
【问题描述】:

我基本上是想通过添加一个带有白色不透明过滤器的 after 元素来使元素看起来“禁用”。

问题是,只是将宽度和高度设置为 100%,它不包括父边框!

我该如何解决这个问题?我需要 after 元素恰好位于其父元素之上

div {
  border: 5px solid blue;
  position: relative;
  padding: 1rem;
  background-color: blue;
  text-align: center;
  font-size: 120%;
  font-family: sans-serif
}

div::after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: white;
  opacity: 0.6;
  z-index: 2;
}
<div>Test</div>

【问题讨论】:

标签: html css


【解决方案1】:

使用calc根据边框的数量调整大小和位置。

CSS 自定义属性在这里是理想的。

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

 ::before,
 ::after {
  box-sizing: inherit;
}

:root {
  --bdr: 5px;
}

div {
  border-style: solid;
  border-color: blue;
  border-width: var(--bdr);
  position: relative;
  padding: 1rem;
  background-color: grey;
  text-align: center;
  font-size: 120%;
  font-family: sans-serif;
  width: 80%;
  margin: 1em auto;
}

div::after {
  content: "";
  position: absolute;
  width: calc(100% + ( 2 * var(--bdr)));
  height: calc(100% + ( 2 * var(--bdr)));
  top: calc(var(--bdr) * -1);
  left: calc(var(--bdr) * -1);
  background-color: red;
  opacity: 0.6;
  z-index: 2;
}
<div>
  Test
</div>

【讨论】:

    【解决方案2】:

    您可以将负边距设置为等于边框,并在after 元素中使用 CSS calc 函数,如下所示:

    div::after {
      content: "";
      position: absolute;
      width: calc(100% + 10px);
      height: calc(100% + 10px);
      top: -5px;
      left: -5px;
      background-color: white;
      opacity: 0.6;
      z-index: 2;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 2014-12-29
      相关资源
      最近更新 更多