Center positioning. Horizontal and vertical alignment of elements in CSS

Today, dear reader, we will deal with the problem of vertical alignment in a block div.

Most likely you already know about the existence of a wonderful CSS property vertical-align. And God himself ordered us to use precisely this property for vertical alignment (it’s not for nothing that it has such a self-explanatory name).

Formulation of the problem: You need to center the contents of a variable height block relative to the vertical.

Now let's start solving the problem.

And so, we have a block, its height can change:

Block content

The first thing that comes to mind is to do the following feint:

Block content

There is every reason to believe that the phrase Block content will be aligned to the center height of the div container.

But it was not there! We will not achieve any expected center alignment this way. And why? It would seem that everything is indicated correctly. It turns out that this is the rub: the property vertical-align can only be used to align the contents of table cells or to align inline elements relative to each other.

Regarding alignment inside a table cell, I think everything is clear. But I’ll explain another case with inline elements.

Vertical alignment of inline elements

Suppose you have a line of text that is broken up by line tags into parts:

You welcomes piece text!

An inline tag is a container whose appearance does not cause the content to wrap to a new line.

The action of the block tag causes the contents of the container to wrap to a new line.

is a block tag. If we enclose pieces of text in blocks
, then each of them will be on a new line. Using tag , which, unlike
, is lowercase, containers will not be moved to a new line, all containers will remain on the same line.

Container convenient to use when specifying a part of the text with special formatting (highlighting it with a color, a different font, etc.)

For containers Apply the following CSS properties:

#perviy( vertical-align:sub; ) #vtoroy( vertical-align:3px; ) #tretiy( vertical-align:-3px; )

The resulting line of text will look like this:

This is nothing more than vertical alignment of inline elements, and the CSS property vertical-align copes with this task perfectly.

We got a little distracted, now we return to our main task.

Vertical alignment in div container

No matter what, for alignment within the div container we will use the property vertical-align. As I already said, this property can be used in the case of aligning inline elements (we discussed this case in detail above and it is not suitable for us for alignment in a div container); all that remains is to use the fact that vertical-align works for table cells.

How can we use this? We don’t have a table, we work with a div container.

Ha, it turns out to be very simple.

CSS property display allows you to turn our div block into a table cell, this can be done easily and naturally:

Let's say we have a class div textalign:

Block content

For this block we specify the following CSS property:

Textalign( display: table-cell; )

This CSS instruction will miraculously turn our div into a table cell without visually changing it in any way. And for a table cell we can apply the property vertical-align fully and the desired vertical alignment will work.

However, everything cannot end so simply. We have a wonderful IE browser. He doesn't know how to work with the property display: table-cell(I suggest you read the table illustrating the functionality of this CSS property in different browsers on the website htmlbook.ru). Therefore, we will have to resort to various tricks.

There are many ways to achieve alignment in a div container for all browsers:

  • Method using an additional auxiliary div container
  • Method using expression. It is connected with a tricky calculation of block heights. You can't do this without knowledge of JavaScript.
  • Using the line-height property. This method is only suitable for vertical alignment in a block of known height, and therefore is not applicable in the general case.
  • Using absolute and relative content offset in case of IE browser. This method seems to me the most understandable and simple. Additionally, it is implementable for a variable height div container. We will dwell on it in more detail.

As you understand, we just have to solve the problem of vertical alignment in IE, associated with its misunderstanding of the property display: table-cell(neither IE6, nor IE7, nor IE8 not familiar with this property). Therefore, using conditional comment We will specify other CSS properties specifically for browsers of the IE family.

Conditional comment

Construction type:

... Инструкции, действующие только в случае выполнения условия в квадратных скобках...

is called a conditional comment (be careful, the type of conditional comment must completely correspond to the example given, up to a space).

The instructions contained in such a conditional comment will be executed only if the browser interpreting this code belongs to the IE family.

Thus, using a conditional comment, we can hide a piece of code from all browsers except IE.

The solution of the problem

Because of all this parsley, we will need to provide our HTML code with two additional containers. This is what our text block will look like:

This is some kind of verification text.
It consists of two lines.

For div container class textalign CSS properties are set that align its content vertically for all normal browsers (except IE, of course):

Display: table-cell; vertical-align: middle;

And two more properties that set the width and height for the block:

Width:500px; height: 500px;

This is quite enough to align the contents of the container centered relative to the vertical, in all browsers except IE.

Now we begin to add properties related to alignment for browsers of the IE family(it is for them that we used additional blocks div And span):

Referring to the tag div inside a class block textalign. To do this, you need to first indicate the name of the class, and then, separated by a space, the tag to which we are accessing.

Textalign div( position: absolute; top: 50%; )

This design means: for all div tags inside a block with a class textalign apply the listed properties.

Accordingly, the styles specified for the block textalign are modified:

Textalign( display: table-cell; vertical-align: middle; width:500px; height: 500px; position: relative; )

Now the top left point of the text block is moved down by 50%.

To explain what is happening, I drew an illustration:

