2

I'm basically trying to make a element looking "disabled" by adding an after element with a white opaque filter exactly on top of it.

Problem is, just by setting width and height to 100% it does not include the parent's border!

How can I solve this? I need the after element to sit exactly on top of its parent

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>
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Mojimi
  • 2,561
  • 9
  • 52
  • 116

2 Answers2

1

Adjust the size and position by the amount of the borders using calc.

CSS Custom Properties would be ideal here.

* {
  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>
Paulie_D
  • 107,962
  • 13
  • 142
  • 161
0

You could set a negative margin equal to the border and use CSS calc function in the after element, like this:

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;
}
Fel
  • 4,428
  • 9
  • 43
  • 94