0

I have some buttons with text inside. What I'm trying to do is to align them to middle from vertical and horizontal.On the example I have 3 buttons (the left one is bigger in purpose)

When it a long text its placed on some rows on the middle of the button - it is not starting from the vertical middle but looks fine, but when I get short text it ("oneWord") then attached to the top side and all looks messy.

enter image description here

I read some exampels:

How do I vertically align something inside a span tag? Button's text vertical align

How do I vertically align something inside a span tag?

vertical-align:middle for text in button

After all this I set my style to:

.spanContainer {
    height: 70px;
}

.spanContainer span {
    height: 70px;
    display: table-cell;
    vertical-align: middle;
    white-space: normal;
}

After All the changes I'm getting those result:

On vertical side it is in middle(short and long text) - O.K, but on the horizontal for short text it start from the left side

enter image description here

The problem is that display: table-cell float it to left side for short text! How can I create those buttons so even if I have one word or a long text they all will start on the middle of the button on horizontal and vertical?

Community
  • 1
  • 1
Dima
  • 443
  • 2
  • 9
  • 23

1 Answers1

1

Try the snippet below

CSS

.spanContainer {
    height: 70px;
    display: table;
    width: 200px;
}

.spanContainer span {
    background-color: #ff0000;
    display: table-cell;
    text-align: center;
    vertical-align: middle;  
} 

Or don't use width on spanContainer, use some padding on the inner span instead

.spanContainer {
    height: 70px;
    display: table;
}

.spanContainer span {
    background-color: #ff0000;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    padding: 0px 20px 0px 20px; 
} 

HTML

<span class="spanContainer">
  <span>something</span>
</span>

First solution | Second solution

hex494D49
  • 9,109
  • 3
  • 38
  • 47
  • the `display: table` in `spanContainer` actually puts it in the middle but it re-size the width button, I cant use `width:100%` because those buttons are width fixed from from beginning – Dima Aug 14 '14 at 16:27
  • @Dima Well, your button may be 200px wide as well ;) – hex494D49 Aug 14 '14 at 16:30
  • @Dima I added another solution; so, you don't have to specify `width` of the `spanContainer`, you may add some `padding` to the inner `span` – hex494D49 Aug 14 '14 at 16:35
  • @Dima Actually you don't need even `padding` on the inner `span` but in that case how would you see that it's horizontally centered :) If there's no `width` or `padding`, the width of an element will be equal to the content inside. – hex494D49 Aug 14 '14 at 16:43