skip to Main Content

I’ve got a more theoretical problem. Im perplexed why the width of a div element does not change after I specifically specify it in the class selector ".blue-box".

In the ".float-container div" selector, I have specified the width of a box of 100px, but the ".blue-box" selector does not overwrite it, even though it is a child element of a ".float-container div" selector

<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;
}

I know how to bypass it. Im just interested in the theory behind it.I am confused why the blue-box inherits the 100px width and does not apply its own 330px width. I know that class is more specific than the div element, so where is the problem?

2

Answers


  1. It’s not inheriting the width. The blue box is a subject of the .float-container div selector, which has specificity (0, 1, 1) which beats the specificity of .blue-box which is (0, 1, 0).

    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search