OneBite.Dev - Coding blog in a bite size

center body in css

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

Centering content within a webpage might initially seem challenging, but with CSS, it is quite achievable and straight-forward. This article boils down the steps to accomplish this feat and helps you understand how to do it with ease.

Code snippet: Centering Body in CSS

Here’s a basic code snippet that shows how to vertically and horizontally center the content within the body tag using CSS:

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
}

Code Explanation: Centering Body in CSS

In the CSS code snippet above, we assigned several properties to the body selector. This helps in creating a vertically and horizontally centered body. Here’s a step-by-step explanation:

  • display: flex; This property is used to create a flexible container which we’ll then use to center our body. This property makes the body act as a flex container.

  • justify-content: center; This property is used to align the content in the center of the container along the main axis. In this case, the content will be positioned in the center horizontally.

  • align-items: center; This property is used to center content along the cross-axis. In this specific case, it aligns the content vertically in the center of the body.

  • height: 100vh; The vh unit stands for viewport height. Setting the height to 100vh means that the body will be 100% of the viewport height. This makes the body spread out to the whole height of your screen.

  • margin: 0; This is used to remove any naturally occurring margins around the body tag. This ensures that the body fits exactly within the viewport.

Now, any HTML element inside the body tag would be aligned in the center of the page both vertically and horizontally. Note that this code snippet will work best if there is a single block of content to center, as flex items will stack together in the center of the body which might not be the desired effect if you have multiple blocks of content.

css