Vertical alignment in divs. CSS: Vertical text alignment. Alignment in line with vertical-align

Very often the task is to align a block in the center of the page / screen, and even so that without a Java script, without a task rigid sizes or negative indents, so that scrollbars also work for the parent if the block exceeds its size. There are quite a lot of monotonous examples on the Internet on how to align a block to the center of the screen. As a rule, most of them are based on the same principles.

Below are the main ways to solve the problem, their pros and cons. To understand the essence of the examples, I recommend reducing the height/width of the Result window in the examples at the links provided.

Option 1: Negative indentation.

Positioning block using the top and left attributes by 50%, and knowing the height and width of the block in advance, set a negative margin, which is equal to half the size block. A huge minus this option is that you need to count negative padding. Also block does not behave quite correctly when surrounded by scrollbars - it is simply cut off because it has negative margins.

Parent ( width: 100%; height: 100%; position: absolute; top: 0; left: 0; overflow: auto; ) .block ( width: 250px; height: 250px; position: absolute; top: 50%; left : 50%; margin: -125px 0 0 -125px; img (max-width: 100%; height: auto; display: block; margin: 0 auto; border: none; ) )

Option 2. Automatic indentation.

Less common, but similar to the first. For block set the width and height, position with the top attributes right bottom left to 0, and set margin auto. The advantage of this option is working scrollbars parent, if the latter has 100% width and height. The disadvantage of this method is the rigid setting of dimensions.

