how to select a specific element if both have same classname

lets say I have these two buttons
<Button class="navButton">Menu</Button>
<Button class="navButton">Restart</Button>
<Button class="navButton">Menu</Button>
<Button class="navButton">Restart</Button>
then how do I select the button with the text restart, menu I tried doing this
.navButton:nth-child(1) {
margin-left: 15%;
}

.navButton:nth-child(2) {
margin-right: 15%;
}
.navButton:nth-child(1) {
margin-left: 15%;
}

.navButton:nth-child(2) {
margin-right: 15%;
}
button with menu text is selecting but restart is not selecting
8 Replies
Jochem
Jochem2y ago
easiest would be to just give them IDs
Aditya Kirad
Aditya Kirad2y ago
you mean give different classnames two the different element this thought also first came in my mind
Kevin Powell
Kevin Powell2y ago
We'd have to see more context for why or why not :nth-child() would we working... but yeah, having another way to select them would be ideal?
Aditya Kirad
Aditya Kirad2y ago
ok
Jochem
Jochem2y ago
well, that works too, but you can do
<Button id="theFirstButton" class="navButton">Menu</Button>
<Button id="theSecondButton" class="navButton">Restart</Button>
<Button id="theFirstButton" class="navButton">Menu</Button>
<Button id="theSecondButton" class="navButton">Restart</Button>
and then
#theFirstButton {
margin-left: 15%;
}

#theSecondButton {
margin-right: 15%;
}
#theFirstButton {
margin-left: 15%;
}

#theSecondButton {
margin-right: 15%;
}
Just make sure that all your IDs are unique
Aditya Kirad
Aditya Kirad2y ago
sorry my bad I didn't show the full code these two button have a div between them
<Button class="navButton">Menu</Button>
<div></div>
<Button class="navButton">Restart</Button>
<Button class="navButton">Menu</Button>
<div></div>
<Button class="navButton">Restart</Button>
also I did some changes in the css
.navButton:nth-child(1) {
margin-left: 15%;
}

.navButton:nth-child(3) {
margin-right: 15%;
}
.navButton:nth-child(1) {
margin-left: 15%;
}

.navButton:nth-child(3) {
margin-right: 15%;
}
and it worked can you explain why this worked is this have anything related to the div between the two button
MarkBoots
MarkBoots2y ago
nth-child looks at ALL the siblings within a parent, not only the ones that have the same class (or other selector). so in this case the navbutton is the fist and third child. the div in between is de second in your case could also use the :first-child and :last-child selector (if there are no other elements after the second button.
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server