2

If I use flex to position my links, the padding doesn't seem to work for padding-top.

Here is an example:

html

<div class="container">
  <p>title</p>
  <div>
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
  </div>
</div>

css

body {
  margin: 0;
}

.container {
  display: flex;
  justify-content: space-between;
}

.container a {
  padding: 15px;
  background: #e23311;
}

And here is a jsfiddle.

How can I fix this so that the padding applies to the top of the links as well?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
tam5
  • 3,197
  • 5
  • 24
  • 45
  • 1
    Add `display: inline-block;` to your `.container a` rule. – Asons Sep 20 '16 at 17:19
  • 1
    Sweet that works @LGSon. Want to write it as an answer? – tam5 Sep 20 '16 at 17:21
  • Perfect, and there is an answer showing it so I closed it as a dupe – Asons Sep 20 '16 at 17:26
  • Ah I see. I just didn't understand why this behavior was only occurring when display: flex was applied to the container. – tam5 Sep 20 '16 at 17:31
  • Me neither actually, so this duplicate might not be 100% correct in this case. I will leave for now, but might alter it later. – Asons Sep 20 '16 at 17:33
  • It might be the "margin collapse" issue, here caused by the `margin: 0` on the body, so if you remove that instead it works too. – Asons Sep 20 '16 at 17:36
  • I don't think that's all of it. If you don't have `margin: 0` true you get more of the top padding, but still not all of it. I think as you said, you need the `inline-block` to fix the margin collapse on the actual `a` element. – tam5 Sep 20 '16 at 18:00
  • Didn't check that, good you did. Lets leave it as is until someone complains :) – Asons Sep 20 '16 at 18:07
  • Your top padding works fine. It's just hidden because you have `margin: 0` on the `body`. If you provide some space, you'll see the full padding: https://jsfiddle.net/yqawkgLk/2/ – Michael Benjamin Sep 20 '16 at 18:09
  • Because the `a` elements are inline-elements in a block formatting context (they are not part of flex layout), they assume inline-level box characteristics. Namely, they will remain in their line and will not disturb surrounding lines (vertically-speaking). – Michael Benjamin Sep 20 '16 at 18:10
  • Making the anchors inline-block allows them to act more like block-level elements while remaining inline. I posted an answer to a similar question yesterday: http://stackoverflow.com/q/39577892/3597276 – Michael Benjamin Sep 20 '16 at 18:12
  • 1
    @Michael_B thanks for correcting me on that margin thing, I see you are right abt that. And thanks for the explanation... cheers :) – tam5 Sep 20 '16 at 18:42

0 Answers0