Search code examples
htmlcssimagealignmentvisual-glitch

HTML + CSS - Centering Images With Hyperlinks


So I have two images with hyperlinks and when I try to center them, they act funny so I thought huh, maybe the dimensions of the elements are... distorted? Somehow? So I add a border around the elements and sure enough, the sizes of them look like this:

https://gyazo.com/f5a91e1a26eaf3aea6208ffa2eea698c

HTML:

<a id="home-invite-button" href="https://url.com" target="_blank"><img 
src="Images/Invite Button.png"></a>
<a id="home-wiki-button" href="https://url.com" target="_blank"><img 
src="Images/Wiki Button.png"></a>

CSS:

#home-invite-button {
  position: absolute;
  top: 540px;
  left: 0px;
  right: 0px;
  margin: 0px auto;
  width: 50%;
  border: thin black solid;
}

#home-wiki-button {
  position: absolute;
  top: 630px;
  left: 0px;
  right: 0px;
  margin: 0px auto;
  width: 50%;
  border: thin black solid;
}

So the question is, how can I make the actual size of the elements the same as the actual image? Thanks so much!


Solution

  • Avoid assigning the width to your images, instead wrap the <a> tags inside a div content-holder and then apply the positioning to the holder. The images will remain intact.

    Have a look at the snippet below:

    .content-holder {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      border: thin black solid;
    }
    
    #home-invite-button {
      display: flex;
      border: 1px solid red;
    }
    
    #home-wiki-button {
      display: flex;
      border: 1px solid red;
    }
    <div class="content-holder">
      <a id="home-invite-button" href="https://url.com" target="_blank"><img 
      src="http://placehold.it/100x100"></a>
      <a id="home-wiki-button" href="https://url.com" target="_blank"><img 
      src="http://placehold.it/100x100"></a>
    </div>

    Hope this is what you are trying to achieve.