OneBite.Dev - Coding blog in a bite size

center align text in css

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

Centering text using CSS is a fundamental technique that every web developer should master. This short article will guide you through a simple approach to center align text in CSS.

Code snippet to center align text in CSS

Here is a practical code snippet that can be used to center align text in CSS.

.center-text {
    text-align: center;
}

To apply this to a paragraph in your HTML, you would do something like this:

<p class="center-text">This is some centered text!</p>

Code Explanation for center text in CSS

In the above code snippet, a CSS class called .center-text is defined, which will apply the style rules within its braces ({}) to any HTML elements that have this class applied.

The rule within the .center-text style is text-align: center;. The text-align property in CSS defines the horizontal alignment of text in an element. Setting this to center will center the text.

This code can be applied to any HTML text element. For example, if you wanted to center the text within a heading, you could apply the class to a heading element like so:

<h2 class="center-text">This is a centered heading</h2>

In the HTML snippets, the class .center-text is applied to a paragraph (<p>) and heading (<h2>) element. This means the text inside these elements will be displayed according to the rules defined in the .center-text CSS class, which in this case is center alignment.

Understand that this is one of the most basic ways to center text with CSS and will work in pretty much all scenarios. However, if you want to center something other than text or want to center both vertically and horizontally, you will need to use different methods.

css