To center text both horizontally and vertically inside a <div>
block, you can use CSS Flexbox or CSS Grid. Here's an example using CSS Flexbox:
HTML:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Center Text</title>
</head>
<body>
<div class="container">
<div class="centered-text">
<p>This is centered text.</p>
</div>
</div>
</body>
</html>
CSS (styles.css):
css
body {
margin: 0;
padding: 0;
display: flex; /* Center the container both horizontally and vertically */
justify-content: center;
align-items: center;
min-height: 100vh; /* Ensure full viewport height */
}
.container {
text-align: center; /* Center the content horizontally */
}
.centered-text {
display: inline-block; /* Prevents the block from taking full width */
padding: 20px; /* Add padding for better appearance */
background-color: #f0f0f0; /* Optional background color */
}
In this example:
We use CSS Flexbox on the
body
element to center the.container
both horizontally and vertically within the viewport. This ensures that the entire content is centered.Inside the container, we use
text-align: center;
to center the text horizontally within the container.The
.centered-text
<div>
is givendisplay: inline-block;
to prevent it from taking the full width of the container. You can adjust the padding and background color as needed for styling.
With this setup, the text inside the <div>
will be both horizontally and vertically centered within the container. You can replace the text within the <p>
element with your own content.
Comments
Post a Comment