skip to Main Content

I have an anchor tag. I have given an outline to this anchor tag. But this outline is not visible unless the anchor tag has a display: flex.

Here in the below example, there are two anchor tags. The first one does not have a flex container, but the second one has. And you can see the outline for the first anchor tag is not visible, but the outline is visible for the second anchor tag.

Why is this so?

.link {
  outline: 2px solid #000;
}
.link.flex {
  display: flex;
}
.content {
  padding: 20px;
  border: 1px solid #ff2121;
}
<a class="link" href="">
    <div class="content">
    <h4>This doesnot have a flex container</h4>
    </div>
</a>
<a class="link flex" href="">
    <div class="content">
    <h4>This has a flex container</h4>
    </div>
</a>

2

Answers


  1. The outline isn’t showing on the first <a> tag because <a> tags are inline by default, meaning they only take up as much space as their content. When you put a larger block element, like a <div>, inside an inline <a>, the outline doesn’t wrap around it correctly. Setting display: flex on the <a> tag fixes this by making it behave like a block element, allowing the outline to cover the entire content.

    Login or Signup to reply.
  2. Add some padding to see it

    .link {
      outline: 2px solid #000;
      padding: 10px;
    }
    
    .link.flex {
      display: flex;
    }
    
    .content {
      padding: 20px;
      border: 1px solid #ff2121;
    }
    <a class="link" href="">
      <div class="content">
        <h4>This doesnot have a flex container</h4>
      </div>
    </a>
    <a class="link flex" href="">
      <div class="content">
        <h4>This has a flex container</h4>
      </div>
    </a>

    The result is quite strange but it’s the logical result of using block element inside inline elements. It’s described perfectly here: Is it wrong to change a block element to inline with CSS if it contains another block element?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search