简体   繁体   中英

Position text vertically center in div with CSS

I'd like to position all my text vertically centered within the div.

Currently 'Chat to us online now' is at the top of the div.

How do I achieve this using my code?

Fiddle: http://jsfiddle.net/jL5bpmp1/

 * { margin:0 } .box { -webkit-border-radius: 20px; -moz-border-radius: 20px; border-radius: 20px; background-color:#0f89cf; height:55px; width:100%; padding:5px 0 0 0; margin-bottom:30px } .box img, .box div { float:left; margin-left:10px } .box h1 { color:#fff; font-size:18px } .box h1 span { display:block; font-size:23px } 
 <div class="is-mobile"> <div class="box"> <img src="http://placehold.it/50x50"> <div> <h1>Chat to us online now</h1> </div> </div> <div class="box"> <img src="http://placehold.it/50x50"> <div> <h1>Call the Helpline <span>101 2333 9302</span></h1> </div> </div> <div class="box"> <img src="http://placehold.it/50x50"> <div> <h1>Make a General Enquiry <span>101 2333 9303</span></h1> </div> </div> </div> 

I suggest to use display:inline-block instead of float:left , then you can set up the vertical align value easily.

.box img, .box div {
    display:inline-block;
    vertical-align:middle;
}

jsfiddle

You can use this common vertical centering method:

.box div {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

 * { margin:0 } .box { -webkit-border-radius: 20px; -moz-border-radius: 20px; border-radius: 20px; background-color:#0f89cf; height:55px; width:100%; padding:5px 0 0 0; margin-bottom:30px } .box img, .box div { float:left; margin-left:10px } .box h1 { color:#fff; font-size:18px } .box h1 span { display:block; font-size:23px } .box div { position: relative; top: 50%; transform: translateY(-50%); } 
 <div class="is-mobile"> <div class="box"> <img src="http://placehold.it/50x50"> <div> <h1>Chat to us online now</h1> </div> </div> <div class="box"> <img src="http://placehold.it/50x50"> <div> <h1>Call the Helpline <span>101 2333 9302</span></h1> </div> </div> <div class="box"> <img src="http://placehold.it/50x50"> <div> <h1>Make a General Enquiry <span>101 2333 9303</span></h1> </div> </div> </div> 

If your browser support is IE10+ you can use flex-box. You just need to add 2 lines:

.box {
    display: flex;
    align-items: center;
    padding: 0;
}

I also added padding: 0; as you don't need that now you're using flex-box. Welcome to the future. The best place to learn about flexbox is here:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

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