Force two elements to always occupy the same space

Asked

Viewed 57 times

1

How to make two elements always occupy the same space, independent of the browser and screen size?

I used the transform translateX however, when testing the phone did not work, here I put -18px, in my application I had to put -45px for desktop and -43px cell phone:

#plus {
    transform: translateX(-18px) rotate(90deg);
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css">

<i class="fas fa-minus"></i>
<i id="plus" class="fas fa-minus"></i>

The idea is that the second icon will rotate to switch between + and -

1 answer

3


For both elements to occupy the same place, use position: absolute in the icon #plus and it will be superimposed on the first, but you have to put them inside the same container, it can be a span because it does not change the layout. But the span also needs a position: relative:

span.icone{
   position: relative;
   background: red; /* apenas para mostrar a área ocupada pelo span */
}

#plus {
   transform: rotate(90deg);
   position: absolute;
   top: 0;
   left: 0;
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css">

<span class="icone">
   <i class="fas fa-minus"></i>
   <i id="plus" class="fas fa-minus"></i>
</span>

In this case you do not need to reposition one of the elements with translate.

In the case of Safari, you need to add the prefix -webkit- in the transform:

#plus {
    -webkit-transform: rotate(90deg);
    transform: rotate(90deg);
}

Alternative with native classes

You can use native component classes for stack the two icons, just rotating the second via CSS. Following the same example above, placing the icons inside a span, class fa-stack in container and class fa-stack-1x in each icon (the 1x is the normal size of the icon):

.rot {
   transform: rotate(90deg);
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css">

<span class="fa-stack">
   <i class="fas fa-minus fa-stack-1x"></i>
   <i class="fas fa-minus fa-stack-1x rot"></i>
</span>

  • 1

    Thanks @Bacco and sam, I didn’t know these awesome font classes

  • .............

Browser other questions tagged

You are not signed in. Login or sign up in order to post.