As you can see from the picture, we have made some progress. But that is not all! The top left point of the yellow block has indeed moved 50% down, relative to the parent (purple) block. But we need it to be at fifty percent of the height of the purple block. center of the yellow block, not its top left point.

Now the tag will come into play span and its relative positioning:

Textalign span( position: relative; top: -50%; )

Thus, we have shifted the yellow block up by 50% of its height, relative to its initial position. As you understand, the height of the yellow block is equal to the height of the centered content. And the last operation on the span container placed our content in the middle of the purple block. Hooray!

Let's play tricks a little

First of all, we need to hide parsley from all normal browsers and open it for IE. This can be done, of course, using a conditional comment; it’s not for nothing that we got acquainted with it:

There is a small problem. If the centered content is too high, then this leads to unpleasant consequences: there is an extra height for the vertical scroll.

Solution to the problem: need to add a property overflow: hidden block textalign.

Get to know the property in detail overflow possible in .

The final CSS instructions for the block textalign has the form:

Textalign( display: table-cell; vertical-align: middle; width:500px; height: 500px; position: relative; overflow: hidden; border: 1px solid black; )

I'm sorry, I forgot to mention one important point. If you try set the height of the class block textalign as a percentage, then you have nothing will work.

Centering in variable height block

Very often there is a need to set the height of a class block textalign not in pixels, but as a percentage of the height of the parent block, and align the contents of the div container in the middle.

The catch is that it is impossible to do this for a table cell (but the class block textalign turns exactly into a table cell, thanks to the property display:table-cell).

In this case, you must use an external block for which the CSS property is specified display:table and already set the percentage value of the height for it. Then the block nested in it, with the CSS directive display:table-cell, will happily inherit the height of the parent block.

In order to implement a variable height block in our example, we will edit the CSS a little:

To the class textalign we will change the property value display With table-cell on table and remove the alignment directive vertical-align: middle. Now we can safely change the height value from 500 pixels to, for example, 100%.

So the CSS properties for the class block textalign will look like this:

Textalign( display: table; width:500px; height: 100%; position: relative; overflow: hidden; border: 1px solid black; )

All that remains is to implement content centering. To do this, a div container nested in a class block textalign(this is the same yellow block in the picture), you need to set the CSS property display:table-cell, then it will inherit the height of 100% from the parent block textalign(purple block). And nothing will stop us from aligning the contents of the nested div container in the center with the property vertical-align: middle.

We get another additional list of CSS properties for the div block nested in the container textalign.

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

That's the whole trick. If desired, you can have a variable height with the content centered.

For more information on vertical alignment of a variable height block, see .

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 setting rigid dimensions or negative indents, and so that the scrollbars 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 disadvantage of this option is that you need to count negative indents. 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 we set the width and height, position the attributes top 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 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 is 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. The css function translate() will come to the rescue. 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 negative effects may appear 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 external 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:

Hello! We continue to master the basics of the HTML language. Let's see what you need to write to align the text to the center, width or edges.

Getting down to business, let's look at how to center text in HTML in three different ways. The last two are linked directly to the style sheet. It can be a CSS file that connects to the pages of the site and defines their appearance.

Method 1 - direct work with HTML

It's actually quite simple. See example below.

Align the paragraph to the center.

If you need to move text fragments in a different way, then instead of the “center” parameter, enter the following values:

  • justify – align text to the width of the page;
  • right – on the right edge;
  • left - to the left.

By analogy, you can move the content that is in the headers (h1, h2) and container (div).

Method 2 and 3 - using styles

The design presented above can be slightly transformed. The effect will be the same. To do this, you need to write the code below.

Text block.

In this form, the code is written directly into the HTML to center the text content.

There is another alternative way to achieve results. You will need to do a couple of steps.

Step 1. In the main code write

Text material.

Step 2. In the included CSS file, enter the following code:

Rovno (text-align:center;)

I note that the word “rovno” is just the name of a class that can be called differently. This is left to the discretion of the programmer.

By analogy, in HTML you can easily make text centered, justified, and aligned to the right or left edge of the page. As you can see, there is far more than one option to achieve your goal.

Just a few questions:

  • Are you doing an information non-profit project?
  • Do you want your website to rank well in search engines?
  • Do you want to earn income online?

If all the answers are positive, then just look at an integrated approach to website development. The information will be especially useful if it runs on the WordPress CMS.

I would like to point out that your own websites are just one of many options for generating passive or active income on the Internet. My blog is dedicated to financial opportunities online.

Have you ever worked in the field of traffic arbitrage, copywriting or other areas of activity that generate primary or additional income through remote collaboration? You can learn about this and much more right now on the pages of my blog.

I will publish a lot of really useful information in the future. Stay in touch. If you wish, you can subscribe to Workip updates by e-mail. The subscription form is located below.

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 a parent container with display: table and inside it the desired number of columns that you want to center using display: table-cell and vertical-align: middle .

See example

Why does this work with table markup but not with div elements? Because the rows in the table have the same height. When a table cell's content does not use all the available height space, the browser automatically adds vertical padding to center the content.

