center text in html css
Code snippet for how to center text in html css with sample and detail explanation
Article:
Centering text is one of the most common tasks when creating a webpage. It is a core concept in HTML CSS and is taught in almost every beginners guide. This article will demonstrate how to center text in HTML CSS in a straightforward way.
Code Snippet for Text Centering
Here’s a simple piece of HTML CSS code that allows you to center text:
<!DOCTYPE html>
<html>
<head>
<style>
.center {
text-align: center;
color: red;
}
</style>
</head>
<body>
<h2 class="center">Hello World</h2>
</body>
</html>
Code Explanation for Text Centering
This code is broken down into three main parts: The HTML tag, The Style tag, and The Body tag.
-
The HTML tag: The HTML tag,
<!DOCTYPE html><html>
, declares to the browser that this is an HTML document. -
The Style tag: Inside the
<head>
, a style is defined for a class named “center”. There are two attributes in this class:text-align
andcolor
.text-align: center;
: It is used to align the text to the center.color: red;
: It makes the color of the text red.
-
The Body tag: Inside the
<body>
tag, an<h2>
element is created, and the class “center” is applied to it using the class attribute. This makes the text within this<h2>
element inherit the properties of the “center” class, causing it to become centered and red.
In conclusion, using CSS to center your text in HTML can greatly improve the visual appearance of your web site. By using the text-align: center;
property in your CSS, you can quickly center text, enhancing your site’s readability and aesthetic appeal.