Vertical alignment on CSS, line-height and vertical-align middle
When laying out pages, it is often necessary to align the content of an element in the middle, both horizontally and vertically. While horizontal alignment is easy, vertical alignment can be difficult. Such alignment may be needed for various widgets on the site, for example, you need to align the picture strictly in the middle. Let's see how to solve the vertical alignment problem.
Previously, pages were typeset using tables (tabular layout), but now it is customary to use block layout based on div tags (block layout). This means that today it is better not to use tables for creating blocks, although aligning the contents of a table cell was quite simple before, which cannot be said about aligning in a div block. The valign attribute was actively used in table layout.
But there are solutions. Several techniques can be used to vertically align elements. For example, the line-height method . It is more suitable for aligning a line of text. This method works in all browsers. The value of 100px in this example is chosen arbitrarily, choose the one you need yourself, depending on your needs.
& lt; div class = "parent">
& lt; div class = "child"> Line of text & lt; / div>
& lt; / div>
.child {
line-height: 100px;
}
Another way is as follows. If the text-align: center CSS property is used to horizontally align the content of the block, then the vertical-align: middle property is used for vertical alignment. This property only works for inline elements, but can be adapted for block elements as well. This is the answer to the question why vertical-align: middle does not work, which can often be found on various forums and portals. You need to make a special display style for such a block using the display property, example below:
& lt; div class = "parent">
& lt; div class = "child"> Content & lt; / div>
& lt; / div>
.parent {
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
}
Thus, making vertical alignment in CSS is quite simple, the article shows the most popular methods.
Latest articles
- 03.04.24IT / Уроки PHP Уроки простыми словами. Урок 3. Все операторы PHP с примерами, с выводом работы кода на экран.
- 02.04.24IT / Уроки PHP Уроки простыми словами. Урок 2. Типы данных в PHP с примерами.
- 02.04.24IT / Уроки PHP Уроки простыми словами. Урок 1. Коротко о языке веб-программирования PHP. Основы синтаксиса.
- 09.11.23IT / Database Errors when migrating from MySQL 5.6 to 5.7 and how to fix them - database dump import failed with an error or INSERT does not work. Disabling STRICT_TRANS_TABLES strict mode or using IGNORE
- 08.07.22IT / Misc Convert office files DOC, DOCX, DOCM, RTF to DOCX, DOCM, DOC, RTF, PDF, HTML, XML, TXT formats without loss and markup changes