简体   繁体   中英

Issue to vertically align text within a DIV

Hello would you know why vertical alignment (text within the 4 dark DIVs) does not work in my case despite vertical-align: middle; and display: table-cell; Thanks http://jsfiddle.net/ymE8R/1/

.block {
    background: red;
    width:90%;
    Height: 200px;
}
.col1, .col2, .col3, .col4 {
    float: left;
    width: 25%;
    background: red;
    text-align: center;
    font-size: 12px;
    color: #fff;
    font-weight: 300;
    height: 24px;
    vertical-align: middle;
    display: table-cell;
}

By floating the encapsulating divs, you've made them block-level elements. According to the MDN :

On block level elements, the line-height CSS property specifies the minimal height of line boxes within the element.

Therefore, declare a line-height property that is as high as the encapsulating div:

.col1, .col2, .col3, .col4 {
    height: 24px;
    line-height: 24px;
}

This results in the text within these columns being centered vertically within the div:

在此处输入图片说明

Fiddle here .

If you add a line-height equal to the height of the div it will align as you desire.

In this case, add line-height:24px; to .col1, .col2, .col3, .col4 {} in the css.

Fiddle here .

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