CSS centering of DIV blocks: horizontal and vertical. Methods for vertical center alignment in CSS

Today's article aims to show you how to center a div, both horizontally and vertically, using a few CSS tricks. We will also tell you how to center across the entire page or in an individual div element.

Easily center a DIV element on the page

This method will work perfectly in all browsers.

CSS

Center-div ( margin: 0 auto; width: 100px; )

Example

The value auto in the margin property sets the left and right margin to the entire space available on the page. The important thing to remember here is that the centered div element must have a width value set.

Centering a DIV inside a DIV element the old fashioned way

This center alignment div method will work in all browsers.

CSS

Outer-div ( padding: 30px; ) .inner-div ( margin: 0 auto; width: 100px; )

HTML

Example

The outer div can be placed in any way you like, but the inner div must have a specified width (width).

Centering a DIV inside a DIV element using inline-block

In this method of centering a div within a div, it is not necessary to specify the width of the inner element. It will work in all modern browsers, including IE8.

CSS

Outer-div ( padding: 30px; text-align: center; ) .inner-div ( display: inline-block; padding: 50px; )

HTML

Example

The text-align property only works on inline elements. The inline-block value allows the inner div to be displayed as an inline element and also as a block (inline-block). The text-align property on the outer div element will allow us to center the inner div.

Center a DIV inside a DIV element horizontally and vertically

Here margin: auto is used to center the div in the center of the page. The example will work in all modern browsers.

CSS

Outer-div ( padding: 30px; ) .inner-div ( margin: auto; width: 100px; height: 100px; )

HTML

Example

The inner div element must have a specified width (width) and height (height). The method will not work if the outer div element has a fixed height.

Center the DIV at the bottom of the page

Here margin: auto is used to center the div vertically and absolute positioning is used for the outer element. The method will work in all modern browsers.

CSS

