简体   繁体   中英

CSS Text Vertical Align Middle

I got a problem. I am trying to make an image with a hover. I got some text in the div. Now i want the text to be centered of the div. I used:

display: table-cell;
vertical-align: middle;

The text is Almost in the middle of the Div. When i add more text to it, you will see that the text isnt centered.

Live Example: http://jsfiddle.net/DennisBetman/6TkkE/

I hope some of you know the problem and can help me.

You made your <h1> have a position:absolute , but there was no container that it was positioned relative to.

I took position:absolute and height:100% off of the <h1> . then I added position:relative to its container .text

Here's the fiddle to show this: http://jsfiddle.net/6TkkE/5/

Here is a nice workaround for this, which worked fine for my purpose: Get a container of your size (relative is fine too). Make it's position relative, place a span or p inside it with absolute position. Give it a line-height, maybe 30px. Depends on your font size. Then center it with left and top, fix the margin and the width must be 100% to apply text-align: center.

.container {
    position: relative;
    width: 800px;
    height: 600px;
}
.container > span {
    position: absolute;
    left: 50%;
    top: 50%;
    margin-top: -15px;
    margin-left: -50%;
    line-height: 30px;
    width: 100%;
    text-align: center;
}
...
<div class="container">
    <span>Vertical and Horizontal align.</span>
</div>

Worked fine for me!

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