1

I have a html layout like this:

<div class="container">
  <div class="content">
    // content goes here
  </div>
</div>

I have 100vh applied to container div. And I need to vertically center content. I found I could vertically center everything inside content div if I apply the following CSS to both container and content, but I'm wondering if it's bad practice and if I should be doing something else instead?

display: flex;
justify-content: center;
align-items: center;

Thanks!

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
hemoglobin
  • 761
  • 4
  • 12
  • 33

3 Answers3

2

There is nothing wrong or invalid with nesting flex containers. The flexbox specification neither prohibits nor even admonishes against the practice.

In fact, it's what you must do when you need to apply flex properties to the descendants of a top-level container, since flex layout works only between parent and child elements.

More details here: Proper use of flex properties when nesting flex containers

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
0

It depends on what you need to achieve. Below a few results using different colors to make it more visible.

Using flexbox for both items.

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: blue;
  height: 250px;
}

.content {
  background-color: red;
  height: 200px;
  width: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="container">
  <div class="content">
    <p>Content</p>
  </div>
</div>

Only using it for the container

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: blue;
  height: 250px;
}

.content {
  background-color: red;
  height: 200px;
  width: 200px;
}
<div class="container">
  <div class="content">
    <p>Content</p>
  </div>
</div>

And finally only using it for the content

.container {
  background-color: blue;
  height: 250px;
}

.content {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: red;
  height: 200px;
  width: 200px;
}
<div class="container">
  <div class="content">
    <p>Content</p>
  </div>
</div>
Gerard
  • 15,418
  • 5
  • 30
  • 52
-2

You just need to use it on your container:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}

Fiddle example: http://jsfiddle.net/eq9y42nj/34/

Is this what you are looking for?

Torjescu Sergiu
  • 1,483
  • 10
  • 24
  • Inside the content div, I have two elements: an image and a text section. If I apply it only to the container, the text doesn't vertically center. I'm just wondering if it's bad practice/if it has any drawbacks if I apply it to both? Or if there's another solution that would center everything. – hemoglobin Aug 28 '18 at 06:52
  • http://jsfiddle.net/eq9y42nj/36/ check this fiddle, I simulated an image with a red background container – Torjescu Sergiu Aug 28 '18 at 06:54