HTML Text Centering: A Step-by-Step Guide for Beginners
Centering text in HTML is a common task for web developers. In this guide, you’ll learn multiple methods to center text using HTML and CSS, including best practices for responsive design.
Step-by-Step Guide to Center Text in HTML
1. Centering Text with the <center>
Tag (Deprecated)
The <center>
tag was used in older HTML versions but is now deprecated in HTML5. Avoid using it in modern web development.
<!DOCTYPE html>
<html>
<head>
<title>Center Text Example</title>
</head>
<body>
<center>This text is centered using the `<center>` tag.</center>
</body>
</html>
Best Practice: Use CSS instead of the <center>
tag for better control and compatibility.
2. Centering Text Using Inline CSS
Inline CSS is a quick method to center text.
<!DOCTYPE html>
<html>
<head>
<title>Inline CSS Example</title>
</head>
<body>
<p style="text-align: center;">This text is centered using inline CSS.</p>
</body>
</html>
3. Centering Text with Internal or External CSS
Using internal or external CSS allows you to manage styles efficiently.
Example with Internal CSS:
<!DOCTYPE html>
<html>
<head>
<title>Internal CSS Example</title>
<style>
.center-text {
text-align: center;
}
</style>
</head>
<body>
<p class="center-text">This text is centered using internal CSS.</p>
</body>
</html>
Example with External CSS:
/* styles.css */
.center-text {
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<title>External CSS Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p class="center-text">This text is centered using external CSS.</p>
</body>
</html>
4. Centering Text Vertically and Horizontally
To center text both vertically and horizontally, use Flexbox.
<!DOCTYPE html>
<html>
<head>
<title>Flexbox Centering Example</title>
<style>
.center-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
</style>
</head>
<body>
<div class="center-container">
<p>This text is centered vertically and horizontally using Flexbox.</p>
</div>
</body>
</html>
Best Practices for Centering Text
Use CSS for Styling
Use CSS for Styling: Avoid outdated methods like the <center>
tag.
Responsive Design:
Responsive Design: Use Flexbox
or Grid
for advanced layout controls.
Consistency:
Consistency: Use external CSS for better scalability and maintainability.
Semantic HTML
Semantic HTML: Wrap your text in appropriate semantic tags like <h1>
or <p>
.