Search code examples
htmlsvghyperlinktags

How does the `a` tag behave?


Could you explain how the a tag behaves in this example? Why is it so small?

a {
  border: 1px solid currentColor;
}
<li>
  <a href="https://facebook.com/starbucks">
    <svg aria-hidden="true" class="valign-middle absoluteCenter" focusable="false" preserveAspectRatio="xMidYMid meet">
<path></path>
<circle class="sb-icon-hover" cx="50%" cy="50%" fill="transparent" r="75%"></circle>
</svg>
  </a>
</li>

Also, could you explain, how to fix it? And how to center it inside the block? Thank you!


Solution

  • The anchor element (<a>) is by default an inline element. It will have the height of the font (example 1). So, making a border around it will display the height of the font.

    If you set the display of the <a> to inline-block or block (example 2 and 3) the element will "contain" the child elements (except if you limit the height...). With either one you can set properties like border, background, padding, margin etc.

    svg {
      display: inline; /*default*/
      height: 2em;
      vertical-align: bottom;
    }
    
    a {
      border: 1px solid currentColor;
    }
    
    ul li:nth-child(1) a {
      display: inline; /*default*/
    }
    
    ul li:nth-child(2) a {
      display: inline-block;
    }
    
    ul li:nth-child(3) a {
      display: block;
    }
    
    li {
      margin: .1em;
    }
    <ul>
      <li>
        <a href="https://facebook.com/starbucks">default
          <svg viewBox="0 0 100 100">
            <circle cx="50%" cy="50%" fill="red" r="50%"/>
          </svg>
        </a>
      </li>
      <li>
        <a href="https://facebook.com/starbucks">inline-block
          <svg viewBox="0 0 100 100">
            <circle cx="50%" cy="50%" fill="red" r="50%"/>
          </svg>
        </a>
      </li>
      <li>
        <a href="https://facebook.com/starbucks">block
          <svg viewBox="0 0 100 100">
            <circle cx="50%" cy="50%" fill="red" r="50%"/>
          </svg>
        </a>
      </li>
    </ul>