Vertical Centering Text in DIV
#1
Posted 01 May 2013 - 11:52 AM
1. Create a CSS class for the div that contains the text and named for example "centered"
<div class="centered">some text</div>
2. Then in your stylesheet add the class "centered" and simply set the line-height of the text to be tha same as the height of the div.
.centered{height:40px; line-height:40px;}
* Keep in mind that this works only if the height of the div is fixed.
#7
Posted 30 April 2018 - 05:05 AM
With the flexbox layout module in CSS3, it has become a lot easier to center items vertically in a container. We no longer have to apply the fixed height.
Here is an example:
<section> <h3>Hello World!</h3> </section>
section { display:flex; height: 100vh; align items: center; }
If you apply this style, the child items of the section will be vertically centered; whatever be the height of container.
Here is another method.
<section> <h3>Hello World!</h3> </section>
section { height: 100vh; position: relative; } h3 { position: absolute; top: 50%; transform: translateY(-50%); }
This is another method of vertically centering elements in a container.
I prefer the first method because the second method required positioning properties which I don't like to use.
0 user(s) are reading this topic
0 members, 0 guests, 0 anonymous users