To vertically center text within an HTML element using CSS, you can use a combination of CSS flexbox or CSS Grid. Here's an example using both methods:
HTML:
html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="container flexbox">
<p>Vertically Centered Text (Flexbox)</p>
</div>
<div class="container grid">
<p>Vertically Centered Text (CSS Grid)</p>
</div>
</body>
</html>
CSS (styles.css):
css
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
.container {
width: 300px;
height: 100px;
border: 1px solid #ccc;
text-align: center;
font-size: 18px;
}
/* Using Flexbox */
.flexbox {
display: flex;
align-items: center;
justify-content: center;
}
/* Using CSS Grid */
.grid {
display: grid;
place-items: center;
}
In this example:
We have an HTML file that includes two
divcontainers with text and CSS classesflexboxandgrid.In the CSS (styles.css) file, we apply styles to vertically center the text within these containers.
We use the
display: flex;property on thebodyelement to make it a flex container.We set
align-items: center;andjustify-content: center;on thebodyelement to center its children both vertically and horizontally.Inside the
.containerclass, we set thewidth,height, and other styles as desired.For the container with the
flexboxclass, we usedisplay: flex;,align-items: center;, andjustify-content: center;to vertically and horizontally center the text using flexbox.For the container with the
gridclass, we usedisplay: grid;andplace-items: center;to center the text using CSS Grid.
When you open the HTML file in a web browser, you will see two containers with text that are vertically centered on the page using both flexbox and CSS Grid techniques.
Comments
Post a Comment