moesphemie moesphemie - 3 months ago 8
CSS Question

Different styles dependent on displayed elements

I have an element which could contain one, two or three buttons.

When i have only one button, then there is no margin to the right

When i have two buttons, then the first button gets a right margin

And when i've three buttons, the first and the second button get a right margin

What i have tried:

  • The :only-child covers my needs for only one button.

  • The sibling selector works pretty good but is limited when it comes to three buttons

Would love to read your solutions for this :)


Here comes a screen-capture of the page:
It shows the three possibilities. The container could either contain one, two or three buttons. I have already figured out how to edit the space around two buttons but how do i manage this for three?

This is a Gif of the three buttons


You can use the :last-child selector and have css that looks like this:

button {
  margin-right: 10px;
button:last-child {
  margin-right: 0px;

When you only have one button, it will be the last element, and therefore won't have any margin. Then for two and three buttons, the last one won't have margin.

The :last-child selector works for IE9 and above.