CSS - Center Alignment. All Vertical Alignment Methods in CSS

In CSS, some seemingly simple things are not so easy to do. One of these things is alignment, i.e. when one element needs to be positioned in a certain way relative to another.

This article presents some ready-made solutions, which will help simplify the work of centering elements horizontally and/or vertically.

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

CSS - Center Align Block

1. Aligning one block to the center of another. In this case, the first and second blocks have dynamic sizes.

...
...

Parent ( position: relative; ) .child ( position: absolute; left: 50%; top: 50%; -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50% , -50%); -ms-transform: translate(-50%, -50%); -o-transform: translate(-50%, -50%); ; )

2. Aligning one block to the center of another. In this case, the second block has fixed dimensions.

Parent ( position: relative; ) .child ( position: absolute; left: 50%; top: 50%; /* width and height of 2 blocks */ width: 500px; height: 250px; /* Values ​​are determined depending on its size */ /* margin-left = - width / 2 */ margin-left: -250px; /* margin-top = - height / 2 */ margin-top: -125px )

Browsers that support this solution:

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

3. Aligning one block to the center of another. In this case, the second block has dimensions specified in percentages.

Parent ( position: relative; ) .child ( position: absolute; /* width and height of 2 blocks in % */ height: 50%; width: 50%; /* Values ​​are determined depending on its size in % */ left: 25%; /* (100% - width) / 2 */ top: 25%; /* (100% - height) / 2 */ )

Browsers that support this solution:

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

CSS - Horizontal Alignment

1. Align one block element(display: block) relative to the other one (in which it is located) horizontally:

...
...

Block ( margin-left: auto; margin-right: auto; )

Browsers that support this solution:

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

2. Aligning a line (display: inline) or line-block (display: inline-block) element horizontally:

...
...

Parent ( text-align: center; ) .child ( display: inline-block; )

Browsers that support this solution:

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

CSS - Vertical Alignment

1. Center one element (display: inline, display: inline-block) relative 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 solution:

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

2. Centering one block relative to another vertically by representing the parent as a table, and the child as a cell of this table.

Parent ( display: table; ) .child ( display: table-cell; vertical-align: middle; )

Browsers that support this solution:

  • 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 alignment solutions, then share them in the comments.

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 element, 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 indoor unit 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 so that we can 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 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 the application of 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/

Obvious minus this decision– 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 a limited number of 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 multiline 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/

Minus 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 to external unit relative positioning, and to the internal – absolute;
  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 a 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

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

It's easiest with using CSS align blocks whose height (for vertical alignment) or width (for horizontal alignment) is known in advance.

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 indoor unit to assign 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 is 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

With vertical alignment much more problems- 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 not installed zero size font, 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. C set value"middle", the content inside the cell is aligned to the center. Of course, tabular layout is now considered archaic, 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!

Alignment of various elements, as on a website or page, is initially for someone challenging task, which changes the vertical alignment of the text. Oddly enough, one of the most complicated ways using CSS is to center the content. Centering content horizontally is relatively easy at some points in time. Centering content vertically is almost always difficult. Centering different element, which needs to be set vertically using CSS. This is definitely a very frequently asked question that creates problems for designers and web masters. However, there are many methods for performing vertical centering, and each of them is quite easy to use.

If you've ever tried it, it's tricky, especially if you want to avoid using tables. Luckily, our cries for help have been heard, and one of the new weapons added to the CSS arsenal to solve this problem is a type of layout known as a flexible box layout. As you'll find out in a few moments, it provides you with some really great features to simplify complex layouts. Part of this excellent functionality also allows you to center your content vertically and horizontally, and that's what we'll cover in this tutorial. You can do this with padding to some extent, but it may take your layout to smaller screens. Adding a custom CSS class to your stylesheet means you can vertically center any content in seconds.

Horizontal alignment determines how the left and right edges of a paragraph line up between the left and right edges of the text box. Vertical alignment determines the vertical placement of the character in the text field. Absence good ways vertical centering elements in CSS has been a dark flaw in its reputation for pretty much its entire existence.

