October 26, 2017 in CSS

Horizontal & Vertical centring using flexbox module

Aligning content vertically inside a DIV or a box has always been an issue in CSS. There was some tricks available with display: table and display: table-cell properties. But it was never convenient to implement, until flexbox module came into the existence.

With Flexbox, one can align anything (vertically or horizontally) with the align-items and justify-content properties.

The align-items property specifies the vertical alignment of contents inside the flex container and the justify-content property allows the content to align horizontally.

Code you need to use for horizontal and vertical centring of content is:

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

Note: You can use flexbox modules for particular parts of your page, its not mandatory to create whole layout using flexbox properties.

Complete example with HTML and CSS code:

html, body {
    height: 100%;
}

body {
    margin: 0;
}

.flex-container {
    height: 100%;
    padding: 0;
    margin: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    flex: 1 0 auto;
}

.flex-item {
    background-color: red;
    padding: 5px;
    width: 100px;
    height: 100px;
    line-height: 100px;
    margin: 10px;
    color: white;
    font-weight: bold;
    font-size: 2em;
    text-align: center;
}

 

<div class="flex-container">
    <div class="flex-item">1</div>
    <div class="flex-item">2</div>
    <div class="flex-item">3</div>
    <div class="flex-item">4</div>
</div>

About the author

Jaspreet Kaur

Jaspreet is a UI/UX designer with expertise in front-end development for web and mobile. She is passionate about designing solutions through collaboration, iteration, and following the best technology development practices.

Leave a Reply

Your email address will not be published. Required fields are marked *