Parent ( width: 100%; height: 100%; position: absolute; top: 0; left: 0; overflow: auto; ) .block ( width: 250px; height: 250px; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; img (max-width: 100%; height: auto; display: block; margin: 0 auto; border: none; )

Option 3. Table.

Let's ask parent table styles, cell parent Set the text alignment to center. A block we set the line block model. The disadvantages we get are non-working scrollbars, and in general, the aesthetics of the “emulation” of the table are not.

Parent ( width: 100%; height: 100%; display: table; position: absolute; top: 0; left: 0; > .inner ( display: table-cell; text-align: center; vertical-align: middle; ) ) .block ( display: inline-block; img ( display: block; border: none; ) )

To add a scroll to this example, you will have to add one more element to the design.
Example: jsfiddle.net/serdidg/fk5nqh52/3.

Option 4. Pseudo-element.

This option is devoid of all the problems listed in the previous methods, and also solves the original problems. The point is that parent set styles pseudo element before, namely 100% height, center alignment and inline block model. It’s the same with block a line block model is placed, centered. To block didn't "fall" under pseudo element, when the dimensions of the first one are greater than parent, indicate parent white-space: nowrap and font-size: 0, after which block cancel these styles with the following - white-space: normal. IN in this example font-size: 0 is needed to remove the resulting space between parent And block due to code formatting. The space can be removed in other ways, but it is considered best to simply avoid it.

Parent ( width: 100%; height: 100%; position: absolute; top: 0; left: 0; overflow: auto; white-space: nowrap; text-align: center; font-size: 0; &:before ( height: 100%; display: inline-block; vertical-align: middle; content: ""; ; img (display: block; border: none; ) )

Or, if you need the parent to take up only the height and width of the window, and not the entire page:

Parent ( position: fixed; top: 0; right: 0; bottom: 0; left: 0; overflow: auto; white-space: nowrap; text-align: center; font-size: 0; &:before ( height: 100%; display: inline-block; vertical-align: middle; content: ""; ( display: block; border: none; ) )

Option 5. Flexbox.

One of the simplest and most elegant ways is to use flexbox. It does not require unnecessary body movements, quite clearly describes the essence of what is happening, and is highly flexible. The only thing worth remembering when choosing this method- support for IE from version 10 inclusive. caniuse.com/#feat=flexbox

Parent ( width: 100%; height: 100%; position: fixed; top: 0; left: 0; display: flex; align-items: center; align-content: center; justify-content: center; overflow: auto; ) .block ( background: #60a839; img ( display: block; border: none; ) )

Option 6. Transform.

Suitable if we are limited by the structure, and there is no way to manipulate the parent element, but the block needs to be aligned somehow. will come to the rescue css function translate() . A value of 50% absolute positioning will position the top left corner of the block exactly in the center, then a negative translate value will move the block relative to its own dimensions. Please note that they may float negative effects in the form of blurred edges or font style. Also, this method can lead to problems with calculating the position of the block using java-script. Sometimes, to compensate for the loss of 50% of the width due to the use of the CSS left property, the rule specified for the block can help: margin-right: -50%; .

Parent ( width: 100%; height: 100%; position: fixed; top: 0; left: 0; overflow: auto; ) .block ( position: absolute; top: 50%; left: 50%; transform: translate( -50%, -50%); img (display: block; ) )

Option 7. Button.

User azproduction option where block framed in a button tag. The button has the property of centering everything that is inside it, namely the elements of the inline and block-line (inline-block) model. In practice I do not recommend using it.

Parent ( width: 100%; height: 100%; position: absolute; top: 0; left: 0; overflow: auto; background: none; border: none; outline: none; ) .block ( display: inline-block; img (display: block;; border: none; ) )

Bonus

Using the idea of ​​the 4th option, you can set margins For block, and the latter will be adequately displayed surrounded by scrollbars.
Example: jsfiddle.net/serdidg/nfqg9rza/2.

You can also align the image to the center, and if the image is larger parent, scale it to size parent.
Example: jsfiddle.net/serdidg/nfqg9rza/3.
Example with a large picture:

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 ; )

Main disadvantage this decision, from a semantic point of view, the table is not used for 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 indoor unit takes up no more than one line of text, then you can use the line-height property and set it equal to height external 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:

  • Command the external unit relative positioning position: relative , and the inner one is absolute position: absolute ;
  • Add several 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 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, which 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 when absolute positioning 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 constantly find "critical" errors when it comes to actual responsive design.

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

Let's talk about the CSS vertical align property

When I first started working in web development, I struggled a bit with this property. I thought it should work like 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 text divs, 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 parent container with display: table and inside it - required quantity columns 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 same height. When a table cell's contents don't use everything available space height, the browser automatically adds vertical padding to center the content.

position property

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

  • 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 it 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 value(Not static).

Let's get down to business!

Do you want to implement CSS alignment centered vertically? 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 align text to CSS center vertically. 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 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.

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. Align using:

  • 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 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 to see their boundaries.

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 thing is that the vertical-align property affects the alignment the element itself, not its contents(except when it is applied to table cells). Therefore, applying this property to external element didn't give anything. Moreover, applying this property to the inner element will also do nothing, since line blocks(inline-block) 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 the 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 limited number cases when the heights of both blocks are known.

Alignment using 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/

Also this technique can also be used to align multi-line text if you override 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 "stretch"

This method can be used when the height of the external block is unknown, but the height of the internal block is known.

To do this you need:

  1. set relative positioning to the external block, and absolute positioning to the internal block;
  2. 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;
  3. 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 with 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 with transform

This method is similar to the previous one, but it can be used when the height of the indoor unit 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 in previous method Couldn't you set the value as a percentage? Since percentage values margin properties are calculated relative to the parent element, a value of 50% would be equal to half the height of the outer box, and we needed 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

Most modern way 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 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.

Tags: Add tags

When creating div blocks, you've probably come across situations where you need to center your div horizontally and vertically using pure CSS. For example, when creating pop-ups with . There are several ways to implement centering, and in this article I'll share my favorite and easiest ways, using CSS or jQuery.

First, the basics:

Horizontal centering in CSS

This is easy to do, we use margin for our div block.

ClassName( margin:0 auto; width:200px; height:200px; )

For centering block div only horizontally, you need to define the block width (width), use the property auto for margins left and right. This method will work for everyone block elements(div, p, h1, and so on...). For use horizontal centering for string elements (links, pictures...), you need to apply the parameter display:block;

Horizontal and vertical centering in CSS

Centering a div block horizontally and vertically at the same time is a little trickier. You need to know the dimensions of the div block ahead of time.

ClassName( width:300px; height:200px; position:absolute; left:50%; top:50%; margin:-100px 0 0 -150px; )

By using absolute By positioning a block, we can detach it from surrounding elements and determine its position in relation to the size of the browser window. Move the div block to 50% to the left and top of the window. The top left corner of the block is now in the center of the browser window. All that remains is to install the div block in the center of the page by moving it to half its width left and half its height up. Hooray! The result was excellent centering of the block on pure css code.

Horizontal and vertical centering with jQuery

As mentioned earlier – CSS method centering only works with fixed dimensions. If the dimensions are not defined, the jQuery method will come to the rescue:

$(window).resize(function())( $(".className").css(( position:"absolute", left: ($(window).width() - $(".className").outerWidth( ))/2, top: ($(window).height() - $(".className").outerHeight())/2 )); // To run the function when the window is loaded: $(window).resize();

Operation this method is to run the resize() function using the line $(window).resize(). This function works whenever the browser window is resized. We use outerWidth() And outerHeight(), because in contrast width() And height(), they include padding and border thickness in the size they return. Last line, starts the process centering div block when loading the page.

The advantage of using this method is that you may not know what size the div is. Main disadvantage– this only works when JavaScript is enabled. Therefore, this method is acceptable for multifunctional interfaces such as VKontakte, Facebook, etc.

As always, feel free to suggest your favorite method for centering blocks by commenting.