CSS Vertical Centering

Hi, I’m having problems centering elements in the viewport, and I’m struggling to find the specific solution to the problem using google.
So I have an h1 header with responsive text, and a figure with a nested image in my project.
I would like to use flex to center the image in the viewport, while having the h1 banner at the top, and have all this fill the viewport. However, when using display - flex, and setting the container with these two elements, height to 100vh and reducing the height in the browser, the image overflows into my content, h2 and paragraph at the bottom.
Any help would greatly be appreciated, really struggling with basic layouts in CSS.

Here is the Codepen link to the project : https://codepen.io/darryn-jacobs/pen/NWNdZOY

Okay so I just noticed the problem, I have a position - relative property set on my figure element to float in a figcaption over the image nested in my figure element, the flex property seems to be centering things fine. So now I’m unsure how to keep the image/figure from overflowing into the elements below it, while maintaining the floating caption?

Hey Darryn,

can you show as an image of the problem?

I can’t reproduce your problem or I do not understand it fully. :slightly_smiling_face:


Hey Miku
Thanks for the response. Here is an image, as the height of the viewport is reduced, the image flows over the header and paragraph. It’s only noticeable at very small viewport heights.

So I don’t know if I’m over-complicating things, but to try and summarize:

I have an h1 heading with responsive text.
A figure with a nested image that fills the container.
The figure is set to position: relative to allow the figcaption, which is set to position: absolute to be hidden and then displayed on hover.

So I basically just want these elements to be displayed for the height of the viewport and then center the figure vertically and horizontally.
The way I tried to do this was by placing everything in a div container with a with a height: 100vh.
I then placed the figure in another nested div with a height: 80vh
To center the figure horizontally in this container I put a display: flex property on the div.
And then put a display: flex property on the div.
And used align-self: center on the figure to align it vertically.

I hope this explanation is less convoluted, not sure if there is an easier way to have elements fill the viewport and center them vertically, but this is the solution I came up with.

Changing the height to min-height might fix the problem:

div.flex {
  min-height: 80vh;

.viewport {
  min-height: 100vh;
1 Like

Thanks appreciate it. That seems to have fixed it.