Outer-div ( position: absolute; bottom: 30px; width: 100%; ) .inner-div ( margin: 0 auto; width: 100px; height: 100px; background-color: #ccc; )

HTML

Example

The inner div must have a width set. The space at the bottom of the page is adjusted using the bottom property of the outer div. You can also center a div at the top of the page by replacing the bottom property with the top property.

Center DIVs on the page vertically and horizontally

Here, to center the div, we again use margin: auto and absolute positioning of the outer div. The method will work in all modern browsers.

CSS

Center-div ( position: absolute; margin: auto; top: 0; right: 0; bottom: 0; left: 0; width: 100px; height: 100px; )

Example

The div element must have a width (width) and height (height).

Making adaptive centering of a DIV element on the page

Here, to center the div using CSS, we make the width of the div element responsive so that it responds to changes in window size. This method works in all browsers.

CSS

Center-div ( margin: 0 auto; max-width: 700px; )

Example

A centered div element must have its max-width property set.

Centering a DIV inside an element using the inner block properties

The inner div element here is responsive. This method of centering a div inside a div will work in all browsers.

CSS

Outer-div ( padding: 30px; ) .inner-div ( margin: 0 auto; max-width: 700px; )

HTML

Example

The inner div must have its max-width property set.

Centering two responsive divs next to each other

Here we have two responsive div elements side by side. This method of placing a div in the center of the screen will work in all modern browsers.

CSS

Container ( text-align: center; ) .left-div ( display: inline-block; max-width: 300px; vertical-align: top; ) .right-div ( display: inline-block; max-width: 150px; ) screen and (max-width: 600px) ( .left-div, .right-div ( lef max-width: 100%; ) )

HTML

Example

Here we have several elements with the inline-block property applied, located inside a centered container. This example also uses CSS media queries; that is, if the screen size is less than 600 pixels, then the max-width property for both the left and right div is set to 100%.

DIV element centered using Flexbox

Here we center the CSS div using Flexbox. It is intended to facilitate the process of developing user interface designs. This module is supported by Chrome 38+, IE11, Microsoft Edge, Firefox 38+, Safari 9+, Opera 30+, iOS Safari 9+, as well as Android Browser 40+.

CSS

Container ( display: flex; align-items: center; justify-content: center; height: 100vh; ) .item ( background-color: #f3f2ef; border-radius: 3px; width: 200px; height: 100px; )

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 the 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

Often during layout there is a need for vertical alignment of text in a block. If this needs to be done in a table cell, then the value of the vertical-align CSS property is set.

But a reasonable question arises: is it possible to do without a table, without overloading the page layout with unnecessary tags? The answer is “you can,” but due to poor CSS support in the MSIE browser, the solution to the problem for it will be different from the solution for other common browsers.

As an example, consider the following fragment:


div(
border: 1px solid #000;
height: 10em;
width: 10em;
}


Some text

and try to vertically align the text to the center of the block and to the bottom edge of the block.

Solving the problem of “Correct” browsers (including MSIE

Most modern browsers support CSS2.1, namely the table-cell value for the display property. This gives us the opportunity to force a block of text to appear as a table cell and, taking advantage of this, align the text vertically:

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

div(
display: table-cell;
vertical-align: bottom;
}

Internet Explorer (up to version 7 inclusive)

You can solve the problem of aligning text to the bottom edge of a block in MSIE using absolute positioning (here we will need a string element nested in the block):

div(
position: relative;
}
div span(
display: block;
position: absolute;
bottom: 0%;
left: 0%;
width: 100%;
}

This set of rules also works in “correct” browsers.

Specify properties

Div span (
display: block;
width: 100%;
}

not necessary, but they may be needed if, in addition to vertical text alignment, you also plan to use horizontal alignment, for example, text-align: center ;.

To vertically align the text to the center of the block, the original fragment will still have to be complicated - we will introduce another line element:

Material to study:

  • Vertical Centering in CSS (www.jakpsatweb.cz/css/css-vertical-center-solution.html)
  • Vertical centering using CSS (www.student.oulu.fi/%7Elaurirai/www/css/middle/)
  • Vertical align (www.cssplay.co.uk/ie/valign.html)
  • vertical-align:middle (cssing.org.ua/2005/07/14/vertical-align-middle/)
  • Another method of vertical alignment in CSS (cssing.org.ua/2007/04/26/another-css-valign-method)
  • 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. Alignment with:

    • 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 are 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 point is that the vertical-align property affects the alignment of the element itself, not its content (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 indents If the heights of the inner and outer blocks are known, then 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.

    Aligning with 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 “stretching” This method can be used when the height of the outer block is unknown, but the height of the inner block is known.

    To do this you need:

  • set relative positioning to the external block, and absolute positioning to the internal block;
  • 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;
  • 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 using 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 using transform This method is similar to the previous one, but it can be used when the height of the inner block 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.

    Today, dear reader, we will deal with the problem of vertical alignment in a block div.

    Most likely, you already know about the existence of the wonderful CSS property vertical-align. And God himself ordered us to use precisely this property for vertical alignment (it’s not for nothing that it has such a self-explanatory name).

    Problem statement: It is necessary to align the contents of a variable-height block centered relative to the vertical.

    Now let's start solving the problem.

    And so, we have a block, its height can change:

    Block content

    The first thing that comes to mind is to do the following feint:

    Block content

    There is every reason to believe that the phrase Block content will be aligned to the center height of the div container.

    But it was not there! We will not achieve any expected center alignment this way. And why? It would seem that everything is indicated correctly. It turns out that this is the rub: the property vertical-align can only be used to align the contents of table cells or to align inline elements relative to each other.

    Regarding alignment inside a table cell, I think everything is clear. But I’ll explain another case with inline elements.

    Vertical alignment of inline elements

    Suppose you have a line of text that is broken up by line tags into parts:

    A piece of text welcomes you!

    An inline tag is a container whose appearance does not cause the content to wrap to a new line.

    The action of a block tag causes the contents of the container to wrap to a new line.

    is a block tag. If we enclose pieces of text in blocks , then each of them will be on a new line. Using tag , which, unlike , is lowercase, containers will not be moved to a new line, all containers will remain on one line.

    Container convenient to use when specifying a part of the text with special formatting (highlighting it with a color, a different font, etc.)

    For containers Apply the following CSS properties:

    #perviy( vertical-align:sub; ) #vtoroy( vertical-align:3px; ) #tretiy( vertical-align:-3px; )

    The resulting line of text will look like this:

    This is nothing more than vertical alignment of inline elements, and the CSS vertical-align property copes with this task perfectly.

    We got a little distracted, now we return to our main task.

    Vertical alignment in div container

    No matter what, we will use the vertical-align property for alignment within the div container. As I already said, this property can be used in the case of aligning inline elements (we discussed this case in detail above and it is not suitable for us for alignment in a div container); all that remains is to use the fact that vertical-align works for table cells.

    How can we use this? We don’t have a table, we work with a div container.

    Ha, it turns out to be very simple.

    The CSS display property allows us to turn our div block into a table cell, this can be done easily and naturally:

    Let's say we have a class div textalign:

    Block content

    For this block we specify the following CSS property:

    Textalign( display: table-cell; )

    This CSS instruction will miraculously turn our div into a table cell without visually changing it in any way. And for a table cell we can apply the property vertical-align fully and the desired vertical alignment will work.

    However, everything cannot end so simply. We have a wonderful IE browser. He doesn't know how to work with the property display: table-cell(I suggest you read the table illustrating the functionality of this CSS property in different browsers on the website htmlbook.ru). Therefore, we will have to resort to various tricks.

    There are many ways to achieve alignment in a div container for all browsers:

    • Method using an additional auxiliary div container
    • Method using expression. It is connected with a tricky calculation of block heights. You can't do this without knowledge of JavaScript.
    • Using the line-height property. This method is only suitable for vertical alignment in a block of known height, and therefore is not applicable in the general case.
    • Using absolute and relative content offset in case of IE browser. This method seems to me the most understandable and simple. Additionally, it is implementable for a variable height div container. We will dwell on it in more detail.

    As you understand, we just have to solve the problem of vertical alignment in IE, associated with its misunderstanding of the property display: table-cell(neither IE6, nor IE7, nor IE8 are familiar with this property). Therefore, using a conditional comment specifically for browsers of the IE family, we will indicate other CSS properties.

    Conditional comment

    Construction type:

    ... Instructions that only apply if the condition in square brackets is true...

    is called a conditional comment (be careful, the type of conditional comment must completely correspond to the example given, up to a space).

    The instructions contained in such a conditional comment will be executed only if the browser interpreting this code belongs to the IE family.

    Thus, using a conditional comment, we can hide a piece of code from all browsers except IE.

    The solution of the problem

    Because of all this parsley, we will need to provide our HTML code with two additional containers. This is what our text block will look like:

    This is some kind of verification text.
    It consists of two lines.

    For div container class textalign CSS properties are set that align its content vertically for all normal browsers (except IE, of course):

    Display: table-cell; vertical-align: middle;

    And two more properties that set the width and height for the block:

    Width:500px; height: 500px;

    This is quite enough to align the contents of the container vertically, in all browsers except IE.

    Now we begin to add properties related to alignment for browsers of the IE family (it is for them that we used additional blocks div And span):

    Referring to the tag div inside a class block textalign. To do this, you need to first indicate the name of the class, and then, separated by a space, the tag to which we are accessing.

    Textalign div( position: absolute; top: 50%; )

    This design means: for all div tags inside a block with a class textalign apply the listed properties.

    Accordingly, the styles specified for the block textalign are modified:

    Textalign( display: table-cell; vertical-align: middle; width:500px; height: 500px; position: relative; )

    Now the top left point of the text block is moved down by 50%.

    To explain what is happening, I drew an illustration:

    As you can see from the picture, we have made some progress. But that is not all! The top left point of the yellow block has actually moved 50% down, relative to the parent (purple) block. But we want fifty percent of the height of the purple block to be the center of the yellow block, and not its top left point.

    Now the tag will come into play span and its relative positioning:

    Textalign span( position: relative; top: -50%; )

    Thus, we have shifted the yellow block up by 50% of its height, relative to its initial position. As you understand, the height of the yellow block is equal to the height of the centered content. And the last operation on the span container placed our content in the middle of the purple block. Hooray!

    Let's play tricks a little

    First of all, we need to hide parsley from all normal browsers and open it for IE. This can be done, of course, using a conditional comment; it’s not for nothing that we got acquainted with it:

    .textalign div( position: absolute; top: 50%; ) .textalign span( position: relative; top: -50%; )

    There is a small problem. If the centered content is too high, then this leads to unpleasant consequences: there is an extra height for the vertical scroll.

    Solution to the problem: you need to add a property overflow: hidden block textalign.

    Get to know the property in detail overflow possible in .

    The final CSS instructions for the block textalign has the form:

    Textalign( display: table-cell; vertical-align: middle; width:500px; height: 500px; position: relative; overflow: hidden; border: 1px solid black; )

    I'm sorry, I forgot to mention one important point. If you try to set the height of a class block textalign in percentage terms, then nothing will work out for you.

    Centering in variable height block

    Very often there is a need to set the height of a class block textalign not in pixels, but as a percentage of the height of the parent block, and align the contents of the div container in the middle.

    The catch is that it is impossible to do this for a table cell (but the class block textalign turns exactly into a table cell, thanks to the property display:table-cell).

    In this case, you must use an external block for which the CSS property is specified display:table and already set the percentage value of the height for it. Then the block nested in it, with the CSS directive display:table-cell, will happily inherit the height of the parent block.

    In order to implement a variable height block in our example, we will edit the CSS a little:

    To the class textalign we will change the property value display With table-cell on table and remove the alignment directive vertical-align: middle. Now we can safely change the height value from 500 pixels to, for example, 100%.

    So the CSS properties for the class block textalign will look like this:

    Textalign( display: table; width:500px; height: 100%; position: relative; overflow: hidden; border: 1px solid black; )

    All that remains is to implement content centering. To do this, a div container nested in a class block textalign(this is the same yellow block in the picture), you need to set the CSS property display:table-cell, then it will inherit the height of 100% from the parent block textalign(purple block). And nothing will stop us from aligning the contents of the nested div container in the center with the property vertical-align: middle.

    We get another additional list of CSS properties for the div block nested in the container textalign.

    Textalign div( display: table-cell; vertical-align: middle; )

    That's the whole trick. If desired, you can have a variable height with the content centered.

    For more information on vertical alignment of a variable height block, see .