OneBite.Dev - Coding blog in a bite size

center vertically css

Code snippet for how to center vertically css with sample and detail explanation

Title: Center Vertically CSS

Centering vertically in CSS can seem a daunting task if you’re new to development, but worry not! This article will guide you step by step to achieve this with simple lines of code.

Code Snippet for Vertical Centering in CSS

Let’s dive right into it and understand how to center elements vertically on your web page. Look at the below lines of code.

.container{
    display: flex;
    align-items: center;
    height: 150px;
    border: 1px solid black;
}

.inner-element {
    width: 100px;
    height: 100px;
    background-color: blue;
}

In the HTML, you would have something like this:

<div class="container">
    <div class ='inner-element'></div>
</div>

Code Explanation for Vertical Centering in CSS

This technique uses the CSS flexbox layout to center the inner element vertically inside the container.

The .container class contains the styles of the parent element where we wish to center an inner element. display: flex; sets the layout of the container to flexbox. The flex container becomes flexible by setting the display property to flex.

The align-items: center; property aligns the inner-element vertically in the middle of the .container. It aligns the flex item along the cross axis.

The height property is given a value of 150px. You can replace it with any value that meets the requirements of your design. The border property is added merely for visual understanding in this example and might not be necessary in your design.

The .inner-element class styles the child element that you want to center within the container. The height property is set to 100px, and the width is set to 100px, showing that our inner element is lesser than the height of the container, thus leaving spaces along both its top and bottom when aligned vertically.

Manipulating the dimensions of the .inner-element will yield different alignment outcomes. Therefore, mastering vertical alignment using CSS flexbox will involve quite a bit of experimenting with these values to meet your specific design needs.

With this knowledge at your disposal, you should now be able to center elements vertically within a container using CSS. Happy coding!

css