Align text vertically inside div with percentage of height and width?

I know how to align text vertically inside a div, but I'm not sure how to do this if the div has a percentage height and width. Here is my code:

    <div id="header">
        <h1>Home</h1>
    </div>

    #header {
        background-color: red;  
        color: white;
        text-align: center;
        vertical-align: middle;
        width: 100%; 
        height: 15%;
    }

Now on my webpage, the text in the div was aligned horizontally, but not vertically. How to fix this problem? Can you also try to explain your answers and keep them as simple as possible (I'm still relatively new to HTML / CSS). Thank.

+4
source share
6 answers

Try giving display:inline-blockyour h1 tag.

Demo

0
source

flexbox , .

:

display:flex;
justify-content: center; //horizontal centering
align-items:center; //vertical centering

FIDDLE

. , , , , flexbox , , (, h1 ).

+6

line-height height :

#header {
    background-color: red;  
    color: white;
    text-align: center;
    vertical-align: middle;
    width: 100%; 
    height: 15%;
    line-height: 0.15em;
}
0

:

display:inline-block

h1

example: http://jsfiddle.net/24pwprvf/

0

display:table:

#header {
    background-color: red;  
    color: white;
    text-align: center;
    vertical-align: middle;
    width: 100%; 
    height: 15%;
    display: table;/*Add display:table*/
}

display: table , . - ,

.

0

, .

You can get the same effect by putting "display: inline-block" in either the #header div or the hhead C # header style.

The first part is not recommended. Best practice would be to use it only in h1 style.

0
source

All Articles