• Methods for vertical center alignment in CSS. A Complete Guide to Centering a DIV Element

    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 set to 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 value is redefined to normal or any desired value, and display: inline-block and vertical-align: middle are given to it.

    Very often in layout it is necessary to center some element horizontally and/or vertically. Therefore, I decided to make an article with different ways of centering so that everything is at hand in one place.

    Horizontal alignment margin: auto

    Horizontal alignment using margin is used when the width of the centered element is known. Works for block elements:

    Elem ( margin-left: auto; margin-right: auto; width: 50%; )

    Specifying auto for the right and left margins makes them equal, which centers the element horizontally within the parent block.

    text-align: center

    This method is suitable for centering text within a block. text-align: center:

    Alignment with text-align .wrapper ( text-align: center; )

    I'm center aligned

    position and negative margin left

    Suitable for centering blocks of known width. We give the parent block position: relative to position relative to it, the centered element position: absolute , left: 50% and a negative margin-left whose value is equal to half the width of the element:

    Alignment with position .wrapper ( position: relative; ) .wrapper p ( left: 50%; margin: 0 0 0 -100px; position: absolute; width: 200px; )

    I'm center aligned

    display: inline-block + text-align: center

    The method is suitable for aligning blocks of unknown width, but requires a wrapper parent. For example, you can center a horizontal menu this way:

    Alignment with display: inline-block + text-align: center; .navigation ( text-align: center; ) .navigation li ( display: inline-block; )

    Vertical alignment line-height

    To align one line of text, you can use the same height and line spacing values ​​for the parent block. Suitable for buttons, menu items, etc.

    line-height .wrapper ( height: 100px; line-height: 100px; )

    I'm vertically aligned

    position and negative margin up

    An element can be aligned vertically by giving it a fixed height and applying position: absolute and a negative margin up equal to half the height of the element being aligned. The parent block must be given position: relative:

    Wrapper ( position: relative; ) elem ( height: 200px; margin: -100px 0 0; position: absolute; top: 50%; )

    This way, using positioning and negative margins, you can center an element on the page.

    display: table-cell

    For vertical alignment, the display: table-cell property is applied to the element, which forces it to emulate a table cell. We also set its height and vertical-align: middle . Let's wrap all this in a container with the dislpay: table; property. :

    Vertical alignment display: table-cell .wrapper ( display: table; width: 100%; ) .cell ( display: table-cell; height: 100px; vertical-align: middle; )

    I'm vertically aligned

    Dynamic alignment of an element on a page

    We looked at ways to align elements on a page using CSS. Now let's take a look at the jQuery implementation.

    Let's connect jQuery to the page:

    I suggest writing a simple function to center an element on the page, let's call it alignCenter() . The element itself acts as an argument to the function:

    Function alignCenter(elem) ( // code here )

    In the body of the function, we dynamically calculate and assign the coordinates of the page center to the CSS left and top properties:

    Function alignCenter(elem) ( elem.css(( left: ($(window).width() - elem.width()) / 2 + "px", top: ($(window).height() - elem. height()) / 2 + "px" // don't forget to add position: absolute to the element to trigger coordinates )) )

    In the first line of the function, we get the width of the document and subtract from it the width of the element, divided in half - this will be the horizontal center of the page. The second line does the same thing, only with height for vertical alignment.

    The function is ready, all that remains is to attach it to the DOM readiness and window resize events:

    $(function() ( // call the centering function when the DOM is ready alignCenter($(elem)); // call the function when resizing the window $(window).resize(function() ( alignCenter($(elem)); )) // element centering function function alignCenter(elem) ( elem.css(( // calculating left and top coordinates left: ($(window).width() - elem.width()) / 2 + "px", top: ($(window).height() - elem.height()) / 2 + "px" )) ) ))

    Application of Flexbox

    New CSS3 features, such as Flexbox, are gradually becoming commonplace. The technology helps create markup without using floats, positioning, etc. It can also be used to center elements. For example, apply Flexbox to the parent element.wrapper and center the content inside:

    Wrapper ( display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; height: 500px; width: 500px; ) .wrapper .content ( margin: auto; /* margin: 0 auto; horizontal only */ /* margin: vertical only */ ) Lorem ipsum dolor sit amet

    This rule centers the element horizontally and vertically at the same time - margin now works not only for horizontal alignment, but also for vertical one. And without a known width/height.

    Related resources Help the project

    Aligning text vertically in CSS is quite a tricky job. I've seen enough people struggle with this that I constantly find "critical" errors when it comes to actual responsive design.

    But fear not: if you're already struggling with CSS vertical alignment, you've come to the right place.

    Let's talk about the CSS vertical align property

    When I first started working in web development, I struggled a bit with this property. I thought it should work like the classic “text-align” property. Oh, if only everything were so simple...

    The vertical-align CSS property works fine with tables, but not with divs or other elements. When you use it on a div, it aligns the element relative to other divs, but not its content. In this case, the property only works with display: inline-block; .

    See example

    We want to center the content, not the div itself!

    You have two options. If you only have div elements with text, then you can use the line-height property. This means that you need to know the height of the element, but you cannot set it. This way your text will always be in the center.

    There is a drawback to this CSS vertical alignment approach, however. If the text is multi-line, then the line height will be multiplied by the number of lines. Most likely, in this case, you will end up with a terribly laid out page.

    Take a look at this example

    If the content you want to center consists of more than one line, then it is better to use table divs. You can also use tables, but this is not semantically correct. If you need breaks for responsive purposes, it's better to use div elements.

    For this to work, there must be a parent container with display: table and inside it the desired number of columns that you want centered using display: table-cell and vertical-align: middle .

    See example

    Why does this work with table markup but not with div elements? Because the rows in the table have the same height. When a table cell's content does not use all the available height space, the browser automatically adds vertical padding to center the content.

    position property

    Let's start with the basics of CSS div vertical alignment:

    • position: static is the default. The element is rendered according to HTML order;
    • position: absolute - used to determine the exact position of an element. This position is always related to the nearest relatively positioned parent element (not static ). If you don't determine the exact position of an element, you will lose control of it. It will appear randomly, completely ignoring the flow of the document. By default, the element appears in the upper left corner;
    • position: relative - used to position an element relative to its normal position (static). This value preserves the document flow order;
    • position: fixed - used to position the element relative to the browser window so it is always visible in the viewport.

    Note: Some properties (top and z-index) only work if the element is set to position (not static ).

    Let's get down to business!

    Do you want to implement CSS vertical center alignment? First create an element with relative position and dimensions. For example: 100% in width and height.

    The second step may vary depending on the target browsers, but you can use one of two options:

    • Old property: need to know the exact size of the window to remove half the width and half the height. Look at the example;
    • New CSS3 property: you can add a transform property with a translate value of 50% and the block will always be in the center. View example.

    Basically, if you want to center content, never use top: 40% or left: 300px . This works fine on test screens, but it is not centered.

    Remember position: fixed ? You can do the same thing with it as with an absolute position, but you don't need a relative position for the parent element - it will always be positioned relative to the browser window.

    Have you heard of the flexbox specification?

    You can use flexbox. This is much better than any other CSS vertical center text alignment option. With flexbox, managing elements is like child's play. The problem is that you need to discard some browsers such as IE9 and versions below. Here's an example of how to vertically center a block:

    View example

    Using a flexbox layout, you can center multiple blocks.

    If you apply what you've learned from these examples, you'll be able to master CSS vertical block alignment in no time.

    Links and further reading

    Learning CSS markup

    FlexBox Froggy

    Flexbox sandbox

    The translation of the article “CSS Vertical Align for Everyone (Dummies Included)” was prepared by the friendly project team.

    Aligning elements on a web page can be a challenging task, especially when it comes to vertically aligning text. This question is often found on forums, and solving this issue is especially difficult for novice users. But in reality there is nothing complicated here. All you need is a little knowledge of CSS Cascading Style Sheets. Since this is all done due to its rules.

    Vertical text alignment can be achieved in at least five different ways. Each of them is good in its own way, given the circumstances and details of the situation. We will look at several examples, and based on the conditions, you will choose the appropriate rotation for yourself.

    First method with line-height

    The first method is very banal and has a big drawback, which limits its application. But still, whatever one may say, it can be useful and even bring the desired result. This will be a conditional alignment, since we are essentially setting the line height to match the block height using the line-height property.

    first example. demo #1

    first example. demo #1

    /* No.1 */ .talign1( border: 1px solid red; height:200px;/* block height */ ) .talign1 > p( line-height:200px;/* set the line height according to the block height */ margin :0;/* remove outer padding, if any */ text-align:center;/* align the text horizontally with the center */ padding: 0;/* remove inner padding, if any */ ) /* end No. 1*/

    In exactly the same way, it is possible to implement the image in the vertical center, but by adding one new property vertical-align: middle; .

    Example. Demo #2

    Example. Demo #2

    /* No.2 */ .talign2( border: 1px solid red; line-height:200px;/* block line height */ ) .talign2 div( text-align:center;/* align elements horizontally centered */ ) .talign2 img( vertical-align:middle;/* align the images vertically in the center */ border: 1px solid black; ) /* end №2*/

    Alignment with position property

    This method is widely used in many CSS tasks, including our task. But it should be noted that it is not completely perfect and has its side effects. This is because the element's percent centering will be centered on the top left edge of the inner block.

    Therefore, you need to set a negative value to the margins. The size of the indentation on the top should correspond to half the height of the internal block, and the indentation on the left should correspond to half the width. Thus, we obtain the absolute center.

    In this option, it is probably mandatory to know the exact height and width of the child element. Otherwise, incorrect centering may occur.

    /* No.3 */ .talign3( border: 1px solid red; height:200px;/* block height */ position: relative; ) .talign3 div( position: absolute; top: 50%; left: 50%; height: 30%; width: 50%; margin: -5% 0 0 -25%; border: 1px solid black;

    Alignment with table property

    Here we use an old technique, turning the elements into a table with cells. In this case, the table tags

    will not apply, but will use CSS properties such as display: table; , display: table-cell; . In older versions of IE, this method does not work, and it is not necessary. Does anyone else actually use them?

    Example. demo #4

    Example. demo #4

    /* No.4 */ .talign4( border: 1px solid red; height:200px;/* block height */ display: table; width: 100%; ) .talign4 div( display: table-cell; vertical-align: middle ; text-align:center ) /* end #4*/

    Alignment with flex property

    This is a more specific option with properties that are not so often found in website layout. But, nevertheless, in rare cases they are very useful.

    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 text alignment to the center; 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 elements 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.