Adrian Föder
Adrian Föder

Reputation: 891

Why does a flex column child not span 100% width when margin 0 auto given?

This occurred when using Zurb Foundation's XY grid but actually is a vanilla CSS Flex question; consider the following code:

<div style="display:flex;flex-direction:column;height:100vh">
  <div style="flex: 1;background-color:yellow">

  </div>

  <div style="
    background-color:blue;
    color:white;
    padding-right: 0.9375rem;
    padding-left: 0.9375rem;

    margin: 0 auto;
    ">
  Why does this not span 100% width<br/>like any block elem would?
  </div>
</div>

(Fiddle)

Why does the bottom div in its X-axis only takes as much width as needed by its content instead of taking the full width like any block element would normally do; and what should I do in order to achieve this (something better than settings its width to 100% maybe?)

Upvotes: 2

Views: 2566

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 371241

When you set margin 0 auto you are using a shorthand property to say this:

  • margin-top: 0
  • margin-right: auto
  • margin-bottom: 0
  • margin-left: auto

In flexbox, auto margins consume all space in their defined direction. So margin-left: auto and margin-right: auto will consume all available space on either side of the flex item, therefore centering the item.

If you simply want to center the text, then instead of auto margins on the flex item, center the actual text:

Instead of this:

div { margin: 0 auto; }

Try this:

div { display: flex; justify-content: center; text-align: center; }

body {
  margin: 0;
  padding: 0;
}
<div style="display:flex;flex-direction:column;height:100vh">
  <div style="flex: 1;background-color:yellow">
  </div>
  <div style="
    background-color:blue;
    color:white;
    padding-right: 0.9375rem;
    padding-left: 0.9375rem;
    
    /* margin: 0 auto; */
    display: flex;
    justify-content: center;
    text-align: center;
    ">
    Why does this not span 100% width<br/>like any block elem would?
  </div>
</div>

More details:

Upvotes: 3

Related Questions