Shubham Kanodia
Shubham Kanodia

Reputation: 6236

How to center text vertically inside a div with dynamically changing height?

I am trying to make a website navbar using divs instead of the usual lists. The divs are inline-blocks and on hover, the navbar expands. This should cause all the inner divs to expand (height:100%), while retaining centered text. I want to use only html and css.

One way is to set line-height and use vertical-align:middle. But since the div expands vertically in a dynamic manner, I cannot give a static value to line-height. I tried using line-height:100%, but that doesn't seem to help!


The html:

<html>
  <head>
    <title>Hello</title>

    <link rel="stylesheet" type="text/css" href="style2.css">
  </head>

  <body>
      <div id="headContainer">
      <a href="/HOME"><div id="logo"></div></a>
        <div id="rightBar">
            <div class="navelement"><a href="HOME">HOME</a></div>
            <div class="navelement"><a href="HOME">HOME</a></div>
            <div class="navelement"><a href="HOME">HOME</a></div>
            <div class="navelement"><a href="HOME">HOME</a></div>
        </div>
      </div>

  </body>

The Css:

* {
    margin: 0;
    padding: 0;
}
#headContainer {
    height: 80px;
    width: 100%;
    background-color: white;
    border: 5px solid red;
}
#headContainer:hover {
    height: 100px; /*Dynamically change navbar height on hover, thus changing the height of all children*/
}

#rightBar {
    line-height:100%;
    display: inline-block;
    width:80%;
    height: 100%;
    border: 5px solid blue;
    vertical-align: middle;
}

.navelement{
    display: inline-block;
    height: 100%;
    border:2px solid cyan;
}

The JSFIDDLE: http://jsfiddle.net/GBz3s/1/

Upvotes: 0

Views: 71

Answers (2)

Perry
Perry

Reputation: 53

If you're using a precise height for your nav, then you can use a hack with padding by declaring the height, floating the divs, doing some math, and making adjustments accordingly. You can see an updated fiddle here: http://jsfiddle.net/Perry_/GBz3s/3/

.navelement{
    float: left;
    width: 24.25%; 
    border:2px solid cyan;
    position: relative;
    height: 70px;
    padding: 25px 0 0 0;
}

    #rightBar:hover .navelement {
        height: 90px;
        padding: 45px 0 0 0;
    }

Upvotes: 1

Tushar
Tushar

Reputation: 4418

You can do it like this

you need to give display: inline-table; to .navelement and

display: table-cell; vertical-align: middle; to .navelement a

CSS

.navelement{
    display: inline-table;
    height: 100%;
    border:2px solid cyan;
}
.navelement a {
    display: table-cell;
    vertical-align: middle;
}

Upvotes: 0

Related Questions