css 关于div元素宽度的继承(特异性)问题

1u4esq0p  于 2023-02-14  发布在  其他
关注(0)|答案(2)|浏览(132)

我有一个更理论化的问题,我很困惑为什么div元素的宽度在我在类选择器". blue-box"中指定后没有改变。
在". float-containerdiv"选择器中,我指定了一个100px的框宽,但是". blue-box"选择器不会覆盖它,即使它是". float-containerdiv"选择器的子元素

<div class="float-container">
      <div class="red-box">Box 1</div>
      <div class="blue-box">Box 2</div>
      <div class="orange-box">Box 3</div>
      <div class="yellow-box">Box 4</div>
      <div class="green-box">Box 5</div>
      <div class="pink-box">Box 6</div>
    </div>
.float-container div {
  border: 2px solid;
  height: 75px;
  width: 100px;
}

.red-box {
  background: red;
}

.blue-box {
  background: rgba(0, 0, 255, 0.493);
  text-align: end;
  width: 330px;
}

.orange-box {
  background: orange;
}

.yellow-box {
  background: yellow;
}

.green-box {
  background: green;
}

.pink-box {
  background: pink;
}

我知道如何绕过它。我只是对它背后的理论感兴趣。我很困惑为什么蓝框继承了100px的宽度而不应用它自己的330px宽度。我知道那个类比div元素更具体,那么问题在哪里呢?

zwghvu4y

zwghvu4y1#

它没有继承宽度,蓝色的框是.float-container div选择器的主题,它的特异性(0,1,1)优于.blue-box的特异性(0,1,0)。

axzmvihb

axzmvihb2#

The styling from {.float-container div} has more specificity than that of {.blue-box}.
Look at it this way. Let's assume class selectors have a specificity of 10 and element selectors have a specificity of 1. 
Then {.float-container div} would have a specificity of 10 + 1 = 11 because it contains both class and element selectors while {.blue-box} would have a specificity of just 10.
You can reference this article if you need more explanations.
https://medium.com/code-writers/understanding-compound-selectors-and-why-to-avoid-them-in-css-d969e60b71dc

相关问题