0

So i'm trying to center a text in the middle of a div. I looked half of the website, and it looks like i have to do smthg like that :

.container{
    width:100px;
    height:200px;
    display:table-cell;
    vertical-align: middle;
    line-height: normal;  
}

But it doesn't work...

Here's what i do :

HTML:

    <div id="left_bot" class="menu_button"><span class="text_menu_button">Div1</span></div>

CSS:

.menu_button{
    width:37%;
    height: 44%;
    text-align: center;
    display: table-cell;
    vertical-align: middle;
    line-height: normal;  
    font-size: 48px;
}
#left_top{
    top:0;
    float:left;
    background-color: red;
    margin: 2% 1% 1% 2%;
}

But i still have the text in the center, but not in the middle of the div.

I don't get why, i tried to insert the vertical-align on a .text_menu_button but still nothing :x

Thx

Bobby
  • 4,372
  • 8
  • 47
  • 103
  • You can use flexbox and answer already exists here - http://stackoverflow.com/questions/19026884/flexbox-center-horizontally-and-vertically – Eugene Obrezkov Aug 01 '14 at 14:03
  • 1
  • yes sorry, is the same, i just have 4 divs. And @EugeneObrezkov i looked the answers, but i don't get why it doesn't work... the vertical-align should do this, but he do nothing... – Bobby Aug 01 '14 at 14:06
  • @user3241192 read answer provided below more clearly. You must set ```display: flex```, ```align-items: center``` and ```justify-content: center```. – Eugene Obrezkov Aug 01 '14 at 14:09

2 Answers2

2

The .container should have display: table; and .menu-bottom display: table-cell; to apply table like behavior with CSS.

HTML

<div class="container">
    <div id="left_bot" class="menu_button"><span class="text_menu_button">Div1</span>
    </div>
</div>

CSS

.container {
    height:200px;
    display:table;
    width: 100%;
}
.menu_button {
    text-align: center;
    display: table-cell;
    vertical-align: middle;
    font-size: 48px;
}

demo: http://jsfiddle.net/ALB6D/1/

Henri Hietala
  • 3,021
  • 1
  • 20
  • 27
  • OK so this was the problem... i didn't added the display: table; I don't get why we have to do that, but i will look the internet. Thx for your time – Bobby Aug 01 '14 at 14:09
0

An easy way to center a text vertically is to set the line-height equal to the height.

div { font-size: 30px; line-height: 100px; height: 100px; }

Demo: jsFiddle