简体   繁体   中英

Align Text in middle vertically

I am not able to vertically align middle some text using the position absolute method. JSFIDDLE

HTML

    <div class="heighted">
    <div class="middle-wrapper">
        <span class="middle">text to be vertically aligned in the middle</span>
    </div>
</div>
<hr/>
<div class="heighted">
    <div class="middle-wrapper">
        <img class="middle" src="http://www.google.com/homepage/images/google_favicon_64.png" />
    </div>
</div>

CSS

    .heighted {
    background: gray;
    height: 100px;
}
.middle-wrapper {
    height: 100%;
    position: relative;
}
.middle {
    bottom: 0;
    margin: auto;
    position: absolute;
    top: 0;
}

I am getting Stack Overflow error when adding code, it might be a bug in Stack Overflow, so please follow the link.

Set line-height: 100px; to .heighted or .middle-wrapper or .middle - DEMO

CSS:

.heighted {
    background: gray;
    height: 100px;
    line-height: 100px;
}
.middle-wrapper {
    height: 100%;
    position: relative;
}
.middle {
    bottom: 0;
    margin: auto;
    position: absolute;
    top: 0;
}

HTML:

<div class="heighted">
    <div class="middle-wrapper">
        <span class="middle">text to be vertically aligned in the middle</span>
    </div>
</div>
<hr/>
<div class="heighted">
    <div class="middle-wrapper">
        <img class="middle" src="http://www.google.com/homepage/images/google_favicon_64.png" />
    </div>
</div>

You should try display:table-cell; and use vertical-align:middle;

Check how amazing and optimize: http://jsfiddle.net/9jugdtqx/2/

and: http://jsfiddle.net/9jugdtqx/3/

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