Vertical alignment of elements using CSS. Horizontal and vertical alignment of elements

  • CSS
  • HTML
  • I think many of you who have had to deal with layout have encountered the need to align elements vertically and know the difficulties that arise when aligning an element to the center.

    Yes, there is a special multi-value vertical-align property in CSS for vertical alignment. However, in practice it doesn't work at all as expected. Let's try to figure this out.


    Let's compare the following approaches. Align using:

    • tables,
    • indentation,
    • line-height
    • stretching,
    • negative margin,
    • transform
    • pseudo element
    • flexbox.
    To illustrate, consider the following example.

    There are two div elements, with one of them nested within the other. Let's give them the corresponding classes - outer and inner.


    The challenge is to align the inner element with the center of the outer element.

    First, let's consider the case when the dimensions of the external and internal blocks known. Let's add the rule display: inline-block to the inner element, and text-align: center and vertical-align: middle to the outer element.

    Remember that alignment only applies to elements that have an inline or inline-block display mode.

    Let's set the sizes of the blocks, as well as background colors so that we can see their borders.

    Outer ( width: 200px; height: 200px; text-align: center; vertical-align: middle; background-color: #ffc; ) .inner ( display: inline-block; width: 100px; height: 100px; background-color : #fcc )
    After applying the styles, we will see that the inner block is aligned horizontally, but not vertically:
    http://jsfiddle.net/c1bgfffq/

    Why did it happen? The thing is that the vertical-align property affects the alignment the element itself, not its contents(except when it is applied to table cells). Therefore, applying this property to the outer element did not produce anything. Moreover, applying this property to an inner element will also do nothing, since inline-blocks are aligned vertically relative to adjacent blocks, and in our case we have one inline block.

    There are several techniques to solve this problem. Below we will take a closer look at each of them.

    Alignment using a table

    The first solution that comes to mind is to replace the outer block with a table of one cell. In this case, the alignment will be applied to the contents of the cell, that is, to the inner block.


    http://jsfiddle.net/c1bgfffq/1/

    The obvious disadvantage of this solution is that, from a semantic point of view, it is incorrect to use tables for alignment. The second disadvantage is that creating a table requires adding another element around the outer block.

    The first minus can be partially removed by replacing the table and td tags with div and setting the table display mode in CSS.


    .outer-wrapper ( display: table; ) .outer ( display: table-cell; )
    However, the outer block will still remain a table with all the ensuing consequences.

    Alignment using indentation

    If the heights of the inner and outer blocks are known, then the alignment can be set using the vertical indents of the inner block using the formula: (H outer – H inner) / 2.

    Outer ( height: 200px; ) .inner ( height: 100px; margin: 50px 0; )
    http://jsfiddle.net/c1bgfffq/6/

    The disadvantage of the solution is that it is applicable only in a limited number of cases when the heights of both blocks are known.

    Alignment using line-height

    If you know that the inner block should occupy no more than one line of text, then you can use the line-height property and set it equal to the height of the outer block. Since the content of the inner block should not wrap to the second line, it is recommended to also add the white-space: nowrap and overflow: hidden rules.

    Outer ( height: 200px; line-height: 200px; ) .inner ( white-space: nowrap; overflow: hidden; )
    http://jsfiddle.net/c1bgfffq/12/

    This technique can also be used to align multiline text if you redefine the line-height value for the inner block, and also add the display: inline-block and vertical-align: middle rules.

    Outer ( height: 200px; line-height: 200px; ) .inner ( line-height: normal; display: inline-block; vertical-align: middle; )
    http://jsfiddle.net/c1bgfffq/15/

    The disadvantage of this method is that the height of the external block must be known.

    Alignment using "stretch"

    This method can be used when the height of the external block is unknown, but the height of the internal block is known.

    To do this you need:

    1. set relative positioning to the external block, and absolute positioning to the internal block;
    2. add the rules top: 0 and bottom: 0 to the inner block, as a result of which it will stretch to the entire height of the outer block;
    3. set the vertical padding of the inner block to auto.
    .outer ( position: relative; ) .inner ( height: 100px; position: absolute; top: 0; bottom: 0; margin: auto 0; )
    http://jsfiddle.net/c1bgfffq/4/

    The idea behind this technique is that setting a height for a stretched and absolutely positioned block causes the browser to calculate the vertical padding in an equal ratio if it is set to auto .

    Alignment with negative margin-top

    This method has become widely known and is used very often. Like the previous one, it is used when the height of the outer block is unknown, but the height of the inner one is known.

    You need to set the external block to relative positioning, and the internal block to absolute positioning. Then you need to move the inner block down by half the height of the outer block top: 50% and raise it up by half its own height margin-top: -H inner / 2.

    Outer ( position: relative; ) .inner ( height: 100px; position: absolute; top: 50%; margin-top: -50px; )
    http://jsfiddle.net/c1bgfffq/13/

    The disadvantage of this method is that the height of the indoor unit must be known.

    Alignment with transform

    This method is similar to the previous one, but it can be used when the height of the indoor unit is unknown. In this case, instead of setting a negative pixel padding, you can use the transform property and move the inner block up using the translateY function and a value of -50% .

    Outer ( position: relative; ) .inner ( position: absolute; top: 50%; transform: translateY(-50%); )
    http://jsfiddle.net/c1bgfffq/9/

    Why was it impossible to set the value as a percentage in the previous method? Since percentage margin values ​​are calculated relative to the parent element, a value of 50% would be half the height of the outer box, and we would need to raise the inner box to half its own height. The transform property is perfect for this.

    The disadvantage of this method is that it cannot be used if the indoor unit has absolute positioning.

    Alignment with Flexbox

    The most modern way of vertical alignment is to use Flexible Box Layout (popularly known as Flexbox). This module allows you to flexibly control the positioning of elements on the page, arranging them almost anywhere. Center alignment for Flexbox is a very simple task.

    The outer block needs to be set to display: flex and the inner block to margin: auto . And it's all! Beautiful, is not it?

    Outer ( display: flex; width: 200px; height: 200px; ) .inner ( width: 100px; margin: auto; )
    http://jsfiddle.net/c1bgfffq/14/

    The disadvantage of this method is that Flexbox is supported only by modern browsers.

    Which method should I choose?

    You need to start from the problem statement:
    • To vertically align text, it is better to use vertical indents or the line-height property.
    • For absolutely positioned elements with a known height (for example, icons), the method with a negative margin-top property is ideal.
    • For more complex cases, when the height of the block is unknown, you need to use a pseudo element or the transform property.
    • Well, if you are so lucky that you do not need to support older versions of the IE browser, then, of course, it is better to use Flexbox.

    In CSS, some seemingly simple things are not so easy to do. One of these things is alignment, i.e. when one element needs to be positioned in a certain way relative to another.

    This article presents some ready-made solutions that will help simplify the work of centering elements horizontally and/or vertically.

    Note: Below each solution is a list of browsers indicating the versions in which the specified CSS code works.

    CSS - Center Align Block

    1. Aligning one block to the center of another. In this case, the first and second blocks have dynamic sizes.

    ...
    ...

    Parent ( position: relative; ) .child ( position: absolute; left: 50%; top: 50%; -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50% , -50%); -ms-transform: translate(-50%, -50%); -o-transform: translate(-50%, -50%); ; )

    • Chrome 4.0+
    • Firefox 3.6+
    • Internet Explorer 9+
    • Opera 10.5+
    • Safari 3.1+

    2. Aligning one block to the center of another. In this case, the second block has fixed dimensions.

    Parent ( position: relative; ) .child ( position: absolute; left: 50%; top: 50%; /* width and height of 2 blocks */ width: 500px; height: 250px; /* Values ​​are determined depending on its size */ /* margin-left = - width / 2 */ margin-left: -250px; /* margin-top = - height / 2 */ margin-top: -125px )

    Browsers that support this solution:

    • Chrome 1.0+
    • Firefox 1.0+
    • Internet Explorer 4.0+
    • Opera 7.0+
    • Safari 1.0+

    3. Aligning one block to the center of another. In this case, the second block has dimensions specified in percentages.

    Parent ( position: relative; ) .child ( position: absolute; /* width and height of 2 blocks in % */ height: 50%; width: 50%; /* Values ​​are determined depending on its size in % */ left: 25%; /* (100% - width) / 2 */ top: 25%; /* (100% - height) / 2 */ )

    Browsers that support this solution:

    • Chrome 1.0+
    • Firefox 1.0+
    • Internet Explorer 4.0+
    • Opera 7.0+
    • Safari 1.0+

    CSS - Horizontal Alignment

    1. Aligning one block element (display: block) relative to another (in which it is located) horizontally:

    ...
    ...

    Block ( margin-left: auto; margin-right: auto; )

    Browsers that support this solution:

    • Chrome 1.0+
    • Firefox 1.0+
    • Internet Explorer 6.0+
    • Opera 3.5+
    • Safari 1.0+

    2. Aligning a line (display: inline) or line-block (display: inline-block) element horizontally:

    ...
    ...

    Parent ( text-align: center; ) .child ( display: inline-block; )

    Browsers that support this solution:

    • Chrome 1.0+
    • Firefox 3.0+
    • Internet Explorer 8.0+
    • Opera 7.0+
    • Safari 1.0+

    CSS - Vertical Alignment

    1. Center one element (display: inline, display: inline-block) relative to the other (in which it is located) in the center. The parent block in this example has a fixed height, which is set using the CSS line-height property.

    ...
    ...

    Parent ( line-height: 500px; ) .child ( display: inline-block; vertical-align: middle; )

    Browsers that support this solution:

    • Chrome 1.0+
    • Firefox 3.0+
    • Internet Explorer 8.0+
    • Opera 7.0+
    • Safari 1.0+

    2. Centering one block relative to another vertically by representing the parent as a table, and the child as a cell of this table.

    Parent ( display: table; ) .child ( display: table-cell; vertical-align: middle; )

    Browsers that support this solution:

    • Chrome 1.0+
    • Firefox 1.0+
    • Internet Explorer 8.0+
    • Opera 7.5+
    • Safari 1.0+

    If you know any other interesting tricks or useful ready-made alignment solutions, then share them in the comments.

    The CSS vertical-align property is responsible for the vertical alignment of text and images on the page. The important feature is that it only works with table elements, inline and inline-block elements. Supported by all modern browsers.

    Syntax CSS vertical-align

    ... vertical-align : value ; ...
    • baseline - alignment to the baseline of the ancestor (or simply the lower boundary of the parent)
    • bottom - align to the bottom of the line (or the element that is located below all)
    • middle - align the element's midpoint to the parent's baseline plus half the parent's height
    • sub - display occurs below the line (looks like a subscript)
    • super - display occurs above the line (as a superscript)
    • text-bottom - align the bottom border of the element to the bottom edge of the line
    • text-top - align the top border of the element to the top edge of the line
    • top - align the top edge of the element to the top of the tallest element on the line
    • inherit - inherits the value of the parent
    • value - indicated in pixels. A positive number shifts upward relative to the baseline. Negative down
    • interest - indicated in percentages. A positive number shifts upward relative to the baseline. Negative down

    Default vertical-align value:

    • baseline (for inline elements)
    • middle (for table cells)

    Vertical alignment in tables

    The most common use of vertical-align is in table cells. In the tag

    use the valign attribute.

    CSS valign syntax for tables

    Where value can take the following values:

    • baseline - alignment to the baseline of the first text line
    • bottom - align to the bottom edge of the table cell
    • middle - alignment to the middle of the cell
    • top - align to the top edge of the cell

    For example:

    or
    Align to top
    Center alignment
    Bottom alignment
    Align to top
    Center alignment
    Bottom alignment

    Examples with vertical alignments

    Example 1. Vertical-align values: baseline, bottom, top, sub


    Aligned text vert_align_baseline
    Aligned text vert_align_bottom
    Aligned text vert_align_top
    Text with vert_align_sub alignment

    Example 2: vertical-align values: absolute values ​​and percentages

    Below are examples of vertical alignment with absolute value and percentages.





    Converts to the following on the page:

    Source string. Text aligned 10 pixels up
    Source string. Text aligned 5 pixels down
    Source string. Text aligned 50% up
    Source string. Text aligned 30% down

    Note

    The vertical-align: middle value does not align the inline element to the center of the largest element in the line (as one would expect). Instead, the value middle aligns the element relative to a hypothetical lowercase "X" (also called x-height).

    To access vertical-align from JavaScript, you need to write the following construction:

    object.style.verticalAlign ="VALUE "

    The problem of vertically centering elements in CSS has a number of ready-made solutions. The choice of alignment method in each individual case depends on the type, size, positioning of elements and other properties specified for them.

    Below are some popular vertical alignment techniques among layout designers. It shows how they work and for what cases each of them is most suitable.

    Here are two div elements:



    Each method will be used to align the indoor unit with the center of the outdoor unit.

    line-height for one line

    When the parent occupies one line of text and the height of the child is known, the line-height property can be applied. The property value must be equal to the height of the outer block. This only works for one line, so it's useful to add overflow: hidden and white-space: nowrap to the child.

    It will not be possible to use the percentage notation line-height=100%, because 100% in this case is the font height.

    Container (
    height: 300px;
    line-height: 300px;
    }

    Inner(
    white-space: nowrap;
    overflow: hidden;
    }

    The method is applicable only if the height of the external block is known.

    Table with vertical-align

    A table is ideal for vertical alignment of elements. In order not to violate semantics, it is better to create table elements using CSS. The position of the cell's contents is controlled by vertical-align. There are four values ​​for this property in tables:

    Baseline - default;
    . bottom — content at the bottom of the cell;
    . middle — content in the middle of the cell;
    . top — content at the top of the cell.

    In the first example, a single table cell becomes the outer block.

    Container (
    display: table-cell;
    vertical-align: middle;
    }

    The good thing about this method is that it works for elements without a given height, but in some cases its use is hampered by the fact that the outer block, like any table cell, adjusts its width to its contents, and you can stretch it only by explicitly setting the width for width. For a cell without a table, percentages do not work adequately.

    This shortcoming is corrected by wrapping the cell in its parent with the display:table property. The size of this element can be set as a percentage. The final code will look like this:

    Outer-wrapper (
    display: table;
    }

    Container (
    display: table-cell;
    vertical-align: middle;
    }





    Position: absolute + negative margin

    The method is used when the height of the internal element is known. It may be unknown to the external unit. The parent is given relative positioning, and the child within it is given absolute positioning.

    A top property value of 50% causes the nested element to be positioned with its top edge in the middle of the outer block. All that remains is to raise its negative margin-top by half its own height so that it stands exactly in the center of the vertical.

    Container (
    position: relative;
    }

    Inner(
    height: 140px;
    position: absolute;
    top: 50%;
    margin-top: -70px;
    }

    The disadvantage of this method is the need to know the height of the child.

    Alignment in line with vertical-align

    The alignment of inline and inline-block elements, including images and icons, in the surrounding text is accomplished by the vertical-align property. Unlike a table, in this case the entire set of its values ​​specified in the specification works.

    If the height of the parent is known, this property can be used to center multiline text.

    For the outer block, the centering of one line is prescribed.

    Container (
    height: 140px;
    line-height: 140px;
    }

    The line-height value for the inner block is redefined to normal or to any desired value. It is also given the alignment vertical-align: middle and conversion to an inline-block type - display: inline-block.

    Inner(
    display: inline-block;
    line-height: normal;
    vertical-align: middle;
    }

    The disadvantage of this method is that you need to know the height of the parent.

    Alignment with transform

    The translateY function of the transform property allows you to center an inner block of unknown height. To do this, the parent must be positioned relatively and the child absolutely.

    The top property with a value of 50% lowers the inner block so that its top edge is positioned in the middle of its parent. The translateY value: -50% raises the element to half its own height and thereby aligns the vertical centers of the blocks.

    Container (
    position: relative;
    }

    Inner(
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    }

    The disadvantage of this technique is the limited support for transform functions in the IE browser.

    Alignment via pseudo-element

    The method works when the height is unknown for neither the first nor the second block. An inline-block pseudo-element is added inside the parent using before or after. The height of the added element must be equal to the height of the parent - height: 100%. The vertical alignment of the content is set using vertical-align: middle.

    Using vertical-align: middle, the inner block is aligned relative to this pseudo-element. Because the parent and child have the same height, the inner element, while being vertically aligned with the pseudo-element, is also centered with the outer box.

    Container:before (
    content: "";
    height: 100%;
    vertical-align: middle;
    display: inline-block;
    }

    Inner(
    display: inline-block;
    vertical-align: middle;
    }

    Universal method. Does not work if the indoor unit is set to absolute positioning.

    Flexbox

    The newest and easiest way to align elements vertically. Flexbox allows you to arrange elements of a Web page as you please. To center a block, you just need to set display: flex for the parent and margin: auto for the child.

    Container (
    display: flex;
    width: 320px;
    height: 140px;
    }

    Inner(
    width: 120px;
    margin: auto;
    }

    Flexbox only works in modern browsers.

    Choosing a method

    Which vertical alignment technique to use depends on the task and the limitations that may be present in any particular case.

    The height of the elements is unknown

    In this situation, you can use one of four universal methods:

    1. Table. The parent becomes a table cell created in HTML or via display-table/display-cell. This parent element is given vertical-align: middle.

    2. Pseudo-element. For the outer block, an inline-block pseudo-element is created with width=100% and vertical-align: middle. The child is given display: inline-block and vertical-align: middle. The method does not work only when the internal block is given absolute positioning.

    3. Transform. The parent gets position: relative. The child is given position: absolute, top: 50% and transform: translateY(-50%);

    4. Flexbox. The outer block is set to display: flex, the inner block is given margin: auto.

    Only the height of the child is known

    The external unit is positioned relative; The inner element is given an absolute positioning, top: 50% and a margin-top equal to half its height.

    One line per block with known height

    The outer block is given a line-height property with a value equal to its height.

    The height of the outer block is known, but the inner element is not.

    The parent is given a line-height equal to its height. The child's line-height is redefined to normal or any desired value, and display: inline-block and vertical-align: middle are given to it.

    When laying out a page, it is often necessary to perform center alignment using the CSS method: for example, centering the main block. There are several options for solving this problem, each of which sooner or later has to be used by any layout designer.

    Center text alignment

    Often, for decorative purposes, it is necessary to set the text to center alignment; CSS in this case allows you to reduce layout time. Previously, this was done using HTML attributes, but now the standard requires text to be aligned using style sheets. Unlike blocks, for which you need to change the margins, in CSS, centering text is done using a single line:

    • text-align:center;

    This property is inherited and passed on from the parent to all descendants. Affects not only the text, but also other elements. To do this, they must be inline (for example, span) or inline-block (any blocks that have the display: block property set). The latter option also allows you to change the width and height of the element, and adjust the indents more flexibly.

    Often on pages, align is assigned to the tag itself. This immediately invalidates the code, since the W3C has deprecated the align attribute. Using it on a page is not recommended.

    Aligning a block to the center

    If you need to center a div, CSS offers a pretty convenient way: using margins. Indents can be set for both block and inline-block elements. The property value should be 0 (vertical padding) and auto (automatic horizontal padding):

    • margin:0 auto;

    Now this option is recognized as absolutely valid. Using external padding also allows you to set the image to be centered: it allows you to solve many problems related to the positioning of an element on the page.

    Align a block left or right

    Sometimes CSS center alignment is not required, but you need to place two blocks side by side: one on the left edge, the other on the right. For this purpose, there is a float property, which can take one of three values: left, right or none. Let's say you have two blocks that need to be placed side by side. Then the code will be like this:

    • .left (float:left;)
    • .right(float:right)

    If there is also a third block, which should be located under the first two blocks (for example, a footer), then it needs to be given the clear property:

    • .left (float:left;)
    • .right(float:right)
    • footer (clear:both)

    The fact is that blocks with the classes left and right fall out of the general flow, that is, all other elements ignore the very existence of aligned elements. The clear:both property allows the footer or any other block to see elements that have fallen out of the flow and prohibits float on both the left and right. Therefore, in our example, the footer will move down.

    Vertical alignment

    There are times when it is not enough to set the center alignment using CSS methods; you also need to change the vertical position of the child block. Any inline or inline-block element can be nested at the top or bottom edge, in the middle of a parent element, or in any location. Most often, the block needs to be aligned to the center; for this, the vertical-align attribute is used. Let's say there are two blocks, one nested inside the other. In this case, the inner block is an inline-block element (display: inline-block). You need to align the child block vertically:

    • top alignment - .child(vertical-align:top);
    • center alignment - .child(vertical-align:middle);
    • bottom alignment - .child(vertical-align:bottom);

    Neither text-align nor vertical-align affects block elements.

    Possible problems with aligned blocks

    Sometimes centering a div using CSS can cause a little trouble. For example, when using float: let's say there are three blocks: .first, .second and .third. The second and third blocks lie in the first. The element with class second is left aligned, and the last block is right aligned. After leveling off, both fell out of the flow. If the parent element does not have a height set (for example, 30em), then it will no longer stretch to the height of its child blocks. To avoid this error, use a “spacer” - a special block that sees .second and .third. CSS code:

    • .second(float:left)
    • .third(float:right)
    • .clearfix(height:0; clear: both;)

    The pseudo-class:after is often used, which also allows you to return the blocks to their place by creating a pseudo-spacer (in the example, a div with the container class lies inside.first and contains.left and.right):

    • .left(float:left)
    • .right(float:right)
    • .container:after(content:""; display:table; clear:both;)

    The above options are the most common, although there are several variations. You can always find the simplest and most convenient way to create a pseudo-spacer through experimentation.

    Another problem that layout designers often encounter is the alignment of inline-block elements. A space is automatically added after each of them. The margin property, which is set to a negative indent, helps to cope with this. There are other methods that are used much less frequently: for example, zeroing. In this case, font-size: 0 is written in the properties of the parent element. If there is text inside blocks, then the required font size is already returned in the properties of inline-block elements. For example, font-size:1em. This method is not always convenient, so the option with external indents is much more often used.

    Aligning blocks allows you to create beautiful and functional pages: this includes the layout of the overall layout, the arrangement of products in online stores, and photographs on a business card website.