Vertical Alignment
1. Using Padding:
In CSS, vertical alignment using padding refers to the practice of adding space inside an element (between its content and border) to align the content vertically within its container.
For example, if you want to vertically center content inside a container, you can use padding to create equal space above and below the content.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
padding: 70px 0;
border: 3px solid green;
}
</style>
</head>
<body>
<div>
<p>vertically centered</p>
</div>
</body>
</html>
Output:
2. Using Line-height:
Using line-height is a simple way to align text vertically. By setting the line-height
equal to the element’s height, the text centers itself within its container.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
line-height: 200px;
height: 200px;
border: 3px solid green;
text-align: center;
}
p {
line-height: 1.5;
display: inline-block;
vertical-align: middle;
}
</style>
</head>
<body>
<div>
<p>vertical and horizontal centered</p>
</div>
</body>
</html>
Output:
3. Using Position:
In CSS, vertical alignment using position means placing an element in the center of its container by using absolute positioning. You set the top position to 50% of the container’s height and adjust it back using a transform to ensure it aligns perfectly in the middle.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
height: 200px;
position: relative;
border: 3px solid green;
}
p {
margin: 0;
position: absolute;
top: 50%;
left: 33.3%;
right: 33.3%;
}
</style>
</head>
<body>
<div>
<p>vertical and horizontal centered</p>
</div>
</body>
</html>
Output:
4. Using Flexbox:
Using Flexbox is one of the easiest and most efficient ways to vertically align content in CSS. With Flexbox, you can easily center items both vertically and horizontally.
In CSS, vertical alignment using Flexbox allows you to center an element within its container by applying display: flex
to the container and using align-items: center
to align items vertically.
Key Points:
display: flex
; Turns the container into a flex container.align-items: center
; Vertically centers the content.justify-content: center
; Horizontally centers the content (optional).
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid green;
}
</style>
</head>
<body>
<div>
<p>vertical and horizontal centered</p>
</div>
</body>
</html>