OneBite.Dev - Coding blog in a bite size

center in css

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

In this simple guide, we will learn how to center elements in CSS. CSS, or Cascading Style Sheets, is a style sheet language used for describing the look and formatting of a document written in HTML.

Code snippet for centering elements in CSS

The primary way to center a block element horizontally is by using the margin property in CSS. Here’s a simple example:

.center {
    margin-left: auto;
    margin-right: auto;
    width: 50%;
}

In this example, we created a class named ‘.center’. Any HTML element assigned this class will be centered according to these CSS rules.

Code Explanation for centering elements in CSS

Firstly, we define a class called .center. We can use this class to apply these styles to any HTML element by adding class="center" to the element’s tag.

In the ‘.center’ class, we set margin-left and margin-right to auto. This will automatically adjust the left and right margins, pushing the element to the center of its container.

Then, we set width to 50%. This makes the element take up half the width of its container. This, in combination with the auto margins, helps to center the element. You can adjust this percentage according to the desired width of the centered element.

Keep in mind, this method of centering works on block-level elements (like div and p). Block-level elements take up the full width available and hence, setting auto margins adjusts the left and right space equally, centering the element.

css