1

I am trying to horizontally center one div inside parent div (Which is display flex in column mode) using margin 0 auto. When I do this the inner div is getting shrinked to the size of its content. Can someone explain why this is happening and how to fix this?

HTML

<div class="container">
    <div class="mydiv">
        CENTER THIS DIV
    </div>     
</div>

CSS

.container{
    background-color: brown;
    height: 100px;
    display: flex;
    flex-direction: column;
}


.mydiv{
    background-color: chartreuse;
    max-width: 500px;
    margin: 0 auto;
}

If I remove flex from parent, then I am getting the correct output : enter image description here

However, with the flex properties as in above code, this is what I get :

enter image description here

anandhu
  • 686
  • 2
  • 13
  • 40
  • Do you need to use `flex` for the container at all then? `flex` is great for lots of scenarios, but its certainly not the "be-all and end-all" for every responsive layout and you can end up just making things more complicated. But the reason its happening is because it is using `max-width` so the column doesn't have a fixed width that it knows you want to use. – FluffyKitten Sep 16 '20 at 18:11
  • text-align:center is all what you need here – Temani Afif Sep 16 '20 at 19:25
  • i was using flex because i wanted to make the able to grow full size vertifcally. Tried text-align:center but did not work for me. However the solution by Sergio below worked – anandhu Sep 17 '20 at 02:07
  • And why was this marked as duplicate?!! This question was about preventing child div form shriking when using flex. The other thread was about centering a text inside a div – anandhu Sep 17 '20 at 02:10

1 Answers1

4

When you use display: flex; in a parent, the children automatically get the default flex values:

The item is sized according to its width and height properties. It shrinks to its minimum size to fit the container, but does not grow to absorb any extra free space in the flex container. This is equivalent to setting "flex: 0 1 auto".

That's why your .mydiv adjusts to fit the text.

(more info: https://developer.mozilla.org/en-US/docs/Web/CSS/flex)

If you don't want that to happen you could do something like this:

.container{
    background-color: brown;
    height: 100px;
    display: flex;
    flex-direction: column;
    align-items: center; /* add this */
}


.mydiv{
    background-color: chartreuse;
    width: 100%; /* add this */
    max-width: 500px; /* add this */
}

Working example: https://codepen.io/sergiofruto/pen/dyMqbrm