Centered Container with CSS Flexbox Layout Model

Shubham Phadte
Sage Systems
Published in
3 min readOct 2, 2020

Many a times Web Developers arrive at this simple need of centering a container on a webpage. This is a very simple concept to be implemented but can lead to a lot of wasted time and also mind-share. So I am writing this article as guide(for me as well) to come back to when needed to understand the CSS Flexbox implementation to center a container.

It’s a very simple implementation and I have started this series of articles from basic to advanced implementation of use cases in Web Development. So, let’s get started.

Start with a simple index.html webpage. If you are using VS Code you can enter ‘!’ — exclamation mark to generate a template html page.

! — emmet abbreviation to generate template html

Fill in the index.html by adding link tag for the css stylesheet — style.css.

Change the title as desired.

Create a div with the class name “container”. Within it, create a div with class name “heading” and textarea with class name “container-input”.

It should look something like this in the browser.

Output of basic index.html

With the bare structure of the webpage ready, we can focus on the style.css to style the webpage and achieve our goal of centering the container elegantly.

The property box-sizing: border-box ensures that width and height apply to all parts of the element: content, padding and borders. So everything within it is constrained within limits.

Styling the body, we use display:flex; justify-content:center; align-items-center;which makes the display as a flexbox and within the body the items are placed at center horizontally(along the main axis — horizontal axis using justify-content:center;) and items are aligned vertically(along the cross axis-vertical axis using align-items-center;).

We fix the min-height:100vh; so that body takes entire screen height and margin:0; to ensure that scrollbar is removed.You can change the background color as you wish.

body styling
Output of body styling

Actually in the above code itself we have achieved our goal but let us improve on the webpage’s styling.

Styling the container, set background-color as you wish. padding & border-radius to value as you wish. I have fixed the width to 700px. max-width:90% ensures that if screen size is reduced as in a phone screen, the container will be 90% of screen-size. text-align:center; will align the contents to the center.

Output of above styling

Finally, we can style the contents of the container as shown in the below image. Give an appropriate color & font-size to the heading.

Also, the input box is styled to make the background transparent so that it takes the background of the container. Border is slightly darker than the background and border-radius gives curves at the edges. This will make the input box elegant.

Final Output

--

--