Yao Zhao
Yao Zhao

Reputation: 4613

How to set style on an element after setting `all: initial;` on it?

I have a box, to prevent it and its children from inheriting properties from outside world, I set all: initial; on the box. But with this setting, I can't set other styles on it anymore.

<html>
<head>
<style>
.outer {
  color: red;
}
.inner {
  all: initial;
  background: blue;
}
</style>
</head>
<body>
<div class="outer">
  <div class="inner">
    <p>yes</p>
  </div>
</div>
</body>
</html>

In the example above, what I expect is the background is blue but font color is black(initial)

Upvotes: 2

Views: 335

Answers (1)

Temani Afif
Temani Afif

Reputation: 272955

it's because all:initial will also set display to initial which is inline so you will end having a block element (p) inside an inline one (div). You need to add display:block

<html>
<head>
<style>
.outer {
  color: red;
}
.inner {
  all: initial;
  display:block;
  background: blue;
}
</style>
</head>
<body>
<div class="outer">
  <div class="inner">
    <p>yes</p>
  </div>
</div>
</body>
</html>

The coloration was working fine but the output is not the intented one. Some padding will show this:

<html>
<head>
<style>
.outer {
  color: red;
}
.inner {
  all: initial;
  padding:5px;
  background: blue;
}
</style>
</head>
<body>
<div class="outer">
  <div class="inner">
    <p>yes</p>
  </div>
</div>
</body>
</html>

Related: Is it wrong to change a block element to inline with CSS if it contains another block element?

Upvotes: 4

Related Questions