the Internet Windows Android

Horizontal and vertical element alignment. Vertical alignment of elements with CSS

I think many of you who had to play layout came across the need to align elements vertically and know which difficulties arise when aligning the element in the center.

Yes, for vertical alignment in CSS there is a special version of Vertical-Align with many values. However, in practice it works at all as expected. Let's try to figure it out.


Compare the following approaches. Alignment with:

  • tables,
  • indents
  • line HEIGHT,
  • stretching
  • negative Margin,
  • tRANSFORM,
  • pseudo-element
  • flexbox.
As an illustration, consider the following example.

There are two DIV elements, while one of them is embedded in another. We give them the appropriate classes - Outer and Inner.


The task is to align the inner element in the center of the external element.

To begin with, consider the case when the sizes of the external and inner block known. Add the Internal Element The Display Rule: inline-block, and external - Text-Align: Center and Vertical-Align: Middle.

Npomnia that alignment applies only to elements that have an inline or inline-block display mode.

We set the blocks dimensions as well as background colors to see their borders.

Outer (Width: 200px; Height: 200px; text-align: center; vertical-align: middle; background-color: #ffc; )inner (display: inline-block; width: 100px; Height: 100px; background-color : #fcc;)
After applying styles, we will see that the inner block was leveled horizontally, and there are no vertical:
http://jsfiddle.net/c1bgfffq/

Why did it happen? The fact is that the Vertical-Align property affects alignment the element itself, and not its contents (except when it applies to table cells). Therefore, application this property It did not give anything to the outside element. Moreover, the use of this property to the inner element will also give anything, since the lowercase blocks (inline-block) are aligned vertically relative to neighboring blocks, and in our case we have one lowercase block.

To solve this problem, there are several techniques. Below more Consider each of them.

Alignment using a table

The first permissal solution is to replace the external block of the table from 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//

Obvious minus this solution - From the point of view of semantics, it is incorrectly applying tables for alignment. The second minus is that it is necessary to add another element around the external block to create a table.

The first minus can be partially removed, replacing Table and TD tags on DIV and setting the table mode of display in CSS.


.OUTER-Wrapper (Display: Table;) .OUTER (Display: Table-Cell;)
Nevertheless, the external unit will still remain a table with all the consequences of this.

Alignment with indents

If the height of the internal and external block is known, then the alignment can be asked using vertical indents from the inner unit using the formula: (H Outer - H inner) / 2.

Outer (Height: 200px;) .inner (Height: 100px; margin: 50px 0;)
http://jsfiddle.net/c1bgfffq/6/

Minus solutions - it applies only to a limited number of cases when both blocks are known.

Line-Height alignment

If it is known that the internal unit should take no more than one line of the text, you can use the Line-Height property and set it an equal height of the external block. Since the content of the internal unit should not be transferred to the second line, it is also recommended to add the WHITE-SPACE rules: Nowrap and Overflow: Hidden.

Outer (Height: 200px; Line-Height: 200px;) .inner (White-Space: Nowrap; Overflow: Hidden;)
http://jsfiddle.net/c1bgfffq/12/

Also, this technique can also be applied to the alignment of multi-line text if for the indoor unit to override the Line-Height value, as well as add Display: Inline-Block and Vertical-Align: Middle.

Outer (Height: 200px; Line-Height: 200px;) .inner (Line-Height: Normal; Display: Inline-Block; Vertical-Align: Middle;)
http://jsfiddle.net/c1bgfffq/15/

Minus this method It is that the height of the external block should be known.

Alignment with "stretching"

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

For this you need:

  1. set the external block relative positioning, and internal - absolute;
  2. add the internal block of the Top: 0 and Bottom: 0, as a result of which it stretches to the entire height of the external block;
  3. set the AUTO value for vertical indentation of the indoor unit.
.OUTER (Position: relative; )inner (Height: 100px; Position: absolute; top: 0; bottom: 0; margin: auto 0;)
http://jsfiddle.net/c1bgfffq/4/

The essence of this technique is that the set of height for the stretched and absolutely socked block causes the browser to calculate the vertical indents in an equal ratio if their value is set to AUTO.

Alignment with the help of negative margin-top

This method has received wide fame and is used very often. As the previous one, it is used when the height of the outer block is unknown, but the height of the internal is known.

It is necessary to specify the external block of relative positioning, and the internal is absolute. Then it is necessary to move the inner block down on half the height of the external block Top: 50% and raise up half of the high height of Margin-TOP: -H Inner / 2.

Outer (Position: relative;) .inner (Height: 100px; Position: absolute; top: 50%; margin-top: -50px;)
http://jsfiddle.net/c1bgfffq/13/

The minus of this method - the height of the indoor unit should be known.

Alignment with Transform

This method is similar to the previous one, but it can be applied when the height of the inner block is unknown. In this case, instead of setting a negative retardation in pixels, you can use the TRANSFORM property and raise the internal block up using the TRANSLATEY function and the value -50%.

Outer (Position: relative;) .inner (Position: Absolute; Top: 50%; transform: translatey (-50%);)
http://jsfiddle.net/c1bgfffq/9/

Why in the previous way it was impossible to set a value in percent? Since the percentage values \u200b\u200bof the MARGIN property are calculated relative to the parent element, the value of 50% would be half the height of the external block, and we needed to raise the inner block on half of its own height. For this, the TRANSFORM property is suitable.

The minus of this method - it cannot be applied if the internal unit has absolute positioning.

Alignment with FlexBox

The most modern way of vertical alignment is to use Flexible Box Layout (people are known as FlexBox). This module Allows you to flexibly manage the positioning of the elements on the page, by placing them practically as you please. Alignment in the center for FlexBox is a very simple task.

The external unit needs to set Display: Flex, and internal - 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 minus of this method - FlexBox is supported only by modern browsers.

What is the way to choose?

It is necessary to proceed from the setting of the problem:
  • For vertical text alignment, it is better to use vertical indents or Line-Height property.
  • For absolutely positioned elements with a known height (for example, icons), a method with a negative MARGIN-TOP property is ideal.
  • For more complex cases, when the block height is unknown, you need to use a pseudo-element or the TRANSFORM property.
  • Well, if you are lucky so much that you do not need to maintain the old versions of the IE browser, then, of course, it is better to use Flexbox.

Tags: Add Tags

Each layer is constantly facing the need to align the content in the block: horizontally or vertically. There are some good articles on this subject, but they all offer a lot of interesting things, but few practical options, because of which you have to spend too much time to highlight the main thing. I decided to submit this information in the form that is convenient for me to no longer google.

Aligning blocks with known sizes

The easiest S. using CSS. Align the blocks in which the height is known in advance (for vertical alignment) or width (for horizontal alignment).

Alignment with Padding

Sometimes you can not center the item, but add it the border with the border " padding".

For example, there is a picture of 200 per 200 pixels, and it is required to center it in block 240 to 300. We can set the height and width by the external block \u003d 200px, and add to 20 pixels from above and below, and 50 on the left and right.

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

Alignment of absolutely positioned blocks

If the block is set " position: Absolute.", then it can be positioned relative to the nearest parent with" Position: Relative ". For this you need to all properties (" top.","right","bottom","left.") An internal unit to assign same valueAs well as "Margin: Auto".

* There is a nuance: the width (height) of the indoor unit + the LEFT value (Right, Bottom, TOP) should not exceed the size of the parent block. Reliable LEFT properties (Right, Bottom, Top) assign 0 (zero).

.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 by "Text-Align: Center"

To align text in the block there is a special property " text-Align.". With the set value" center"Each line of text is leveling horizontally. For multi-line text, such a solution is used extremely rare, more often this option can be found for the alignment of spans, links or pictures.

Once I had to invent the text to show how the text alignment works with CSS, but nothing interesting to the head came. At first, I decided to copy somewhere in the children's poem somewhere, but I remembered that it may, resort the uniqueness of the article, and our dear readers will not be able to find it in Google. And then I decided to write this this paragraph - after all, the essence is not with it, but the essence in alignment.

.example-text (Text-Align: Center; Padding: 10px; Background: # FF90B8;)

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

But this text is aligned to the left edge, but it is in the block that is leveling relative to the wrapper in the center.

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

Block alignment with margin

Block elements with a well-known width are easily aligned horizontally, if you install "Margin-Left: Auto; Margin-Right: Auto". Usually an abbreviated entry is used: " margin: 0 AUTO"(Instead of zero, there may be any meaning). But for the vertical leveling, this method is not suitable.

.lama-wrapper (Height: 200px; Background: # F1BF88;) .Lama1 (Height: 200px; width: 200px; background: url (lama.jpg); margin: 0 auto;)

This is how it is necessary to align all blocks, where possible (where the fixed or absolute positioning is not required) is the most logical and adequate. Although it seems obvious, but sometimes I saw the frightening examples with negative retreats, so I decided to clarify.

Vertical alignment

With vertical leveling, much more problems - apparently, this in CSS has not been provided. There are several ways to achieve the desired result, but all of them are not very beautiful.

Line-Height alignment

In the case when only one line in the block, it is possible to achieve its vertical alignment by applying the property " line-Height"And setting it the desired height. For reliability it is necessary to install 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 a block alignment with several lines. To do this, you will have to use an additional block wrapper, and set the height of the line to it. The internal unit can be multiline, but necessarily "inline". You need to apply "Vertical-Align: Middle".

.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; Text-Align: Center;)

The wrapper unit must be installed "Font-Size: 0". If you do not set the zero font size, the browser will add several unnecessary pixels from itself. You also have to specify the font size and string height for the inner block, because these properties are inherited from the parent.

Vertical Alignment in Tables

Property " vertical-align"Also acts on the cells of the table. With the set" Middle "value, the content inside the cell is aligned in the center. Of course, a table layout in our time is considered an archaic, but in exceptional cases it is possible to simulate it, indicating" display: Table-Cell".

Usually for vertical alignment I use this option. Below the example of the layout taken from the ready-made project. Interest is the picture that is centered by vertical in this way.

.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 the element is installed "Float" is different from "None", then it will be block in any case (Display: Block) - then you will have to use an additional block wrap.

Aligning an additional inline element

And for inline elements you can apply " vERTICAL-ALIGN: MIDDLE". At the same time all elements with" display: Inline", Which are in one line, are leveled relative to the total central line.

It is necessary to create an auxiliary block with a height of equal to the height of the parent block, then the desired block is leveled in the center. To do this, it is convenient to use pseudo-elements: Before or: Afterter.

.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 are not very interested in Explorer 8 users or care so much that you are ready to insert a piece of unnecessary JavaScript-A for them, then you can use "Display: Flex". Flex blocks are perfectly coping with alignment problems, and it is enough to write "Margin: Auto" to center the content inside.

So far, such a way practically did not meet me, but there is no special restrictions for him.

.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 the centering of the content will not be a problem!

When laying the page, it is often necessary to perform alignment in the center of the CSS method: for example, centen the main unit. There are several options for solving this problem, each of which is sooner or later you have to use any vertigist.

Leveling text in the center

Often in decorative purposes you need to set the text alignment in the center, CSS in this case allows you to reduce the layout time. Previously, this was done using HTML attributes, now the standard requires to align text using style sheets. Unlike blocks for which you need to change external indents, in CSS, text alignment in the center is performed using one line:

  • tEXT-ALIGN: CENTER;

This property is inherited and transferred to all descendants from the parent. It affects not only text, but also on other elements. To do this, they must be flat (for example, span) or straight block (any blocks that the Display: Block property is specified). The last option also allows you to change the width and height of the element, to adjust the indents more flexibly.

Often on Align pages are attributed to the tag itself. This immediately makes the code of an invalid, since the W3C recognized the Align attribute obsolete. Using it on the page is not recommended.

Block alignment in the center

If you need to set the alignment of the DIV in the center, CSS can offer pretty convenient way: Using the external indentation of MARGIN. The indents can be defined both block elements and luxury blocks. The value of the Prix must take values \u200b\u200b0 (vertical indents) and AUTO (automatic indents horizontally):

  • margin: 0 AUTO;

Now this option is recognized as absolutely valid. Using external indents also allows you to set the picture alignment in the center: Allows you to solve many problems associated with the positioning of the item on the page.

Alignment block on the left or right edge

Sometimes the alignment in the center CSS is not required, but it is necessary to put two blocks nearby: one from the left edge, the other - from the right. To do this, there is a Float property that can take one of three values: Left, Right or None. Suppose you have two blocks that need to be put nearby. Then the code will be like this:

  • .Left (float: left;)
  • .right (Float: Right)

If there is also a third block, which should be located under the first two blocks (for example, a footer), then he needs to register the Clear property:

  • .Left (float: left;)
  • .right (Float: Right)
  • footer (Clear: Both)

The fact is that blocks with LEFT and RIGHT classes fall out of the total flow, that is, all other elements ignore the very existence of the aligned elements. The Clear property: Both allows the Futer or any other block to see the elements dropped out of the stream and prohibits streaming (float) both on the left and right. Therefore, in our example, the footer will shift down.

Vertical alignment

There are cases when it is not enough to set alignment in the center of CSS methods, it is necessary to change the vertical position of the child block. Any lowercase or strainer element can be pressed to the upper or lower edge, to be in the middle of the parent element or be in an arbitrary place. Most often requires alignment of the center of the center, this uses the Vertical-Align attribute. Suppose there are two blocks, one is embedded in another. In this case, the internal unit is a straight block element (Display: Inline-Block). It is necessary to align the Child block vertically:

  • alignment at the upper border - .Child (Vertical-Align: TOP);
  • alignment in the center - .Child (Vertical-Align: Middle);
  • leveling at the bottom border - .Child (Vertical-Align: Bottom);

Neither Text-Align nor Vertical-Align act on block elements.

Possible problems with aligned blocks

Sometimes the alignment of DIV in the center of the CSS way can cause small problems. For example, when using Float: Let's say, there are three blocks: .first, .second i.third. The second and third blocks lie in the first. The element with the SECOND class is aligned to the left edge, and the last block is right. After alignment, both fell out of the stream. If the parent element is not given a height (for example, 30EM), then it will stop stretching at the height of the daughter blocks. To avoid this error, use the "strut" - a special unit that sees.second i.third. CSS code:

  • .second (Float: Left)
  • .Third (Float: Right)
  • .clearFix (Height: 0; Clear: Both;)

The pseudo-class is often used: after, which also allows you to return blocks to a place by creating a pseudransport (in the example in DIV with the CONTAINER class lies inside. FIRST and contains.left i.right):

  • .left (Float: Left)
  • .right (Float: Right)
  • .Container: After (Content: "; Display: Table; Clear: Both;)

The above options are the most common, although there are several variations. You can always find the easiest and most convenient way to create a pseudransport by experiments.

Another problem with which the versions often face is the alignment of the strainer block elements. After each of them, a space is automatically added. Conduct with this helps the MARGIN property, which is given a negative indent. There are other methods that are used much less frequently: for example, the zeroing in this case in the properties of the parent element is prescribed Font-Size: 0. If the text is located inside the blocks, then the desired font size is already returned in the properties of the line-block elements. For example, Font-Size: 1em. The method is not always convenient, so a variant with external returns is much more often used.

Alignment of blocks allows you to create beautiful and functional pages: it is a layout of a shared layout, and the location of goods in online stores and photos on the business card.

When creating a web page layout, you probably encountered a situation where you need to centered the DIV horizontally and vertical using CSS. There are several ways to use CSS and jQuery.

But at the beginning of the foundation:

Horizontal leveling with CSS

Class-Name (
Margin: 0 AUTO;
width: 200px;
Height: 200px;
}

To center the div only horizontally, you must specify the width and automatic value for the left and right margins (this is an abbreviated form of writing CSS properties). This method works on block elements (DIV, P, H1, etc.). To apply it for linear elements (for example, hyperlinks and images), you must write another rule - display: block.

Alignment horizontally and vertical means CSS

Simultaneous centering of DIV horizontally and vertically slightly more cunning. You need to know the DIV dimensions in advance.

Class-Name (
width: 300px;
Height: 200px;
Position: Absolute;
Left: 50%;
Top: 50%;
margin: -100px 0 0 -150px;
}

Using the absolute positioning of the elements, we can pull it out of the stream and set its position with respect to the browser window. By setting the DIV offset by 50% of the left and top of the window, we center the upper left corner relative to the page. The only thing that remains to be done is to shift the div left and up half of its width and height, setting the negative values \u200b\u200bof MARGIN so that it is perfectly located in the center.

Alignment horizontally and vertical using jQuery

As already mentioned, the above CSS method works only with a Div fixed size. JQuery comes to the rescue:

// Announcement Functions:
$ (Window) .resize (Function () (
$ (". Class-Name"). CSS ((
Position: "Absolute",
Left: ($ (Window) .width () - $ (". Class-Name"). Outerwidth ()) / 2,
Top: ($ (Window) .Height () - $ (". Class-name"). OuterHeight ()) / 2
});
});
// Calling Functions:
$ (Window) .resize ();

The function calculates the width of the window in $ (Window) .resize () every time each time the user size changes the user. We use OuterWidth () and OuterHeight (), because in contrast to the usual width () and height (), they add Padding and Border width, returning the size. Finally, we adapt when changing the size of the window and center the div when rebooting the page.

In CSS, some at first glance, simple things turn out to be not so easy to perform. One of these things is the alignment, i.e. When one element must be positioned in a definitely relative other.

This article presents some ready-made solutions that will help simplify the work on the centering of elements horizontally and (or) vertically.

Note: Under each solution, a list of browsers indicating the versions in which the specified CSS code works.

CSS - block alignment in the center

1. Alignment of one block in the center of the other. In this case, the first and second block have dynamic sizes.

...
...

Parent (Position: relative;) .Child: 50%; top: 50%; -Webkit-transform: translate (-50%, -50%); -moz-transform: translate (-50% , -50%); -MS-transform: translate (-50%, -50%); -o-transform: translate (-50%, -50%); transform: translate (-50%, -50%) ;)

2. Alignment of one block in the center of the other. In this case, the second unit has fixed dimensions.

Parent (Position: Absolute; Left: 50%; top: 50%; / * width and height 2 block * / width: 500px; Height: 250px; / * Values \u200b\u200bare determined depending on its size * / * margin-left \u003d - width / 2 * / margin-left: -250px; / * margin-top \u003d - height / 2 * / margin-top: -125px;)

Browsers that support this decision:

  • Chrome 1.0+
  • Firefox 1.0+
  • Internet Explorer 4.0+
  • Opera 7.0+
  • Safari 1.0+

3. Alignment of one block in the center of the other. In this case, the second block has dimensions specified in percent.

Parent (Position: relative;) .Child (Position: Absolute; / * Width and height 2 block in% * / height: 50%; width: 50%; / * Values \u200b\u200bare determined depending on its size in% * / left: 25%; / * (100% - width) / 2 * / TOP: 25%; / * (100% - Height) / 2 * /)

Browsers that support this decision:

  • Chrome 1.0+
  • Firefox 1.0+
  • Internet Explorer 4.0+
  • Opera 7.0+
  • Safari 1.0+

CSS - horizontal leveling

1. Aligning one block element (Display: Block) with respect to the other (in which it is located) horizontally:

...
...

Block (Margin-Left: Auto; Margin-Right: auto;)

Browsers that support this decision:

  • Chrome 1.0+
  • Firefox 1.0+
  • Internet Explorer 6.0+
  • Opera 3.5+
  • Safari 1.0+

2. DISPLAY: INLINE (DISPLAY: INLINE-BLOCK) (Display: Inline-Block) horizontal element:

...
...

Parent (Text-Align: Center;) .Child (Display: Inline-Block;)

Browsers that support this decision:

  • Chrome 1.0+
  • Firefox 3.0+
  • Internet Explorer 8.0+
  • Opera 7.0+
  • Safari 1.0+

CSS - vertical leveling

1. To center one element (Display: Inline, Display: Inline-Block) with respect to the other (in which it is located) in the center. The parent block in this example has a fixed height, which is set using the CSS Line-Height property.

...
...

Parent (Line Height: 500px;) .Child (Display: Inline-Block; Vertical-Align: Middle;)

Browsers that support this decision:

  • Chrome 1.0+
  • Firefox 3.0+
  • Internet Explorer 8.0+
  • Opera 7.0+
  • Safari 1.0+

2. The centering of one block relative to the other vertically by means of presenting the parent as a table, and the child as cells of this table.

Parent (Display: Table-Cell; Vertical-Align: Middle;)

Browsers that support this decision:

  • Chrome 1.0+
  • Firefox 1.0+
  • Internet Explorer 8.0+
  • Opera 7.5+
  • Safari 1.0+

If you know any other interesting tricks or useful ready-made solutions for alignment, then share them in the comments.