Horizontal and vertical alignment of elements in CSS. Center alignment: CSS layout

Centering elements vertically with CSS is a challenge for developers. However, there are several methods for solving it, which are quite simple. This lesson presents 6 options for vertically centering content.

Let's start with a general description of the problem.

Vertical centering problem

Horizontal centering is very simple and easy. When the centered element is inline, use the alignment property relative to the parent element. When the element is block - set its width and automatically set the left and right margins.

Most people, when using the text-align: property, refer to the vertical-align property for vertical centering. Everything looks quite logical. If you've used table templates, you've probably used the valign attribute extensively, which reinforces the belief that vertical-align is the right way to go.

But the valign attribute only works on table cells. And the vertical-align property is very similar. It also affects table cells and some inline elements.

The value of the vertical-align property is relative to the parent inline element.

  • In a line of text, the alignment is relative to the line height.
  • The table cell uses alignment with respect to the value calculated by a special algorithm (usually the line height is obtained).

But unfortunately, the vertical-align property doesn't work on block-level elements (such as paragraphs inside a div element). This situation may lead to the idea that there is no solution to the problem of vertical alignment.

But there are other methods of centering block-level elements, the choice of which depends on what is being centered in relation to the outer container.

line-height method

This method works when you want to vertically center one line of text. All you have to do is set the line height to be larger than the font size.

By default, free space will be distributed evenly above and below the text. And the line will be centered vertically. Often the line height is made equal to the height of the element.

HTML:

Desired text

CSS:

#child ( line-height: 200px; )

This method works in all browsers, although it can only be used for a single line. The value of 200 px in the example is chosen arbitrarily. You can use any value larger than the text font size.

Centering an image with line-height

What if the content is an image? Will the above method work? The answer lies in another line of CSS code.

HTML:

CSS:

#parent ( line-height: 200px; ) #parent img ( vertical-align: middle; )

The value of the line-height property must be greater than the height of the image.

CSS Table Method

As mentioned above, the vertical-align property applies to table cells, where it works great. We can render our element as a table cell and use the vertical-align property on it to center the content vertically.

Note: A CSS table is not the same as an HTML table.

HTML:

Content

CSS:

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

We set the table output to the parent div and render the nested div as a table cell. Now you can use the vertical-align property on the inner container. Everything in it will be centered vertically.

Unlike the method above, in this case the content can be dynamic, as the div element will resize to fit its content.

The disadvantage of this method is that it does not work in older versions of IE. You have to use the display: inline-block property for the nested container.

Absolute positioning and negative margins

This method also works in all browsers. But it requires that the centered element be given a height.

The example code does both horizontal and vertical centering at the same time:

HTML:

Content

CSS:

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

First, we set the positioning type of the elements. Then, on the nested div, set the top and left properties to 50%, which is the center of the parent element. But the top left corner of the nested element gets centered. Therefore, you need to lift it up (half the height) and move it to the left (half the width), and then the center will coincide with the center of the parent element. So knowing the height of the element is necessary in this case. Then we give the element negative top and left margins equal to half the height and width, respectively.

This method does not work in all browsers.

Absolute positioning and stretching

The example code performs vertical and horizontal centering.

HTML:

Content

CSS:

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

The idea behind this method is to stretch the nested element to all 4 of the parent element's borders by setting the top, bottom, right, and left properties to 0.

Setting the margins on all sides to auto will set the values ​​on all 4 sides to be equal, and will bring our nested div element to the center of the parent element.

Unfortunately, this method does not work in IE7 and below.

Equal padding top and bottom

This method explicitly sets equal padding above and below the parent element.

HTML:

Content

CSS:

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

In the CSS code for the example, top and bottom padding is set for both elements. For a nested element, setting the padding will serve to vertically center it. And the padding of the parent element will center the nested element in it.

Relative units are used to dynamically resize elements. And for absolute units of measurement, you will have to do the calculations.

For example, if the parent element is 400px high and the nested element is 100px high, then 150px of padding is required at the top and bottom.

150 + 150 + 100 = 400

Using % allows the calculations to be left to the browser.

This method works everywhere. The downside is the need for calculations.

Note: This method works by setting the margin of the element. You can also use margins within an element. The decision to apply margins or padding should be made depending on the specifics of the project.

floating div

This method uses an empty div element, which floats and helps control the position of our nested element in the document. Note that the floating div is placed before our nested element in the HTML code.

HTML:

Content

CSS:

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

We offset the empty div to the left or right and give it a height of 50% of the parent element. This way it will fill the top half of the parent element.

Since this div is floating, it is removed from the normal flow of the document and we need to unwind the nested element. The example uses clear: both , but it suffices to use the same direction as the offset of the floating empty div element.

