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 lineWhen 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-alignA 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;
}
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-alignThe 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 transformThe 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-elementThe 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.
FlexboxThe 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 methodWhich 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 unknownIn 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 knownThe 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 heightThe 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: autoHorizontal 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: centerThis 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 leftSuitable 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: centerThe 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-heightTo 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 upAn 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-cellFor 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 pageWe 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 FlexboxNew 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 projectAligning 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 propertyWhen 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 propertyLet'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 readingLearning 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-heightThe 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 propertyThis 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 propertyHere we use an old technique, turning the elements into a table with cells. In this case, the table tags