I have an html structure like this:
<div class='parent'>
<div class='row'>
<div class='button'>
button
</div>
<div class='button'>
button
</div>
</div>
<div class='row'>
<div class='button'>
button
</div>
<div class='button'>
button
</div>
</div>
</div>
so we have parent -> row -> button, 1 parent, 2 rows, each row has 2-4 buttons. is there a css selector I can use (like nth-child) but that treats all buttons as siblings (even if they're in different rows)? Something like:
.parent .child:nth-child(randomNum) {
}
where randomNum is a number between 1 and numOfTotalButtons.length
CodePudding user response:
Use the sibling selector ~
.
.row ~ .row > .button {
color: hotpink;
}
.row ~ .row ~ .row > .button {
color: blue;
}
<div class='parent'>
<div class='row'>
<div class='button'>
button
</div>
<div class='button'>
button
</div>
</div>
<div class='row'>
<div class='button'>
button
</div>
<div class='button'>
button
</div>
</div>
<div class='row'>
<div class='button'>
button
</div>
<div class='button'>
button
</div>
</div>
</div>
CodePudding user response:
I'm affraid that it is not possible using only CSS. You can archive this using jQuery or pure javascript :
//jQuery
$(".button").eq(0).css("color", "red");
$(".button").eq(1).css("color", "green");
//pure javascript
document.querySelectorAll(".button")[2].style.color = "blue";
document.querySelectorAll(".button")[3].style.color = "pink";
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='parent'>
<div class='row'>
<div class='button'>
button
</div>
<div class='button'>
button
</div>
</div>
<div class='row'>
<div class='button'>
button
</div>
<div class='button'>
button
</div>
</div>
</div>
CodePudding user response:
"is there a css selector I can use (like nth-child) but that treats all buttons as siblings (even if they're in different rows)?"
Yeah, class selector. Is there any other requirements and/or circumstances that you need to address other than that?
.button {
outline: red 3px solid;
}
<div class='parent'>
<div class='row'>
<div class='button'>
button
</div>
<div class='button'>
button
</div>
</div>
<div class='row'>
<div class='button'>
button
</div>
<div class='button'>
button
</div>
</div>
</div>