The top border of the nested div element is directly below the bottom border of the empty div element. We need to move the nested element up by half the height of the floating empty element. To solve the problem, a negative value of the margin-bottom property for a floating empty div element is used.

This method also works in all browsers. However, using it requires an additional empty div element and knowledge of the height of the nested element.

Conclusion

All methods described are easy to use. The difficulty lies in the fact that none of them is suitable for all cases. It is necessary to analyze the project and choose the one that best suits the requirements.

From the author: I welcome you back to our blog pages. In today's article, I would like to talk about various alignment techniques that can be applied to both blocks and their content. In particular, how to align blocks in css, as well as text alignment.

Align blocks to the center

It's easy to center a block in css. This is the most famous technique for many, but I would like to talk about it right now, first of all. This is meant to be centered horizontally relative to the parent element. How is it carried out? Let's say we have a container and our test subject is in it:

< div id = "wrapper" >

< div id = "header" > < / div >

< / div >

Let's assume that this is the header of the site. It doesn't span the full width of the window and we need to center it. We write like this:

#header(

width / max - width : 800px ;

margin : 0 auto ;

We need to specify the exact or maximum width, and then write the key property - margin: 0 auto. It sets the margins for our header, the first value determines the margins from the top and bottom, and the second - to the right and left. The auto value instructs the browser to automatically calculate the padding on both sides so that the element is exactly centered on the parent element. Conveniently!

Text alignment

This is also a very simple trick. To align all inline elements, you can use the text-align property and its values: left, right, center. The latter centers the text, which is what we want. Even a picture can be aligned in the same way, because it is also an inline element by default.

Align text vertically

But this is already more difficult. By default, there is no such simple well-known property that would easily center text in a block container vertically. However, there are several tricks that layout designers have come up with over the years.

Set block height using padding. The way is to not set an explicit height with height, but create it artificially with top and bottom paddings, which should be the same. Let's create any block and write the following properties to it:

