artooras artooras - 1 month ago 6
CSS Question

First element that is floated right

I set

margin
for some elements:

button {
margin: 10px 10px 0 0;
}

a {
margin: 10px 20px 0 0;
}


Now, whenever I
float: right
any of these elements, I want to set
margin-right: 0
for the first right-floated element. Something like below:

.float-right {
float: right;
/* only for first instance */ margin-right: 0;
}


What are the options to do it?

A few constraints:


  • I have different margins for different elements, and I want the
    .float-right
    class to be generic, so I cannot set
    margin-right: 0
    to the class, and then set a margin for other instances of the right-floated element (
    .float-right ~ .float-right
    ).

  • In my case it is not practical to wrap the elements into a container so I could simply use
    :first-child
    pseudo selector.



Below is a simple example where I have a logo
<a>
and a login
<a>
- the latter is floated right, it is not the first element of type
<a>
, and I need
margin-right
to be
0
.



a {
margin-right: 50px;
}

.float-right {
float: right;
}

.float-right:first-child {
margin-right: 0;
}

<a href="">LOGO</a>
<a href="" class="float-right">Login | Register</a>




Answer

What you are really asking for is first-of-class which, as yet, does not exist.

You can target, however, the first element with a class that immediately follows one that does NOT have that class with the :not() seelctor and the immediate sibling selector.

As follows:

a {
  margin-right: 50px;
}
.float-right {
  float: right;
}
*:not(.float-right) + .float-right {
  margin-right: 0;
}
<a href="">LOGO</a>
<a href="" class="float-right">Login | Register</a>

This is not ideal as it's not really extendable to a large degree but it does offer a solution to your specific request.

Comments