OneBite.Dev - Coding blog in a bite size

center align text css

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

Centering text in CSS is a basic yet useful tool every web designer should be able to execute flawlessly. This simple guide will help you understand how you can achieve this much-needed skill.

Code snippet: Center Align Text CSS

The CSS property for center aligning text is quite straightforward. Here’s an example:

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

In this instance, any text within an HTML element assigned with the class “center-text” will be positioned in the middle of its container.

    <div class="center-text">
        This text will be centered.
    </div>

Code Explanation for Center Align Text CSS

The CSS code .center-text { text-align: center; } simply means that we’re creating a CSS rule for any element assigned with the center-text class.

The property text-align: center; is self-explanatory: it aligns the text to the center, taking into account the width of the text container.

The HTML code is a demonstration of using the CSS rule we’ve created. By assigning the “center-text” class to the div element, the text within this div will be centered according to the rules of the specified CSS class.

That’s it! You have successfully centered text in CSS. The text-align property can also be used with values left and right to align the text accordingly, giving you control and flexibility over your text alignment.

css