How to center text (vertically)

I have been struggling with this for many hours and still cannot find a solution. I made this nice grid that is customizable with text length and browser change. Now the problem is that I cannot get the text in the middle of the field.

I have tried everything. To achieve this, I used several properties, but nothing worked.

text-align: center; vertical-align: middle; line-height: "same as div"; 

Css code:

 .parent { text-align:center; margin:0px; width:100%; padding:0px; font-size:18px; color:#000; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-pack: justify; -webkit-justify-content: space-between; -ms-flex-pack: justify; justify-content: space-between; } .child { padding:18px 25px; background: rgba(0, 0, 0, .5); list-style-type:none; width:inherit; margin:5px; } 
+7
html css alignment vertical-alignment
source share
3 answers

Is this what you want?

 .parent { text-align:center; margin:0px; width:100%; padding:0px; font-size:18px; color:#000; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; vertical-align: middle; -webkit-box-pack: justify; -webkit-justify-content: space-between; -ms-flex-pack: justify; justify-content: space-between; } .child { position: relative; background: rgba(0, 0, 0, .5); padding:10px; list-style-type:none; width:inherit; align-items: center; justify-content: center; height:inherit; display: inline-flex; vertical-align: middle; margin:5px; } 
 <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div class="parent"> <div class="child"><span>sometext</span></div> <div class="child">somemoretext somemoretext</div> <div class="child">sometext</div> <div class="child">sometext</div> </div> <div class="parent"> <div class="child">somemoretext somemoretext somemoretext somemoretext</div> <div class="child">sometext</div> </div> </body> </html> 

this is done using flex as ur jsfiddle. u can also make it easier with the “parent display table and vertical alignment in the middle” and the “child cell of the display table and the average bath size” by deleting ur styles styles.

+5
source share

If you don't care that divs with multiple lines of text adjust their height to the actual text content, use height:100% for your child elements.

If you want all your content to stay the same, add

 // Use any fixed value line-height: 50px; height: 50px; 

If you need to change the fixed height in pixels when your window is resized, just use javascript to change the CSS rule (if this method reads this first do not slow down your client when changing the window).

+2
source share

You tried:

margin: 0 auto;

+1
source share

All Articles