Search code examples
htmlcssvertical-alignmentfont-size

Vertically align text divs with responsive font-size within a div


I have this div :

enter image description here

and I tried making the font-size of the text responsive using this code :

font-size:calc(xx + 1.5vw);

If I make the screen smaller the headers are not vertically aligned :

enter image description here

HTML :

<div id="topsection">
<div id="header1">HEADER 1</div>
<div id="header2">Header 2</div>
</div>

CSS :

#header1 {
margin-left:220px;
font-size:calc(20px + 1.5vw);
color:#fff;
}

#header2 {
color: #fff;
margin-left:220px;
font-size:calc(9px + 1.5vw);
}

#topsection {
background-color:#222939;
width:100%;
height:75px;
z-index:1;
position:absolute;
top:10px;
left:0;
color:white;
}

I tried changing the CSS for the headers like this :

#header1 {
display: inline-block;
vertical-align: middle;
margin-left:220px;
font-size:calc(20px + 1.5vw);
color:#fff;
}

#header2 {
display: inline-block;
vertical-align: middle;
margin-left:220px;
font-size:calc(9px + 1.3vw);
color: #fff;
}

but now it looks like this :

enter image description here


Solution

  • You need a content div to center in the middle. See the example below. Have only tested this in Chrome.

    .toolbar{
    background-color:#222939;
    width:100%;
    height:195px;
    line-height:195px;
    z-index:1;
    position:absolute;
    top:0;
    left:0;
    color:white;
    
    
    }
    .toolbar .content{
    display:inline-block;
    vertical-align: middle;
    }
    .toolbar .title {
    
    
    line-height:1;
    
    font-size:calc(20px + 1.5vw);
    color:#fff;
    }
    
    .toolbar .subtitle {
    
    
    line-height:1;
    font-size:calc(9px + 1.5vw);
    color: #fff;
    }
     <div class="toolbar">
    <div class="content">
    <div class="title">HEADER 1</div>
    <div class="subtitle">Header 2</div>
    </div>
    </div>

    Final code

    <!DOCTYPE html>
    <html>
    <head>
        <style>
            .toolbar{
    background-color:#222939;
    width:100%;
    height:195px;
    line-height:195px;
    z-index:1;
    position:absolute;
    top:0;
    left:0;
    color:white;
    }
    .toolbar .content{
    display:inline-block;
    vertical-align: middle;
    }
    .toolbar .title {
    line-height:1;
    font-size:calc(20px + 1.5vw);
    color:#fff;
    }
    
    .toolbar .subtitle {
    line-height:1;
    font-size:calc(9px + 1.5vw);
    color: #fff;
    }
        </style>
    
        </head>
    <body>
         <div class="toolbar">
    <div class="content">
    <div class="title">HEADER 1</div>
    <div class="subtitle">Header 2</div>
    </div>
    </div>
    </body>
    </html>