Search code examples
htmlcsshoveralignment

How can I properly implement #ID:hover{} in CSS with no missalignment on other HTML elements?


So, I've been trying my hand on <div> elements for the first time, which I've had no problems with so far. But now, I want to have a div box, which has multiple <a> links, as <img>'s with the goal of having a #Image:hover function that serves as an animation.

Implentation went good as well, but now I've come across my problem, which I've found nothing specific about... the img element missaligns the other img's whenever I hover it. Now I want to know what I can implement so that it doesn't missalign...

I have this CSS section:

#Icons {
    margin: 8px 0 0;
    padding: 0;
    display: block;
    background-color: transparent;
    min-height: 43px;
    height: 43px;
    max-height: 43px;
}

#Image {
    margin: 0;
    padding: 0;
    width: 40px;
    height: 40px;
}

#Image:hover {
    margin: 0;
    padding: 0;
    width: 43px;
    height: 43px;
}

#Media {
    margin: 0 4px;
    display: inline-block;
    min-width: 43px;
    width: 43px;
    max-width: 43px;
    min-height: 43px;
    height: 43px;
    max-height: 43px;
}

And this HTML section:

<p id="HeaderTwo">Reachable under</p>
<div id="Icons">
    <a id="Media" href="#"><img id="Image" src="../img/discord.png" /></a>
    <a id="Media" href="#"><img id="Image" src="../img/gmail.png" /></a>
    <a id="Media" href="#"><img id="Image" src="../img/telegram.png" /></a>
    <a id="Media" href="#"><img id="Image" src="../img/youtube.png" /></a>
</div>

I tried including the folling bit to some CSS elements in hope that it kinda serves as a box limiter or sth. similiar, so that so no missalignment can/should happen.

min-width: 43px;
width: 43px;
max-width: 43px;
min-height: 43px;
height: 43px;
max-height: 43px;

Solution

  • To avoid elements from resizing the layout, use transform scale.

    Now, aside from your specific question, please consider these fixes:

    • Avoid the usage of ID for styling (also, IDs must be unique)
    • Hover animation is to tell the user that the image is clickable, so the trigger should be on the <a> tag

    .image {
      width: 40px;
      height: 40px;
      transition: transform .3s;
      will-change: transform;
    }
    
    .media {
      display: inline-block;
      margin: 0 4px;
    }
    
    .media:hover .image {
      transform: scale(1.075);
    }
    <div class="icons">
        <a href="#" class="media"><img class="image" src="https://source.unsplash.com/random?1" /></a>
        <a href="#" class="media"><img class="image" src="https://source.unsplash.com/random?2" /></a>
        <a href="#" class="media"><img class="image" src="https://source.unsplash.com/random?3" /></a>
        <a href="#" class="media"><img class="image" src="https://source.unsplash.com/random?4" /></a>
    </div>