Olical
Olical

Reputation: 41452

Vertical align multiple lines of text to the middle

I need to align multiple lines of text to the middle. Here is a rough guide of the markup I am working with.

<ul>
    <li>
        <a href='#'>This should be centered.</a>
    <li>
</ul>

The element that needs to be centered

So as you can see from my image, the "work" link should be centered vertically. I have the width and height set with vertical-align: middle;. I know you need to set the line height for it to actually work but theres the problem. If I set the line height to 72px (the height of the element) then some of the links will stretch down the page due to them taking up two lines.

The broken center

Is there a way of aligning multiple lines of text to the middle without using line-height?

Upvotes: 7

Views: 13945

Answers (4)

Alex Kleshchevnikov
Alex Kleshchevnikov

Reputation: 364

You can try to change display to block for hyperlink and use paddings:

li a {display: block; padding: 30px 10px 30px 10px}

Upvotes: 0

khaustic
khaustic

Reputation: 1

I came up with this to handle vertically-aligned 100% height/width anchors inside containers:

http://jsfiddle.net/khaustic/KDfN6/ markup:

<div class="links one">
    <a href="#">One</a>
</div>
<div class="links two">
    <a href="#">Two Two</a>
</div>

css:

* { 
    /*ie box model forever!*/
    box-sizing:border-box;
    -moz-box-sizing:border-box;
    -webkit-box-sizing:border-box;
}
.links {
    height: 5.0em;
    text-align:center;
    outline: 1px solid #333;
    float:left;
    margin: 0 1.0em;
    overflow:hidden;
}

.links.one { width: 8em; }
.links.two { width: 4em; }

.links a {
    width:10em;
    text-align: center;
    display: table-cell;
    vertical-align:middle;
    height: inherit;
}

Upvotes: 0

Rich
Rich

Reputation: 426

Use display:table-cell; in your li element.

li {
width:200px;
height:200px;
vertical-align:middle;
display:table-cell;
}

This will give you this effect:

enter image description here

Upvotes: 7

sandeep
sandeep

Reputation: 92863

write like this

a{
 display:inline-block;
 vertical-align:middle;
}

& you can give display:table-cell; to it like this

li {
vertical-align:middle;
display:table-cell;
}

but it's not work in IE7 & below

Upvotes: 6

Related Questions