Home > database >  Setting only two rows next to each other in a flexbox of four rows
Setting only two rows next to each other in a flexbox of four rows

Time:01-16

I am trying to place .itemtwo and .itemthree next to each other like you see here with boxes "aside 1" and "aside 2":

placing rows side by side

This is my HTML:

`<div >
  <div >test one</div>
  <div >test two</div>
  <div >test three</div>
  <div >test four</div>
</div>`

This is my CSS:

.wrapper {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.wrapper > div {
  border: 3px solid blue;
  flex: 1 100%;
}

.itemtwo,
.itemthree {
  flex: 1 1 auto;  
  color: red;
}

The interesting thing is that when I change the second declaration block .wrapper > div to .wrapper > * I get my desired effect. I don't understand why my .wrapper > div is not working.

CodePudding user response:

I believe this has something to do with the specificity of the selector. Targeting a tag should have higher priority than the class itself, and using the universal selector '*' will have the lowest priority.

What you could do if you still choose to go down this method is to use the !important exception to force the styling on .itemtwo and .itemthree, which I would not recommend! You can read more about it at this link https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity#:~:text=Inline styles added to an,as having the highest specificity.

.wrapper {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.wrapper > div  {
  border: 3px solid blue;
  flex: 1 100%;
}

.itemtwo,
.itemthree {
  flex: 1 1 auto !important;
  color: red;
}
<div >
  <div >test one</div>
  <div >test two</div>
  <div >test three</div>
  <div >test four</div>
</div>

CodePudding user response:

You are coming up against specificity.

.wrapper > div has higher specificity than .itemtwo and .itemthree

However .wrapper > * has lower specificity than .itemtwo and .itemthree

See MDN for a description of how specificity is calculated.

In your case * actually has no effect on specificity but the div does.

Here's a way of getting what you want using your code without recourse to using !important. This snippet adds a .wrapper to the .itemtwo and .itemthree to increase the specificity.

.wrapper {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.wrapper>div {
  border: 3px solid blue;
  flex: 1 100%;
}

.wrapper .itemtwo,
.wrapper .itemthree {
  flex: 1 1 auto;
  color: red;
}
<div >
  <div >test one</div>
  <div >test two</div>
  <div >test three</div>
  <div >test four</div>
</div>`

  • Related