Html div center alignment. All Vertical Alignment Methods in CSS

Good day, subscribers and readers of this publication. Today I want to go into detail and tell you how to center text in CSS. In some previous articles, I indirectly touched on this topic, so you have some knowledge in this area.

However, in this publication I will tell you about all the different ways to align objects, and also explain how to indent and redline paragraphs. So let's start learning the material!

HTML and its offspring
and align

This method is almost never used, since it has been replaced by cascading style sheet tools. However, knowing that such a tag exists will not hurt you.

As for validation (this term is described in detail in the article ""), the html specification itself condemns the use of < center>, since for validity it is necessary to use a transition DOCTYPE>.

This typeallows prohibited elements to pass through.

CENTER



Now let's move on to the attribute align. It sets the horizontal alignment of objects on and fits after the tag declaration. Typically, it can be used to align content to the left ( left), along the right edge ( right), centered ( center) and by text width ( justify).

Below I will give an example in which I will place the picture and paragraph in the center.

align

This content will be centered.



Please note that for the image the attribute we are analyzing has slightly different meanings.

In the example I used align="middle". Thanks to this, the image was aligned so that the sentence was located clearly in the middle of the picture.

Centering tools in css

CSS properties designed to align blocks, text and graphic content are used much more often. This is primarily due to the convenience and flexibility of implementing styles.

So let's start with the first property of text centering - this is text-align.

It functions in the same way as align in . Among the keywords, you can select one from the general list or inherit the characteristics of an ancestor ( inherit).

I would like to note that in css3 you can set 2 more parameters: start– depending on the rules of writing text (from right to left or vice versa), sets the alignment to the left or right (similar to the work left or right) and end– the opposite of start (when writing text from left to right it acts as right, when writing from right to left – left).

text-align

Sentence on the right

Sentence using end



I'll tell you about a small trick. When selecting a value justify the last line may dangle unattractively from the bottom. In order to, for example, position it in the center, you can use the property text-align-last.

To align site content or table cells vertically, use the property vertical-align. Below I have described the main keywords of the element.

Keyword Purpose
baseline Specifies alignment to an ancestor line, called the base line. If the ancestor object does not have such a line, then alignment occurs along the lower border.
middle The middle of the mutated object is aligned to the baseline, to which the height floor of the parent element is added.
bottom The bottom of the selected content adjusts to the bottom of the object below it.
top Similar to bottom, but with the top part of the object.
super Makes the character superscript.
sub Makes the element subscript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 vertical-align
C IN E TABOUTTO


vertical-align

C IN E TABOUTTO


Indentations

And finally we come to paragraph indents. The CSS language uses a special property called text-indent.

With its help you can make both a red line and a protrusion (you need to specify a negative value).

text-indent

To create a red line you only need to know one parameter.

This is the simple text-indent property.



Today is a lesson on center alignment of divs using CSS technology.

There are several points here that are not entirely easy to understand. I would like to focus on one of them today.

When blocks flow in a normal flow, aligning one, centered, relative to the parent block in which it is located is not particularly difficult.

For this, standard CSS construction is used.

But what should you do if the block that needs to be aligned to the center has an absolute (absolute) or fixed position (fixed). This situation sometimes happens.

Those. in this case, our example takes the following form.

position:relative; - it was added to the parent block so that the counting comes from it, and not from the tag

position:absolute; - in fact, absolute positioning itself.

After the manipulation, margin:auto stops working.

What should I do? How can I re-align the block to the center?

Today I will talk about a trick that is used in this case. It's actually quite simple, you just need to add two CSS properties for the aligned block.

left:50%; - shift the block relative to the parent by 50% to the left.

margin-left:-150px; - because The counting starts from the upper left edge of the block, then for complete evenness, half of the block needs to be shifted to the left, which we do with a negative indent.

If the block width is specified as a percentage, then the solution could be as follows:

If you need to center a line of text:

Line of text

The point is that when a block is assigned a property with position:absolute. The width of the block with the default width:auto value becomes equal to the content. Therefore the text-align property will not work. For everything to start working, you need to force the width to 100%.

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 there is 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 mistake, use a “spacer” - special block which 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.

Task

Align a block element of a given width to the horizontal center of the web page.

Solution

Default width block element takes the value auto , and it will typically take up the entire available width. Therefore, using the described method, you can center align only an element whose width is explicitly specified in percentages or pixels. After that, you should add a margin to the layer style on the left (style property margin-left ) and on the right (margin-right ) with the value auto . However, you can also use the universal margin property with the value auto (example 1).

Example 1: Aligning a layer to the center

HTML5 CSS 2.1 IE Cr Op Sa Fx

Aligning a layer to the center

The length of the vector reverses the positive double integral.


The result of the example is shown in Fig. 1.

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 free of all the problems listed in previous methods, and also solves the initially set tasks. 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 set, 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: ""; ) .block ( display: inline-block; white-space: normal; vertical-align: middle; text-align: left ; 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: ""; ) .block ( display: inline-block; white-space: normal; vertical-align: middle; text-align: left; img ( 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 using css The left property can be helped by the rule specified for the block: 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 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: