Tom Nolan
Tom Nolan

Reputation: 1957

How to center vertical text within a div?

I'm trying to make a simple bar graph using an unordered list. I've got text within each of the bars and have it rotated so that it is vertical. The graph is responsive so the width of the bars shrink when the screen is shrunk.

<div id="chart">
  <ul id="bars">
    <li><div data-percentage="85" class="bar"><span>HTML</span></div></li>
    <li><div data-percentage="85" class="bar"><span>CSS</span></div></li>
    <li><div data-percentage="60" class="bar"><span>jQuery</span></div></li>
    <li><div data-percentage="60" class="bar"><span>PHP</span></div></li>
    <li><div data-percentage="35" class="bar"><span>MySQL</span></div></li>
    <li><div data-percentage="85" class="bar"><span>Worpress</span></div></li>
  </ul>
</div>

The CSS and jQuery associated can be found with the jsFiddle: http://jsfiddle.net/8QVa6/

When the bars width decrease, the text is cut off to the right, any idea what CSS I'm missing to keep it centered the entire time?

Upvotes: 2

Views: 80

Answers (2)

try-catch-finally
try-catch-finally

Reputation: 7624

I'd use top: 50% with position: relative on the label span elements. It needs to be display: block for this to work.

#chart #bars li .bar span {
    color: #fff;
    display: block;
    -webkit-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);
    -o-transform: rotate(-90deg);
    -ms-transform: rotate(-90deg);
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);

    position: relative;
    top: 50%;

    margin-top: -10px; /* about half line height */
}

The margin: -10px is neccessary to compensate the line height after rotation. You can leave it away if it's not so bad if a label is not exactly centered.

See the fork: http://jsfiddle.net/Nb53Z/2/

Upvotes: 1

Melvinr
Melvinr

Reputation: 534

You are using display:inline-table on the span, you need to add display: table; to the parent

#chart #bars li .bar {
  display: table;
  width: 90%;
  margin-left: 10%;
  margin-bottom:10px;
  position: absolute;
  bottom: 0;
}

Upvotes: 1

Related Questions