简体   繁体   中英

How to align text in middle (vertically)

I am struggling with this many hours now and still I can't find a solution. I've made this nice grid that adjusts with text length and browser resising. The problem now is that I can't get text go the middle of the box.

I've tried everything.. I used several properties in order to achieve this but nothing worked.

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

The 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;

}

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 with flex as ur jsfiddle. u can do it also easier with "parent display table and vertical align middle" and "child display table cell and van middle" removing ur flex styles.

If you do not care that divs with multiple lines of text adjust their height to actual text content, use height:100% on your child elements.

If you need all your content to stay the same height, add

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

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

Have you tried:

margin:0 auto;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM