All vertical alignment methods in CSS. Centering a div horizontally and vertically

Aligning elements on a web page may not be such an easy task, especially when it comes to aligning text vertically. This question is often found on the forums, and novice users are especially difficult to solve this issue. But in fact, there is nothing complicated here. All it takes is a little knowledge of CSS Cascading Style Sheets. Since this is all done at the expense of its rules.

Vertical alignment of text 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 a few examples, and based on the conditions, you will choose a suitable growth 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 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

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

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

Example. Demo #2

Example. Demo #2

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

Alignment with the 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 own side effects. This is because the element's centering, given as a percentage, will be centered on the top-left edge of the inner box.

Therefore, you need to set a negative value for the margins. The padding on the top should be half the height of the inner block, and the padding on the left should be half the width. Thus, we get the absolute center.

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

/* #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; ) /* end #3*/

Alignment with the table property

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

will not apply, but 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

/* #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 the flex property

This is a more specific version with properties that are not so common in site layout. But, nevertheless, they are in rare cases very useful.

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

Horizontal alignment

margin: auto

Horizontal alignment with 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 the auto value of the right and left padding 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

I am center aligned



position and negative margin to the left

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

Alignment with position

I am center aligned



display: inline-block + text-align: center

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

Alignment with display: inline-block + text-align: center;



Vertical alignment

line-height

To align a single 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

I am vertically aligned



position and negative margin up

An element can be vertically aligned 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 should be given position: relative:

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

Thus, using positioning and negative margins, you can center the element on the page.

display: table-cell

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

vertical align display: table-cell

I am vertically aligned



Dynamically align 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 add 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, dynamically calculate and assign the coordinates of the page center to the left and top CSS 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, only with a height to align vertically.

The function is ready, it remains to hang it on the DOM readiness and window resize events:

$(function() ( // call the centering function when the DOM is ready alignCenter($(elem)); // call the function when the window is resized $(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 slowly coming into the mainstream. The technology helps to create markup without the use of floats, positioning, etc. It can also be used to center elements. For example, let's apply Flexbox to the parent .wrapper element 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: auto 0; 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 alignment. And without known width/height.

Related Resources

Help the project

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

You probably already know about the existence of the wonderful CSS property vertical-align. And God himself ordered us to use this property for vertical alignment (it is not for nothing that it bears such a self-explanatory name).

Formulation of the problem: It is necessary to align the contents of the variable height block in the center 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 align to the center height of the container div.

But it was not there! We will not achieve any expected center alignment in this way. And why? Everything seemed to be correct. It turns out here's the catch: property vertical-align can only be used to align the contents of table cells or to align inline elements relative to each other.

Regarding the alignment inside the table cell, I think everything is clear. But I will explain another case with inline elements.

Vertical alignment of inline elements

Suppose you have a line of text that is broken with inline tags into parts:

You welcomes a piece text!

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

The action of the block tag leads to the transfer of the contents of the container to a new line.

is a block tag. If we enclose chunks of text in blocks
, then each of them will be on a new line. Using the tag , which, unlike
, is inline, there will be no wrapping of containers to a new line, all containers stay on the same line.

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

For containers apply the following CSS properties:

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

As a result, the line of text will look like this:

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

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

Vertical alignment in a div container

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

How can we use it? We do not have a table, we are working with a div container.

Ha, it turns out to be very simple.

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

Let's have a class div textalign:

Block content

For this block, specify the following CSS property:

Textalign(display: table-cell; )

This CSS instruction will miraculously turn our div block 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 centering will work.

However, everything cannot end so simply. We also have a wonderful IE browser. It does not know how to work with the property display: table-cell(I suggest you familiarize yourself with the table illustrating the performance of this CSS property in different browsers on the site htmlbook.ru). Therefore, we will have to go to various tricks.

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

  • Method using an additional helper div container
  • Method using expression . It is connected with the cunning calculation of block heights. You can't do 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. Also, it's implementable for a variable height div container. We will dwell on it in more detail.

As you understand, we need 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 not familiar with this property). Therefore, using conditional comment specifically for browsers of the IE family, we will specify other CSS properties.

Conditional comment

View design:

... Инструкции, действующие только в случае выполнения условия в квадратных скобках...

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

The instructions contained in such a conditional comment will only be executed if the browser interpreting the given 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 how our block with text will look like:

It's some kind of test text.
It consists of two lines.

For class container div 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 in the center relative to the vertical, in all browsers except IE.

Now we start adding properties related to alignment for IE family browsers(it is for them that we used additional blocks div and span):

Referring to the tag div inside the class block textalign. To do this, you must first specify the name of the class, and then, separated by a space, the tag we are referring to.

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

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

Accordingly, the styles set 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 box is shifted 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 dot of the yellow block has indeed moved 50% down from its parent (purple) block. But what we need is that at fifty percent of the height of the purple block is yellow block center, not its top left point.

Now the tag will go 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 the initial position. As you understand, the height of the yellow block is equal to the height of the centered content. And the last span operation puts our content in the middle of the purple box. Hooray!

Let's Shaman a Little

First things first, we need to hide the parsley from all normal browsers and open it for IE. This can be done, of course, with the help of a conditional comment, it was not in vain that we got to know him:

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

Solution: property needs to be added overflow: hidden bloc textalign.

Get to know the property in detail overflow possible in .

The final look of the CSS instructions for the block textalign looks like:

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

Sorry, I forgot to mention one important point. If you keep trying set the height of the class block textalign as a percentage, then you have nothing will come of it.

Centering in a Variable Height Block

Very often there is a need to set the height of the 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 (and the class block textalign turns into a table cell, thanks to the property display:table-cell).

In this case, you must use the outer block, for which the CSS property is specified display:table and already for it to set the percentage value of the height. 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'll edit the CSS a bit:

class textalign we will change the value of the property display with table cell on the 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; )

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

Getting another additional list of CSS properties for the div nested in the container textalign.

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

That's the whole trick. Optionally, you can variable height with centered content.

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

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 by them.

Below are the vertical alignment techniques popular with layout designers. It shows how they work, and for which cases each of them is most suitable.

Here are two div elements:



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

line-height for one line

When the parent spans 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 box. This only works for one line, so it's good for the child to add overflow: hidden and white-space: nowrap to prevent line wrapping.

You won't be able to use line-height=100% as a percentage, because 100% in this case is the height of the font.

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

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

The method is applicable only when the height of the outer block is known.

Table with vertical-align

A table is the best way to align elements vertically. In order not to violate the semantics, it is better to create table elements using CSS. The position of the cell content is controlled by vertical-align. Four values ​​of this property work in tables:

baseline - by 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 lone table cell becomes the outer block.

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

The method is good because it works for elements without a specified height, but in some cases its use is hindered by the fact that the outer block, like any table cell, adapts its width to its content, and you can only stretch it by setting the width for width explicitly. For a cell without a table, percentages do not work adequately.

This shortcoming is corrected by wrapping the cell in the parent with the display:table property. This element can be sized 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 inner element is known. For an external block, it may be unknown. The parent is given relative positioning, and the child inside it is absolute.

A top property value of 50% causes the nested element to be positioned top-most in the middle of the outer box. It remains to raise it with a negative margin-top by half of 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.

Inline alignment with vertical-align

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

Given the height of the parent, 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 overridden to normal or whatever value you want. He is also given the alignment vertical-align: middle and conversion to 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 box with an unknown height. To do this, the parent must be positioned relatively and the child must be positioned absolutely.

The top property with a value of 50% lowers the inner box so that its top edge is in the middle of the parent. The translateY value: -50% raises the element by half of its own height and thus aligns the vertical centers of the boxes.

Container(
position: relative;
}

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

The disadvantage of the reception is the limited support for transform functions by the IE browser.

Alignment via pseudo-element

The method works when the height is unknown for either the first or the second block. An inline pseudo-element inline-block 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 with vertical-align: middle.

Vertical-align: middle aligns the inner block relative to this pseudo-element. Since the parent and child are the same height, the inner element, while vertically aligned with the pseudo-element, is centered with the outer box as well.

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

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

Universal way. Does not work if the inner block is set to absolute positioning.

Flexbox

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

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

Inner(
width: 120px
margin: auto;
}

Flexbox only works in modern browsers.

Choice of 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 is 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 inner 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 outer block is positioned relatively; the inner element is given absolute positioning, top: 50% and a margin-top equal to half of its height.

One line per block with known height

The outer box is set to the 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 whatever value you want, and it is given display: inline-block and vertical-align: middle.

When designing a web page layout, you've probably come across a situation where you need to center a div horizontally and vertically using CSS. There are several ways using CSS and jQuery.

But first the basics:

Horizontal alignment with CSS

class-name(
margin:0 auto;
width:200px;
height:200px;
}

To center a div only horizontally, you need to specify a width and an automatic value for the left and right margins (this is a shorthand form of writing CSS properties). This method works on block elements (div, p, h1, etc.). To apply it to inline elements (such as hyperlinks and images), you need to write another rule - display:block .

Horizontal and vertical alignment with CSS

Centering the div horizontally and vertically at the same time is a little more tricky. You need to know the dimensions of the div in advance.

class-name(
width:300px;
height:200px;
position:absolute;
left:50%;
top:50%;
margin:-100px 0 0 -150px;
}

With the absolute positioning of an element, we can pull it out of the flow and set its position relative to the browser window. By setting the div offset to 50% from the left and top of the window, we center the top left corner of the page. The only thing left to do is move the div left and up by half of its width and height, with a negative margin so that it's perfectly centered.

Horizontal and vertical alignment with jQuery

As stated, the above CSS method only works on fixed size divs. jQuery comes to the rescue:

// function declaration:
$(window).resize(function()(
$(".class-name").css((
position:"absolute",
left: ($(window).width() - $(".class-name").outerWidth())/2,
top: ($(window).height() - $(".class-name").outerHeight())/2
});
});
// function call:
$(window).resize();

The function calculates the window width in $(window).resize() whenever the user resizes the window. We use outerWidth() and outerHeight() because, unlike regular width() and height() , they add padding and border width, returning the size. Finally, we adapt on window resize and center the div on page reload.