position property

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

  • position: static is the default. The element is rendered according to HTML order;
  • position: absolute - used to determine the exact position of an element. This position is always related to the closest relatively positioned parent element (not static). If you don't determine the exact position of an element, you will lose control of it. It will appear randomly, completely ignoring the flow of the document. By default, the element appears in the upper left corner;
  • position: relative - used to position an element relative to its normal position (static). This value preserves the document flow order;
  • position: fixed - used to position the element relative to the browser window so it is always visible in the viewport.

Note: some properties ( top and z-index) only work if the element is set to position (not static).

Let's get down to business!

Do you want to implement CSS vertical center alignment? First create an element with relative position and dimensions. For example: 100% in width and height.

The second step may vary depending on the target browsers, but you can use one of two options:

  • Old property: need to know the exact size of the window to remove half the width and half the height. See example;
  • New CSS3 property: You can add a transform property with a translate value of 50% and the block will always be in the center. View example.

Basically, if you want to center content, never use top: 40% or left: 300px . This works fine on test screens, but it is not centered.

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

Have you heard of the flexbox specification?

You can use flexbox. This is much better than any other option center text alignment CSS vertically. With flexbox, managing elements is like child's play. The problem is that 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.

When laying out a page, it is often necessary to perform center alignment using the CSS method: for example, centering the main block. There are several options for solving this problem, each of which sooner or later has to be used by any layout designer.

Center text alignment

Often, for decorative purposes, it is necessary to set the text to center alignment; CSS in this case allows you to reduce layout time. Previously, this was done using HTML attributes, but now the standard requires text to be aligned using style sheets. Unlike blocks, for which you need to change the margins, in CSS, centering text is done using a single line:

  • text-align:center;

This property is inherited and passed on from the parent to all descendants. Affects not only the text, but also other elements. To do this, they must be inline (for example, span) or inline-block (any blocks that have the display: block property set). The latter option also allows you to change the width and height of the element and adjust the indents more flexibly.

Often on pages, align is assigned to the tag itself. This immediately invalidates the code, since the W3C has deprecated the align attribute. Using it on a page is not recommended.

Aligning a block to the center

If you need to center a div, CSS offers a pretty convenient way: using margins. Indents can be set for both block elements and inline-block elements. The property value should be 0 (vertical padding) and auto (automatic horizontal padding):

  • margin:0 auto;

Now this option is recognized as absolutely valid. Using external padding also allows you to set the image to be centered: it allows you to solve many problems related to the positioning of an element on the page.

Align a block left or right

Sometimes CSS center alignment is not required, but you need to place two blocks side by side: one on the left edge, the other on the right. For this purpose, there is a float property, which can take one of three values: left, right or none. Let's say you have two blocks that need to be placed side by side. 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 it needs to be given the clear property:

  • .left (float:left;)
  • .right(float:right)
  • footer (clear:both)

The fact is that blocks with the classes left and right fall out of the general flow, that is, all other elements ignore the very existence of aligned elements. The clear:both property allows the footer or any other block to see elements that have fallen out of the flow and prohibits float on both the left and right. Therefore, in our example, the footer will move down.

Vertical alignment

There are times when it is not enough to set the center alignment using CSS methods; you also need to change the vertical position of the child block. Any inline or inline-block element can be nested at the top or bottom edge, in the middle of a parent element, or in any location. Most often, the block needs to be aligned to the center; for this, the vertical-align attribute is used. Let's say there are two blocks, one nested inside the other. In this case, the inner block is an inline-block element (display: inline-block). You need to align the child block vertically:

  • top alignment - .child(vertical-align:top);
  • center alignment - .child(vertical-align:middle);
  • bottom alignment - .child(vertical-align:bottom);

Neither text-align nor vertical-align affects block elements.

Possible problems with aligned blocks

Sometimes centering a div using CSS can cause a little trouble. For example, when using float: let's say there are three blocks: .first, .second and .third. The second and third blocks lie in the first. The element with class second is left aligned, and the last block is right aligned. After leveling off, both fell out of the flow. If the parent element does not have a height set (for example, 30em), then it will no longer stretch to the height of its child blocks. To avoid this error, use a “spacer” - a special block that sees .second and .third. CSS code:

  • .second(float:left)
  • .third(float:right)
  • .clearfix(height:0; clear: both;)

The pseudo-class:after is often used, which also allows you to return the blocks to their place by creating a pseudo-spacer (in the example, a div with the container class lies inside.first and contains.left and.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 simplest and most convenient way to create a pseudo-spacer through experimentation.

Another problem that layout designers often encounter is the alignment of inline-block elements. A space is automatically added after each of them. The margin property, which is set to a negative indent, helps to cope with this. There are other methods that are used much less frequently: for example, zeroing. In this case, font-size: 0 is written in the properties of the parent element. If there is text inside blocks, then the required font size is already returned in the properties of inline-block elements. For example, font-size:1em. This method is not always convenient, so the option with external indents is much more often used.

Aligning blocks allows you to create beautiful and functional pages: this includes the layout of the overall layout, the arrangement of products in online stores, and photographs on a business card website.