📜 ⬆️ ⬇️

1001st vertical alignment method

Much has been said about the vertical alignment of a block of unknown height in the center or bottom of a parent. There are display-based-table-cell-based methods for good browsers (without quotes) and expression for IE, methods based on relative positioning (they may not work well when overflowed). This post will describe a method that works on features of such a powerful display as a built-in block (display: inline-block).

screen-capture


Markup



Immediately make a reservation, the method has a disadvantage, namely, an extra element. The markup will look like the one below:
<div class="parent">
<div class="child">, . </div>
<div class="helper"></div>
</div>

')
The described method is based on the fact that vertical-align: middle works fine for inline elements. Since in our case inline elements are not suitable, a mixed type (display: inline-block) is used to emulate them. Thus, if we manage to present the internal contents of div.parent as a string, and div.child in it to center in the center, using vertical-align: middle, we will achieve the result.


Styles



The first idea that arises is to set the height of the inner content line with the help of a line-height of 100% of the height div.parent - because entails changing the height of the line inside div.child, and redefining the line-height inside div.child does not lead to a positive result. That same strut from the 90s comes to the rescue. The added div.helper block should have a div.parent height, thereby pushing our string apart, as we need. As a result, you can select a meaningful CSS:

.child {
...
display:inline-block;
vertical-align:middle;
}
.helper {
...
display:inline-block;
vertical-align:middle;
height:100%;
width:0px;
}



Struggling with IE



Apply a hack for IE, which allows you to use display: inline-block for block elements (as well as a hack for FF2):

.child {
...
display:-moz-inline-box;
display:inline-block;
vertical-align:middle;
zoom:1;
//display:inline;
}
.helper {
...
display:-moz-inline-box;
display:inline-block;
vertical-align:middle;
height:100%;
width:0px;
zoom:1;
//display:inline;
}



Result



Here is such a simple way. A working example can be found here .

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


All Articles