div( background: #ccc; padding: 30px 0; )

div (

background : #ccc;

padding : 30px 0 ;

The background is just to visually see the edges as well as the padding. Now the height of the block is made up of these two indents and the line itself, and it all looks like this:

Define a line-height for the block. It seems to me that this is a more correct way if you need to align one line of text. With it, you can record the normal height using the height property. After that, he also needs to set the height of the line, the same as the height of the block as a whole.

div( height: 60px; line-height: 60px; )

div (

height: 60px

line-height: 60px;

The result will be similar to the above picture. Everything will work even if you add padding. However, only for one line. If you need more text in an element, then this method will not work.

Convert block to table cell. The essence of this method is that the vertical-align: middle property acts on the table cell, which centers the element vertically. Accordingly, in this case, the block must be set to the following:

div( display: table-cell; vertical-align: middle; )

div (

display : table - cell ;

vertical - align : middle ;

This method is nice because you can align as much text as you like in the center. But it’s better to set display: table to the block in which our div is nested, otherwise it may not work.

Well, here we come to the last trick for today - this is the alignment of the blocks themselves vertically. It must be said that again there is no property that is meant specifically for this, but there are a few tricks that you should be aware of.

Set offsets as a percentage. If you know the height of the parent element and place another block-level element inside it, you can center it using percentage padding. For example, the parent has a height of 600px. You put a block in it that has a height of 300px. How much do you need to back up from above and below to center it? 150 pixels each, which is 25% of the parent's height.

This method allows you to do centering only when the dimensions allow you to make calculations. And if you have a parent 887 pixels in height, then you won’t be able to write anything exactly, this is already clear.

Insert an element into a table cell. Again, if we convert the parent element into a table cell, then the block inserted into it will automatically be centered vertically. To do this, the parent just needs to set vertical-align: middle.

And if, in addition to this, we also write margin: 0 auto, then the element will be centered horizontally!

Text Alignment Vertically in CSS- a very difficult job. I've seen enough people struggling with this and I keep finding "critical" bugs when it comes to real 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 the field of web development, I suffered a little with this property. I thought it should work like a classic property “ text-align". Ah, if only it were that easy...

CSS vertical-align property works fine with tables but not with divs or other elements. When you use it on a div , it aligns the element with other blocks, 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 divs with text, you can use the line-height property. This means that you need to know the element's height, but you can't set it. This way your text will always be in the center.

The truth of this approach CSS vertical alignment there is a disadvantage. If the text is multiline, then the line height will be multiplied by the number of lines. Most likely, in this case, you will end up with a terribly designed page.

Take a look at this example

If the content you want to center is more than one line, then it's 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 be centered with display: table-cell and vertical-align: middle .

See example

Why does this work with table layout but not with div elements? Because the rows in the table have the same height. When the content of a table cell doesn't 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 the HTML order;
  • position: absolute - used to determine the exact position of an element. This position is always associated with the nearest relatively positioned parent element (not static). If you don't determine the exact position of an element, you will lose control over it. It will render randomly, completely ignoring the document flow. By default, the element is displayed in the upper left corner;
  • position: relative - used to position an element relative to its normal (static) position. This value preserves the document flow order;
  • position: fixed - used to position the element relative to the browser window so it always appears 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 be different depending on the target browsers, but one of two options can be used:

  • Old property: Need to know the exact size of the window in order 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 great on test screens, but it's not centering.

Remember position: fixed ? You can do the same thing with it as with absolute position, but you don't need a relative position for the parent element - it will always position relative to the browser window.

Have you heard of the flexbox specification?

You can use flexbox . It's much better than any other option. center text align CSS vertically. With flexbox, managing elements is child's play. The problem is that some browsers like IE9 and below need to be dropped. Here is an example of how to vertically center a block:

View example

Using flexbox layout, you can center multiple boxes.

If you apply what you have learned from these examples, you will be able to master CSS align block vertically 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 a friendly project team.

The designer sometimes asks: 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 the demo button or image.

Let's discuss some of the things 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 setting the parent container's text-align property to center . When an element is a block element, to center it, it is enough to set the width (width) and set the values ​​\u200b\u200bof 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. This is 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 on a cell (for example, ). The vertical-align CSS property can be applied to a cell and to some inline elements.

  • Text is centered relative to line-height (line spacing).
  • With regard 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 centering elements vertically, and you can still use the vertical-align property where appropriate. 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 the text to be 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, the height of the parent element is optional.

Here is 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 height of the font. In practice, this method is great for centering a horizontal menu.

CSS Method Using Table Properties

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

Content

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

Unfortunately, this method does not work in older versions of IE. If you need 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 for block-level elements and works in all browsers. You need to set the height of the element to be centered.

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

Content

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

The first step is to position the parent and child elements. Then we set the offset of the child element to 50% relative to the top (top) and left side (left) of the parent element, thus we center the child element relative to the parent. However, our manipulations will put the top right corner of the child element in the center of the parent element, which, of course, does not suit us.

Our task is 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 we 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 for block-level elements. The method works in all browsers, however, the content can exceed the height of the parent element and go beyond it. 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 relatively and absolutely, 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 the child element using the 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 makes the element vertically centered 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 descendant, 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, thanks to which the child element is visually centered vertically.

Content

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

I use relative sizes. If the block sizes are fixed, then some mathematical calculations will be required.

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

150 + 150 + 100 = 400

floating div

This method uses an empty float box 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; )

We first move the floating box to the left (or right) and give it a height of 50% of the parent element. 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 a value of both . I have set the value to both , however you can use whichever value is the same as the floating element's positioning direction.

Now the top edge of the child element is directly below the bottom edge of the floating element. We need to raise the child element by half the height of the floating element. To do this, it is enough to set a negative bottom margin equal to 50% for the floating block.

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

Aligning elements on a web page can be tricky, especially when it comes to aligning text vertically. This question is often found on the forums, and novice users are especially difficult to solve this issue. But in fact, there is nothing complicated here. All it takes is a little knowledge of CSS Cascading Style Sheets. Since this is all done at the expense of its rules.

Vertical alignment of text 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 a few examples, and based on the conditions, you will choose a suitable growth 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

/* #1 */ .talign1( border: 1px solid red; height:200px;/* block height */ ) .talign1 > p( line-height:200px;/* set line height to match block height */ margin :0;/* remove the outer padding, if any */ text-align:center;/* align the text horizontally to the center */ padding: 0;/* remove the inner padding, if any */ ) /* end № one*/

In exactly the same way it is possible to implement a picture in the center of the vertical, but by adding one new property vertical-align: middle; .

Example. Demo #2

Example. Demo #2

/* #2 */ .talign2( border: 1px solid red; line-height:200px;/* block line height */ ) .talign2 div( text-align:center;/* align elements horizontally center */ ) .talign2 img( vertical-align:middle;/* align images vertically centered */ border: 1px solid black; ) /* end #2*/

Alignment with the 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 own side effects. This is because the element's centering, given as a percentage, will be centered on the top-left edge of the inner box.

Therefore, you need to set a negative value for the margins. The padding on the top should be half the height of the inner block, and the padding on the left should be half the width. Thus, we get the absolute center.

In this variant, it is perhaps mandatory to know the exact height and width of the child element. Otherwise, incorrect centering may occur.

/* #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; ) /* end #3*/

Alignment with the table property

Here we use the old technique, turning the elements into a table with cells. In this case, the table tags

will not apply, but 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

/* #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 the flex property

This is a more specific version with properties that are not so common in site layout. But, nevertheless, they are in rare cases very useful.