mari
mari

Reputation: 229

Display text in the middle of box (vertically)

I have a box of fixed width and height, I have a link in it, i want to display the link in the center of box (vertically). Please see this jsfiddle to see the problem

Demo: http://jsfiddle.net/a5hP3/

Here's code anyway:

HTML:

<div class="box">
    <a href="#">put it down, in center of box</a>
</div>

CSS:

.box
{
   width: 200px;
   height: 300px;
   border:1px solid green;
}

.box a{
      vertical-align:middle; //doesnt work
}

Upvotes: 1

Views: 21178

Answers (5)

Prusprus
Prusprus

Reputation: 8065

There are two solutions:

First you can set the line-height of your div equal to its height. Unfortunately for this, you need to remember to update the line-height whenever you change the div's height dimension.

Another solution is to place your text within a div that's styled to be displayed as a table-cell with a vertical alignement. This would be similar to placing your text within a table and setting the vertical alignment on its cells:

<div style="outline:#000 thin solid; display:table-cell; height:300px; width:700px; vertical-align:middle">
    Some Text
</div>

Upvotes: 1

Serj Sagan
Serj Sagan

Reputation: 30218

This is a problem better handled by javascript. (I'm using jQuery here): http://jsfiddle.net/a5hP3/15/

Upvotes: 0

Sparky
Sparky

Reputation: 98738

Make the line-height the same as the container height...

http://jsfiddle.net/a5hP3/1/

Note: This solution only works when there is one line of text.

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382806

SEE DEMO


CSS:

.box
{
   width: 200px;
   height: 300px;
   border:1px solid green;
   position:relative;
}

.box a{
      display:block;
      position:absolute;
      top:45%;
      left:10% /* adjust based on link width */
}

Upvotes: 0

James Montagne
James Montagne

Reputation: 78690

You can set the line-height equal to the height:

.box
{
   width: 200px;
   height: 300px;
   border:1px solid green;
   line-height: 300px;
}

http://jsfiddle.net/a5hP3/3

Upvotes: 2

Related Questions