Why can't I partially inherit CSS using shorthand?

From time to time, while looking through the stylesheets, I've seen rules such as:

padding: 10px inherit;

      

I didn't know if this was valid CSS, so I made 3 JSFiddles. All 3 scripts have a <p>

parent child <div>

(and have been tested in Chrome 59.0). In the first JSFiddle, the child inherits from the parent padding (one keyword inherit

), and checking the elements shows both <p>

and <div>

have 10px padding in both x and y directions:

div {padding: 10px 10px}
p {padding: inherit}

      

In the second JSFiddle, the child <p>

has both explicit inheritance and x and y (1 actual <length>

, 1 inherit

):

div {padding: 10px 10px}
p {padding: 10px inherit}

      

Checking <p>

shows that the CSS is broken (i.e. no overlay is inherited);

In the third JSFiddle (for completeness) the child <p>

also has both x and y explicitly inherited, but there are 2 separate inherit

keywords in this case :

div {padding: 10px 10px}
p {padding: inherit inherit}

      

and this CSS also breaks down for <p>

(i.e. no overlay inheritance)

I assume this means that children cannot "partially" inherit the values ​​of the parent property using the shorthand form. Is this correct, and if so, why can't it be partially inherited? (i.e. does the W3C docs mention this somewhere?).

UPDATE. If you strip the fill property explicitly (don't use shorthand) you can inherit CAN (see JSFiddle )

Given that I've seen case # 2 (second script) in multiple stylesheets, it looks like other developers also think that partial inheritance is valid.

+3


source to share


3 answers


The spec contains three parameters for the property unset

, all

and inherit

https://www.w3.org/TR/css3-cascade/#propdef-all It even says initial | inherit | unset

. This means these values ​​in the literal sense. Because it doesn't make sense to define backround:url('url.png') inherit;

. This is a hard-coded example of how the engine works internally. It's like defining partial importance, like padding:20px !important 10px;

. No you have to dopadding:!important 10px;



+2


source


While I don't know why this is so, you can do the following trick:



div {padding: 10px 10px}
p {
  padding: inherit;
  padding-bottom: 20px;
  padding-top: 20px;
}

      

0


source


You can independently set padding-top

, padding-bottom

, padding-left

and padding-right

:

* {
  box-sizing: border-box;
}
html, body {
  margin: 0;
}

.first-div {
  background-color: lightgreen;
  padding: 10px 20px;
}

.second-div {
  background-color: purple;
  color: #fff;
  display: inline-block;

  padding-top: 15px;
  padding-bottom: 5px;
  padding-left:inherit;
  padding-right: inherit;
}
      

<div class="first-div">
  <div class="second-div">something clever</div>
</div>
      

Run codeHide result


0


source







All Articles