Vertical alignment in div. Bonus: conditional comments

Everyone who deals with layout sooner or later is faced with the need to align elements vertically... and they know what difficulties can arise when aligning an element to the center. In CSS there is a property `vertical-align` with many values ​​which, logically, should perform vertical alignment. However, in practice it doesn't work at all as expected.

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

1. Alignment using a table

In this case, we replace the outer block with a single-cell table. The alignment will be applied to the contents of the cell, that is, the inner block.

HTML

CSS

Outer ( width : 200px ; height : 200px ; text-align : center ; vertical-align : middle ; background-color : #ffc ; )

The main disadvantage of this solution, from a semantic point of view, is the use of the table for other purposes than its intended purpose. The second disadvantage is that creating a table requires adding another element around the outer block.

The first disadvantage can be partially avoided by replacing the table tags with divs and setting the table display mode in CSS.

HTML

CSS

Outer-wrapper ( display : table ; ) .outer ( display : table-cell ; )

2. Alignment using indents

Provided that we know the heights of the inner and outer blocks, the alignment can be set using the vertical indents of the inner block using the formula: (H outer – H inner) / 2.

CSS

Outer (height: 200px;).inner (height: 100px; margin: 50px 0;)

The downside of the solution is the mandatory knowledge of the height of both blocks.

3. Alignment using line-height

If the inner block occupies 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 advisable to also add the white-space: nowrap and overflow: hidden rules.

CSS

Outer ( height : 200px ; line-height : 200px ; ) .inner ( white-space : nowrap ; overflow : hidden ; )

This method can also be used to align multiline text. To do this, the inner block needs to override the line-height value, and also add the display: inline-block and vertical-align: middle rules.

CSS

Outer ( height : 200px ; line-height : 200px ; ) .inner ( line-height : normal ; display : inline-block ; vertical-align : middle ; )

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

4. Alignment using “stretching”

This method can be used when the height of the internal block is known to us, but the external one is not.

To apply this method we need:

  • Set the outer block to relative positioning position: relative , and the inner block to absolute position: absolute ;
  • Add several top: 0 and bottom: 0 rules 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 internal block to auto .

CSS

Outer ( position : relative ; ) .inner ( height : 100px ; position : absolute ; top : 0 ; bottom : 0 ; margin : auto 0 ; )

5. Alignment with negative margin-top

Similar to the previous one, this method is used when the height of the external block is unknown, but the height of the internal one is known.

You need to set the external block to relative positioning, and the internal block to absolute positioning. Then 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 .

CSS

Outer ( position : relative ; ) .inner ( height : 100px ; position : absolute ; top : 50% ; margin-top : -50px ; )

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

6. Alignment using transform

The method can be used when the height of the indoor unit is unknown. You need to move the inner block down by half the height of the outer block top: 50% , then use the transform property and move it back up using the translateY(-50%) function.

CSS

Outer ( position : relative ; ) .inner ( position : absolute ; top : 50% ; transform : translateY (-50% ); )

7. Alignment with a pseudo-element

This is the most universal method that can be used when the heights of both blocks are unknown.

The essence of the method is to add an inline-block with a height of 100% inside the outer block and assign it vertical alignment. Thus, the height of the added block will be equal to the height of the outer block. The indoor unit will be aligned vertically relative to the added unit, and therefore the external unit.

In order not to violate semantics, it is advisable to add an inline block using the before or after pseudo-elements.

CSS

Outer :before ( display : inline-block ; height : 100% ; vertical-align : middle ; content : "" ; ) .inner ( display : inline-block ; vertical-align : middle ; )

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

8. Alignment with Flexbox

The most modern method of vertical alignment is the use of Flexible Box Layout (or Flexbox). It 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.

Align text vertically in CSS- a very difficult job. I've seen enough people struggle with this that I keep finding "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 a classic property" text-align" Oh, if only everything were so simple...

vertical-align CSS property works great 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.

The truth about this approach CSS vertical alignment there is a drawback. 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 to center 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 closest 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. See 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 option center text alignment CSS vertically. With flexbox, managing elements is like child's play. The problem is that some browsers need to be discarded, 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 learn from these examples, you can master CSS vertical block alignment as soon as possible.

Links and further reading

Learning CSS markup

FlexBox Froggy

Flexbox sandbox

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 for 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.

A designer sometimes has a question: how to center elements vertically? And this causes certain problems. However, there are several methods for centering elements vertically, and each of these methods is quite simple. This article describes some of these methods.

To see each method in action, click on the demo button or on the image.

Let's discuss some of the issues that prevent vertical centering.

Vertical-Align

Horizontally centering an element is fairly easy to implement (using CSS). An inline element can be centered horizontally by giving its parent container a text-align property of center . When an element is a block element, to center it, you just need to set the width (width) and set the values ​​of the right (margin-right) and left (margin-left) margins to auto .

Regarding text: many people are starting to use the vertical-align property for centering. It's logical and my first choice would be the same. To center an element in a table, you can use the valign attribute.

However, the valign attribute only works when applied to a cell (for example, ). The CSS vertical-align property can be applied to a cell and some inline elements.

  • The text is centered relative to line-height (line spacing).
  • In relation to the table, without going into details, centering occurs relative to the height of the row.

Unfortunately, the vertical-align property cannot be applied to block-level elements, such as a paragraph (p) inside a div tag.

However, there are other methods for vertically centering elements, and you can still use the vertical-align property where needed. Which method to use depends on what you are going to center.

Line spacing or Line-height

This method should only be used when you need to center a line of text. To do this, you need to set the line-height (line spacing) of the element that contains text to greater than the font size.

By default, there is equal space above and below the text, so the text is centered vertically.

In this case, it is not necessary to specify the height of the parent element.

Here's the text

#child ( line-height: 200px; )

This method works in all browsers, but do not forget that it should be used for a line of text. If your text spans more than one line, use a different method. The value of the line-height property can be anything, but not less than the font height. In practice, this method works great for centering a horizontal menu.

CSS Method Using Table Properties

As I already wrote, the contents of a cell can be centered using the CSS vertical-align property. The parent element must be represented as a table, the child element must be designated as a cell and the vertical-align property must be applied to it with the value middle . This way, any content in the child element will be centered vertically. The CSS code is given below.

Content

#parent ( display: table;) #child ( display: table-cell; vertical-align: middle; )

Unfortunately, this method does not work in older versions of the IE browser. If you require browser support for IE6 and below, add a display: inline-block declaration to the child element.

#child ( display: inline-block; )

Absolute positioning and negative margin

This method is designed for block-level elements and works in all browsers. You need to set the height of the element that needs to be centered.

Below is the code where the child element is centered using this method.

Content

#parent (position: relative;) #child ( position: absolute; top: 50%; left: 50%; height: 30%; width: 50%; margin: -15% 0 0 -25%; )

First you need to position the parent and child element. We then set the child element's offset to 50% relative to the top and left side of the parent element, thereby centering the child element relative to the parent element. However, our manipulations will center the top-right corner of the child element in the center of the parent element, which, of course, does not suit us.

Our task: to move the child element up and to the left, relative to the parent element, so that the child element is visually centered vertically and horizontally. This is why you need to know the height and width of the child element.

So, we should give the child element a negative top and left margin equal to half, respectively, the width and height of the child element.

Unlike the first two methods, this method is intended for block-level elements. The method works in all browsers, but the content may exceed the height of the parent element and extend beyond its boundaries. This method works best when the height and width of the elements are fixed.

Absolute positioning of a child element

As in the previous method, the parent and child elements are positioned relative and absolute, respectively.

In the CSS code I center the child element both vertically and horizontally, however you can only use vertical centering.

Content

#parent (position: relative;) #child ( position: absolute; top: 0; bottom: 0; left: 0; right: 0; width: 50%; height: 30%; margin: auto; )

The idea of ​​this method is that we can position a child element using top , left , right , bottom property values ​​equal to 0. Since our child element is smaller than the parent element, it will not be able to “stick” to the parent element.

The margin values ​​for all four sides of the child element are zero, which centers the element vertically relative to the parent. Unfortunately, this method has the same disadvantages as the previous method: it is necessary to fix the height and width of the child, lack of support for older IE browsers.

Bottom and top margins are equal

In this method, we explicitly assign equal padding (bottom and top) to the parent element, which visually centers the child element vertically.

Content

#parent ( padding: 5% 0; ) #child ( padding: 10% 0; )

I use relative sizes. If the block sizes are fixed, then you will need to do some mathematical calculations.

For example, if the parent element has a height of 400px and the child is 100px, then you should set the top and bottom padding to 150px.

150 + 150 + 100 = 400

floating div

This method involves an empty float block that controls the vertical position of the child element. The floating div needs to be placed before the child element, see the HTML code below.

Content

#parent (height: 250px;) #floater ( float: left; height: 50%; width: 100%; margin-bottom: -50px; ) #child ( clear: both; height: 100px; )

First we move the floating block to the left (or right) and give it a height of 50% of its parent. This way the floating block will fill the top half of the parent element.

Since the block is floating, it is removed from the general flow of the document, therefore, the child block should be assigned the clear property with the value both . I set the value to both , but you can use a value that matches the positioning direction of the floating element.

Currently, the top edge of the child element lies directly below the bottom edge of the floating element. We need to raise the child element to half the height of the floating element. To do this, just set the negative bottom margin for the floating block to 50%.

Works in all browsers. The disadvantage of this method is that it requires an empty block and requires knowing the height of the child element.

Every layout designer is constantly faced with the need to align content in a block: horizontally or vertically. There are several good articles on this subject, but they all offer a lot of interesting, but few practical options, which is why you have to spend extra time to highlight the main points. I decided to present this information in a form that is convenient for me, so as not to google anymore.

Aligning blocks with known sizes

The easiest way to use CSS is to align blocks that have a known height (for vertical alignment) or width (for horizontal alignment).

Alignment using padding

Sometimes you can not center an element, but add borders to it using the " padding".

For example, there is a picture of 200 by 200 pixels, and you need to center it in a block of 240 by 300. We can set the height and width of the outer block = 200px, and add 20 pixels at the top and bottom, and 50 at the left and right.

.example-wrapper1 ( background : #535E73 ; width : 200px ; height : 200px ; padding : 20px 50px ; )

Aligning Absolutely Positioned Blocks

If the block is set to " position: absolute", then it can be positioned relative to its closest parent with "position: relative". This requires all properties (" top","right","bottom","left") of the inner block to assign the same value, as well as "margin: auto".

*There is a nuance: The width (height) of the inner block + the value of left (right, bottom, top) should not exceed the dimensions of the parent block. It is safer to assign 0 (zero) to the left (right, bottom, top) properties.

.example-wrapper2 ( position : relative ; height : 250px ; background : url(space.jpg) ; ) .cat-king ( width : 200px ; height : 200px ; position : absolute ; top : 0 ; left : 0 ; bottom : 0 ; right : 0 ; margin : auto ; background : url(king.png) ;

Horizontal alignment

Alignment using "text-align: center"

To align text in a block there is a special property " text-align". When set to " center"Each line of text will be aligned horizontally. For multi-line text, this solution is used extremely rarely; more often this option can be found for aligning spans, links or images.

I once had to come up with some text to show how text alignment works using CSS, but nothing interesting came to mind. At first I decided to copy a children's rhyme somewhere, but I remembered that this might spoil the uniqueness of the article, and our dear readers would not be able to find it on Google. And then I decided to write this paragraph - after all, the point is not with it, but the point is in alignment.

.example-text ( text-align : center ; padding : 10px ; background : #FF90B8 ; )

It's worth noting that this property will work not only for text, but also for any inline elements ("display: inline").

But this text is aligned to the left, but it is in a block that is centered relative to the wrapper.

.example-wrapper3 ( text-align : center ; background : #FF90B8 ; ) .inline-text ( display : inline-block ; width : 40% ; padding : 10px ; text-align : left ; background : #FFE5E5 ; )

Aligning blocks using margin

Block elements with a known width can easily be aligned horizontally by setting them to "margin-left: auto; margin-right: auto". Usually the abbreviation is used: " margin: 0 auto" (any value can be used instead of zero). But this method is not suitable for vertical alignment.

.lama-wrapper ( height : 200px ; background : #F1BF88 ; ) .lama1 ( height : 200px ; width : 200px ; background : url(lama.jpg) ; margin : 0 auto ; )

This is how you should align all blocks, where possible (where fixed or absolute positioning is not required) - it is the most logical and adequate. Although this seems obvious, I have sometimes seen scary examples with negative indents, so I decided to clarify.

Vertical alignment

Vertical alignment is much more problematic - apparently, this was not provided for in the CSS. There are several ways to achieve the desired result, but all of them are not very beautiful.

Alignment with line-height property

In the case when there is only one line in a block, you can achieve its vertical alignment by using the " line-height" and setting it to the desired height. For reliability, it is worth setting also "height", the value of which will be equal to the value of "line-height", because the latter is not supported in all browsers.

.example-wrapper4 ( line-height : 100px ; color : #DC09C0 ; background : #E5DAE1 ; height : 100px ; text-align : center ; )

It is also possible to achieve block alignment with several lines. To do this, you will have to use an additional wrapper block and set the line height to it. An internal block can be multi-line, but must be "inline". You need to apply "vertical-align: middle" to it.

.example-wrapper5 ( line-height : 160px ; height : 160px ; font-size : 0 ; background : #FF9B00 ; ) .example-wrapper5 .text1 ( display : inline-block ; font-size : 14px ; line-height : 1.5 ; vertical-align : middle ; background : #FFFAF2 ; color : #FF9B00 ;

The wrapper block must have "font-size: 0" set. If you don't set the font size to zero, the browser will add a few extra pixels. You will also have to specify the font size and line height for the inner block, because these properties are inherited from the parent.

Vertical alignment in tables

Property " vertical-align" also affects table cells. With the value set to "middle", the content inside the cell is aligned to the center. Of course, table layout is considered archaic nowadays, but in exceptional cases you can simulate it by specifying " display: table-cell".

I usually use this option for vertical alignment. Below is an example of layout taken from a completed project. It is the picture that is centered vertically in this way that is of interest.

.one_product .img_wrapper ( display : table-cell ; height : 169px ; vertical-align : middle ; overflow : hidden ; background : #fff ; width : 255px ; ) .one_product img ( max-height : 169px ; max-width : 100 % ; min-width : 140px ; display : block ; margin : 0 auto ;

It should be remembered that if an element has a “float” set other than “none”, then it will in any case be block (display: block) - then you will have to use an additional block wrapper.

Alignment with an additional inline element

And for inline elements you can use " vertical-align: middle". Moreover, all elements with " display: inline" that are on the same line will align with a common center line.

You need to create an auxiliary block with a height equal to the height of the parent block, then the desired block will be centered. To do this, it is convenient to use the pseudo-elements:before or:after.

.example-wrapper6 ( height : 300px ; text-align : center ; background : #70DAF1 ; ) .pudge ( display : inline-block ; vertical-align : middle ; background : url(pudge.png) ; background-color : # fff ; width : 200px ; height : 200px ; .riki ( display : inline-block ; height : 100% ; vertical-align : middle ; )

Display: flex and alignment

If you don't care much about Explorer 8 users, or care so much that you're willing to insert a piece of extra javascript for them, then you can use "display: flex". Flex boxes are great at dealing with alignment issues, and just write "margin: auto" to center the content inside.

So far, I have practically never encountered this method, but there are no special restrictions for it.

.example-wrapper7 ( display : flex ; height : 300px ; background : #AEB96A ; ) .example-wrapper7 img ( margin : auto ; )

Well, that's all I wanted to write about CSS alignment. Now centering content will not be a problem!