Css vertical alignment with nested divs

This question arose due to a fix proposed to this related question

I have 3 nested divs: outer, inner and element.

<div class="outer"> <div class="inner"><div class="item"></div></div> </div> 

Given the following basic CSS:

 .outer{ width:50%; height:100px; border: 1px solid red; position:relative; overflow-x:hidden; box-sizing:border-box; } .inner{ border:1px solid blue; height:100%; position: absolute; box-sizing: border-box; line-height:98px; } .item{ width:100px; height:94px; background-color:yellow; display: inline-block; border:1px solid green; box-sizing:border-box; vertical-align:middle; } 

The challenge is to center the div β€œelement” vertically with equal (or absent) gaps above / below, and vertical scroll bars do not appear.

Codepen is here

Update:

As indicated below, I must add that several elements of different heights should be centered. At the moment, the best answer is to add a negative field to each element, which leads to the following: http://codepen.io/anon/pen/dYWEYZ

However, it smells bad (to me), because it requires an offset, which depends on 3 other properties.

+1
source share
3 answers

A simple solution is http://codepen.io/anon/pen/jbmRjo

to add this to your .item class:

 margin-top: -5px; 

This is due to the borders on the outer and inner classes, as well as the line height of the inner class. If you make 2px borders instead of 1px, then the top border of the field will become -9px. If you leave the border at 1px and make the line height 96px, the upper border of the field will become -3px.

So why can't you use the upper bound of the negative field?

0
source

If you use flexbox, this is easily achieved:

 .inner{ border:1px solid blue; height:100%; position: absolute; box-sizing: border-box; line-height:98px; display:flex; align-items:center; } 
0
source

You can use display: table-cell; to obtain the desired vertical centering:

 .outer{ width:50%; height:100px; border: 1px solid red; position:relative; overflow-x:hidden; box-sizing:border-box; } .inner{ border:1px solid blue; height:100%; position: absolute; box-sizing: border-box; line-height:98px; display: table; //must change this as well } .item{ width:100px; height:94px; background-color:yellow; border:1px solid green; box-sizing:border-box; vertical-align:middle; display:table-cell; //update display type } 
0
source

Source: https://habr.com/ru/post/1233171/


All Articles