First method with line-height

First the way goes simple and somewhat banal, which has its drawbacks and will limit its use. When coding html pages for a website line spacing text content is probably one of the attributes that is usually left as default. In general, we need to set the height of the line itself, which comes with a similar height for the block where it is used line-height property.


This is the first method shown in the demonstrations



CSS

Constutesim_first(
border: 2px solid #bf1515;
height: 175px;
}
.constutesim_first > p(
line-height:175px;
margin:0;
text-align:center;
padding: 0;
font-size: 17px;
color: #3152a0;
font-family: Tahoma;
font-weight: bold;
}


You can also immediately see how everything will look in reality.

Using a similar method, it is possible to realize how to position the image, which will be in the center and certainly vertical. Here all that remains is to specify one property: vertical-align: middle; which is responsible for displaying the image.


.png">Second variation, which comes with an image


CSS

Second-variation(
border: 2px solid red;
line-height:158px;
}

Second-variation div(
text-align:center;
}
.second-variation img (
vertical-align: middle;
border: 0px solid #3a3838;
}


We implement centered and vertical snapshots of images.

Alignment with position property

This is probably the most known method, but the most common application is to use it with CSS. But here we need to add that it is also not ideal and this method also has its own small nuances that are associated with the center of the element, which if it is set as a percentage, then centering will become left side the top side, inside the blog itself.




CSS

Competaird-option (
border: 2px solid #d40e0e;
height: 162px;
position: relative;
}
.competaird-option div (
position: absolute;
top: 50%;
left: 50%;
height: 28%;
width: 49%;
margin: -2% 0 0 -25%;
border: 2px solid #4a4848;
}


Line spacing or line height is the vertical height between lines of text in shaded HTML page. Almost always this distance value is set to an appropriate value by the browser or rendering engine. This value usually depends on the font of the page being displayed and other factors.

Alignment with table property

In this method we use proven and old method, where we convert the elements into a table in which the cells are located. As for the tag called table, it will not be used here, here we will set completely different ones CSS property, this is display: table;, display: table-cell;. If we talk about the oldest versions of IE, then the data will simply not be displayed here. I hope you have updated your browser, as it is no longer relevant and displays almost everything incorrectly.

Cherevert-variation (
border: 2px solid #c30b0b;
height: 173px;
display: table;
width: 100%;
font-size: 17px;
font-weight: bold;
color: #3945a0;
}

Cherevert-variation div(
display: table-cell;
vertical-align: middle;
text-align:center;
}


First of all, let's see what is the default that is used by most browsers. Most modern daytime browsers have line spacing.

Alignment with flex property

Here we come to more original version, which has its own properties that are rarely found in the layout of an Internet resource. But they are still used, and in some cases they are useful. This establishes the main axis, so the definition of the directional flex elements is placed in the floppy container.


Alignment with flex property


CSS

Variant-horizontal (
border: 2px solid #d20c0c;
height: 147px;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
font-weight: bold;
color: #49518c;
}


You can specify a value for row-height the same way you would specify any other size in css, either as a number, pixel size, or percentage.

Alignment with transform property

And now we have come to the most extreme method, but not to the most recent application in the use of its web design. Everything is simple here, you need to shift the specified element vertically to the value you need. Property transform, this is a list of transformations that the installer applies when installing the package. The installer applies the transformations in the same order as they are specified in the property.


Alignment with transform property


CSS

Vertical-medilpasudsa (
border: 2px solid #e00a0a;
height: 158px;
font-size: 19px;
font-weight: bold;
color: #353c71;
}
.vertical-medilpasudsa > div(
position: relative;
top: 50%;
transform: translateY(-50%);
text-align:center;
}


When you specify values ​​as a number, it will use the current font size as a base. The current font size is multiplied by the number you specify to calculate the line height or space between lines.

If you want to center characters horizontally in an element, you should use text-align: center. One option is if you want to center it vertically and you have a fixed header footer and one row of text, set the line height to be the same as the height of your footer.

