Is box sizing inherited if declared inside universal selector?

淺唱寂寞╮ 提交于 2020-01-14 06:18:05

问题


Does this get applied by every element?

EXAMPLE 'A':

*
{
    box-sizing: border-box;
}

I thought box-sizing is not inherited?

This is in regards to box sizing reset:

EXAMPLE 'B':

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

html
{
    box-sizing: border-box;
}

Will both examples have the same effect?


回答1:


I thought box-sizing is not inherited?

No, it's not. You can check the specification and you will see that inherited is NO. In the example A, you are simply using the universal selector to select all the elements and applying box-sizing:border-box to them but it doesn't target pseudo element so they will not have box-sizing:border-box set by default.

Will both examples have the same effect?

No they won't. Even if we consider that it's the only CSS applied to your document, the example B will also target pseudo element to make the inherit the box-sizing and if we follow the parent-child structure they will logically get box-sizing:border-box since html is having box-sizing:border-box.

The other difference is that using inherit will consider the parent style unlike explicitely setting the value in the example A. In the example A, you have to change box-sizing for each element if you want to override the one set by your code while in the example B, changing box-sizing on the element OR any ancestor will override the code you are using.


A basic example to illustrate the difference.

Using A:

* {
  box-sizing: border-box;
}



/* my code*/
body {
  box-sizing: content-box;
}
.box {
  width:100px;
  height:100px;
  border:10px solid;
  padding:10px;
}

p {
  padding:5px;
  border:2px solid red;
}
<div class="box">
  <p></p>
</div>

Using B:

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

html {
  box-sizing: border-box;
}


/* my code*/

body {
  box-sizing: content-box;
}

.box {
  width: 100px;
  height: 100px;
  border: 10px solid;
  padding: 10px;
}

p {
  padding: 5px;
  border: 2px solid red;
}
<div class="box">
  <p></p>
</div>



回答2:


Yes. To confirm with a test:

* {
  box-sizing: border-box;
}

.example {
  border: 1px solid red;
  background: blue;
  width: 100px;
  height: 100px;
  padding: 20px;
}

.border-box {
  box-sizing: border-box;
}

.content-box {
  box-sizing: content-box;
}
<body>
  <div class="example"></div>
  <div class="example content-box"></div>
  <div class="example border-box"></div>
<body>

The div that does not have the .border-box class still inherits its box-sizing from body.



来源:https://stackoverflow.com/questions/59495417/is-box-sizing-inherited-if-declared-inside-universal-selector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!