Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can line-height Attribute Inherit Parent Div's Height Property Or Access Height Property Of The Div To Which It Belongs?

I have a div with height 50px that contains a child div. The height of the child div is inherited from the parent by using the css attribute/value pair: height: 100%.

    <div style="height: 50px;">
        <div style="height: 100%;">Some Text</div>
    </div>            

I want to verically align the text in the child div and to do so I add the line-height property to the child div.

    <div style="height: 50px;">
        <div style="height: 100%; line-height: 50px;">Some Text</div>
    </div>            

Notice that for line-height I have to explicitly define the height as 50px.

The child div can inherit the height property from the parent (using height: 100%) but for line-height I must explicitly set the value?

If so, this is (IMO) kindof messy because let's say I have a div that is nested 10 levels deep and it inherits the height property all the way down. Then if I want to vertically align the text within this div I have to not only hard-code the value to equal the height of the upper-most parent div but I have navigate through my code to find the parent that explicitly defines the height.

Note that I don't want to define line-height at the parent level and then use inherit at the child node to get the value.

It would be nice if there were a way to set line-height equal to the height of the div that it resides in. Perhaps the syntax would look like the following (totally made up):

<div style="height: 100%; line-height: from-property('height');">Some Text</div>

Where line-height uses the from-property method to access the height property. (Yes, I know having a method such as from-property introduces the potential for a circular dependency so perhaps some other way would be better. I am simply using it to express what I would like to have.)

Thanks!

Jan

like image 244
Jan Tacci Avatar asked Nov 12 '12 15:11

Jan Tacci


1 Answers

line-height is designed to set spacing between lines, and use this to align something vertically is not a good option. Unless you are sure the content will always in one line.

Use this to make it vertical center, not perfect though.

div.parent {
  display: table-cell;
  vertical-align: middle;
}
like image 117
xiaoyi Avatar answered Sep 30 '22 02:09

xiaoyi