If you need to center text inside an element such as a div, header or paragraph, you can use text-align property CSS.

Text-align has several valid properties:

Center: Texture is centered;
left: Will be aligned to the left side of the container;
right: Aligned to the right side of the container
justify: Forced to align with both the left and right edges of the container, with the exception of the outermost lines;
justify-all: Makes the extreme line justify the signs;
start: The same as on the left, only if the direction goes from left to right side. But it will be correct if you initially set the text direction, which will happen from right to left;
End: The opposite of the beginning;
match-parent: Similar to inheritance, except for start and end, it is calculated relative to the parent element;

Use these properties to align text within a parent or wrapper div. If you want to center text horizontally in an element, you should use text-align: center.

One option is if you want to center it vertically, if you have a fixed header footer and one row of text, set the line height to be the same as the height of your footer.

Vlad Merzhevich

Due to the fact that the contents of table cells can be simultaneously aligned horizontally and vertically, the possibilities for controlling the position of elements relative to each other are expanded. Tables allow you to specify image alignment, text, form fields and other elements relative to each other and the web page as a whole. In general, alignment is mainly necessary to establish visual communication between different elements, as well as their groupings.

Vertical centering

One way to show the visitor the focus and name of the site is to use a splash page. This is the first page on which, as a rule, there is a flash splash screen or a picture expressing main idea site. The image is also a link to other sections of the site. You need to place this image in the center of the browser window, regardless of the monitor resolution. For this purpose, you can use a table with a width and height of 100% (example 1).

Example 1: Centering the drawing

Alignment

IN in this example horizontal alignment is set using the align="center" tag parameter , and the contents of the cell may not be centered vertically, since this is the default position.

To set the table height to 100%, you need to remove, the code ceases to be valid.

Using width and height throughout accessible area web page guarantees that the contents of the table will be aligned strictly in the center of the browser window, regardless of its size.

Horizontal alignment

By combining the align (horizontal alignment) and valign (vertical alignment) attributes of the tag , it is permissible to set several types of positions of elements relative to each other. In Fig. Figure 1 shows ways to align elements horizontally.

Let's look at some examples of text alignment according to the figure below.

Top Alignment

To specify the top alignment of cell contents, for a tag required to install valign attribute with the value top (example 2).

Example 2: Using valign

Alignment

Column 1 Column 2

In this example, cell characteristics are controlled using tag parameters , but it’s also more convenient to change through styles.

In particular, the alignment in cells is specified by the vertical-align and text-align properties (example 3).

Alignment

Column 1 Column 2

Example 3: Applying styles for alignment

To shorten the code, this example uses grouping of selectors because the vertical-align and padding properties are applied to two cells at the same time.

Bottom alignment is done in the same way, but instead of the top value, bottom is used.

Center alignment

By default, cell contents are aligned to the center of their vertical line, so if the columns have different heights, you need to set the alignment to the top edge.

Sometimes you still need to leave the original alignment method, for example, when placing formulas, as shown in Fig. 2.

Alignment

(18.6)

In this case, the formula is located strictly in the center of the browser window, and its number is located on the right edge. To arrange the elements in this way, you will need a table with three cells. The outer cells should have the same dimensions, in the middle cell the alignment is centered, and in the right cell - along the right edge (example 4). This number of cells is required to ensure that the formula is positioned in the center.

Example 4: Formula Alignment

In this example, the first cell of the table is left empty; it serves only to create an indent, which, by the way, can also be set using styles.

Aligning Form Elements

Using tables, it is convenient to determine the position of form fields, especially when they are interspersed with text. One of the design options for the form, which is intended for entering a comment, is shown in Fig. 3.

Alignment

To ensure that the text next to the form fields is right-aligned and the form elements themselves are left-aligned, you will need a table with an invisible border and two columns. The left column will contain the text itself, and the right column will contain text fields (example 5).
Example 5: Aligning Form Fields
Name

A comment