EN
CSS - vertically center text
1 answers
0 points
How can I vertically center text inside my element?
I've tried vertical-align: middle
but it doesn't work.
My code:
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
.element {
7
height: 100px;
8
vertical-align: middle; /* doesn't work */
9
border: 1px solid lightgray;
10
}
11
12
</style>
13
</head>
14
<body>
15
<div class="element">Some text here...</div>
16
</body>
1 answer
0 points
The easiest solution would be to use flexbox (display: flex
) like this:
xxxxxxxxxx
1
.element {
2
display: flex; /* <----- required */
3
align-items: center; /* <----- required */
4
height: 100px;
5
border: 1px solid lightgray;
6
}
As an alternative you can also use line-height
property:
xxxxxxxxxx
1
.element {
2
height: 100px; /* <----- required */
3
line-height: 100px; /* <----- required */
4
border: 1px solid lightgray;
5
}
Note:
Centering text inside element is a similar problem to centering element vertically. For more solutions go to this article: CSS - center element vertically.
Practical examples
1. Using flexbox
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
.element {
7
display: flex; /* <----- required */
8
align-items: center; /* <----- required */
9
height: 100px;
10
border: 1px solid lightgray;
11
}
12
13
</style>
14
</head>
15
<body>
16
<div class="element">Some text here...</div>
17
</body>
18
</html>
2. Using line-height
property
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
.element {
7
height: 100px; /* <----- required */
8
line-height: 100px; /* <----- required */
9
border: 1px solid lightgray;
10
}
11
12
</style>
13
</head>
14
<body>
15
<div class="element">Some text here...</div>
16
</body>
17
</html>
See also
References
0 commentsShow commentsAdd comment