Search code examples
htmlcssmargin

Why does css ignore the margin of my <a> tag?


I'm trying to make some of my hyperlinks look like buttons, but for some reason it simply ignores the padding and margin I give it, making it look bad.

picture for reference

How can I prevent the margin of the button from being ignored? This would move the button down some more and have the background go fully behind it.

This is the code I'm using:

.bg-div {
  background-color : #b4d4e7;
  padding          : 0rem 1rem;
  }

p{
  line-height: 2rem;
  margin: 0rem 0 1rem 3px;
}

.hyperlink-button {
  border-radius       : 14px;
  background-color    : transparent;
  border              : 2px solid #157ea1;
  padding             : 1rem;
  color               : #157ea1;
  transition-duration : 0.3s;
  margin              : 1rem 0rem;
  width               : fit-content;
  }
<div class="bg-div">
  <h2>text</h2>
  <p>more text<br>
    <a href="www.stackoverflow.com">this is a hyperlink</a>
    <br> yet more text
  </p>
  <a class="hyperlink-button" href="www.stackoverflow.com">hyperlink button</a>
</div>

Using the inspect feature I played around with the margin and padding of several objects, and everything but that specific button works fine. Putting a around the hyperlink button results in exactly the same look. I looked into margin collapsing, but even if the margin of my hyperlink button is a lot bigger than the one from the text, the text one is used and the hyperlink button's is ignored. Besides, the padding is also ignored, which shouldn't occur with normal margin collapsing.


Solution

  • just add display:block as an <a> is an inline element

    .bg-div {
      background-color : #b4d4e7;
      padding          : 0rem 1rem;
      }
    .hyperlink-button {
      display:block;
      border-radius       : 14px;
      background-color    : transparent;
      border              : 2px solid #157ea1;
      padding             : 1rem;
      color               : #157ea1;
      transition-duration : 0.3s;
      margin              : 1rem 0rem;
      width               : fit-content;
      }
    <div class="bg-div">
      <h2>text</h2>
      <p>more text<br>
        <a href="www.stackoverflow.com">this is a hyperlink</a>
        <br> yet more text
      </p>
      <a class="hyperlink-button" href="www.stackoverflow.com">hyperlink button</a>
    </div>