Say I have this html :
<div >
<div ></div>
<div ></div>
<div ></div>
</div>
Currently if I want to get the second sub-div, I can do this :
.div .sub-div:nth-child(2) {
attribute: value;
(...)
}
Now, if I want the extra sub-div, I can do this :
.div .extra-sub-div {
attribute: value;
(...)
}
Now let's assume the attribute and value of the css is the same for all.
Something like :
width: 80px;
What is the css to write to gather all these div in one, instead of writing multiple css like this :
1.
.div .sub-div:nth-child(1) {
width: 80px;
}
.div .sub-div:nth-child(2) {
width: 80px;
}
.div .extra-sub-div {
width: 80px;
}
?
CodePudding user response:
div >
.div > div {
color: red;
width: 80px;
}
<div >
<div >1</div>
<div >2</div>
<div >3</div>
</div>
Ends with '-div':
div[class$="-div"] {
color: green;
width: 80px;
background: yellow;
}
<div >
<div >1</div>
<div >2</div>
<div >3</div>
<div >4</div>
</div>
CodePudding user response:
You can use ,
for each element you need like:
.div .sub-div:nth-child(1), .div .sub-div:nth-child(2), .div .extra-sub-div {
width: 80px;
color:red;
}
<div >
<div >1</div>
<div >2</div>
<div >3</div>
</div>
CodePudding user response:
When you group CSS selectors, you apply the same styles to several different elements without repeating the styles in your stylesheet. Instead of having two, three, or more CSS rules that do the same thing (set the width of something to 80px, for example), you use a single CSS rule that accomplishes the same thing.
To group CSS selectors in a style sheet, use commas to separate multiple grouped selectors in the style.
.div .sub-div:nth-child(1), .div .sub-div:nth-child(2), .div .extra-sub-div {
width: 80px;
}
CodePudding user response:
The question is not so clear.
I assume the most appropriate for you is to select the first level of of divs like:
.div > div {
width: 80px;
}
or if you want the first three items
.div div:nth-child(-n 3) {
width: 80px;
}
Anyway, there are a lot of sites which can help you with tips in css: ex:
https://css-tricks.com/useful-nth-child-recipies/
CodePudding user response:
.div div{
width: 80px;
}
This CSS will select .div .sub-div:nth-child(1), .div .sub-div:nth-child(2), .div .extra-sub-div with
CodePudding user response:
I would personally just add another class into the child div
-elements, separated with a space. This way you're not targetting all of the child div
-elements, but only the ones with this exact class.
This is good if you have child elements in the parent div
and you don't want them to have the styling from the .red-class
-class:
.red-class {
color: red;
}
<div >
<div >text</div>
<div >text</div>
<div >text</div>
<div >text</div>
</div>