Horizontal alignment of content, which has the float property, can be done very easily and is also completely cross-browser (works in Opera 8+, Firefox 3+, IE 5.5+).

Example of div block alignment

To align a float block or multiple blocks in a row, you need another outer block. The outer block and inner blocks are assigned position: absolute; and float: left; , assign external left: 50%; , and for internal blocks right: 50%; . To use float: right; need to assign external assign right: 50%; , and for internal blocks left: 50%; . I recommend clearing floats by placing a block with the clear: both; property after the center-aligned elements. .

This way you can achieve the following centering:

Has a green border indoor unit with id = block-inner, the outer block with id = block has an intermittent red border.

Block content

#block ( position: relative; float: left; left: 50%; border: 1px dashed #a00; ) #block-inner ( position: relative; float: left; right: 50%; border: 2px solid #0a0; padding : 10px; ) #page (overflow: hidden; )

Example of menu item alignment

In practice, the above example can be applied when horizontally aligning a site menu. However, you need to take into account that with a sufficiently large number of items (occupying more than half the page in width), horizontal scrolling appears. To get rid of it, you need to apply the overflow property in the external block. If the menu is a drop-down menu, then its drop-down items can be cut off by this external block. To avoid this problem, you need to apply the overflow property to a block that is as enclosing as possible, for example, the outermost block that frames the entire content of the page.

For example, you can align the menu like this:

Items li of the ul list have a green border, and the ul list has a dashed red border.

The HTML code for the example below looks like this:

The CSS code for the example below looks like this:

#menu ( position: relative; float: left; left: 50%; border: 1px dashed #a00; list-style: none; margin: 0; padding: 0; ) #menu li ( position: relative; float: left; right: 50%; border: 2px solid #0a0; padding: 10px; #page (overflow: hidden; )

So it's pretty simple. I wish you success in mastering new methods.

Web designers use DIVs in their work every day. Without any understatement, this is the most popular tag. Open the source of any website and you will see that most, if not two thirds of the objects are enclosed in

. Even with the advent of HTML5 and the emergence of serious competitors in the form of article or header, it continues to be inserted into markup everywhere. Therefore, I suggest you understand the issue of formatting and centering div blocks.

What is DIV

The name of the element comes from the English word division, which means division. When writing markup, it is used to break elements into blocks. DIVs enclose groups of content on a web page. For example, images, paragraphs with text. The tag does not affect the display of content in any way and does not carry any semantic load.

DIV supports all global attributes. But for web design you only need two - class and id. You will only remember about everyone else in exotic cases, and that’s not a fact. The align attribute, which used to be used to center or left align divs, has been deprecated.

When to use DIVs

Imagine that the site is a refrigerator, and the DIVs are plastic containers into which you need to sort the contents. You wouldn't put fruit in the same container with liverwurst. You will place each type of product separately. Web content is generated in a similar way.

Open any website and divide it into meaningful blocks. Header at the top, footer at the bottom, main text in the center. On the side there is usually a smaller column with advertising content or a tag cloud.

Document

Now look at each section in more detail. Start with header. The site header has a separate logo, navigation, first-level heading, and sometimes a slogan. Assign each semantic block its own container. This will not only separate the elements in the flow, but also make them easier to format. You'll find it much easier to center an object in a DIV tag by giving it a class or ID.

Centering DIVs Using Margins

When processing web elements, the browser considers three properties: padding, marging and border. Padding is the space between content and its border. Margin - fields that separate one object from another. Border is the lines along the blocks. They can be assigned to all of them at once or only to one side:

div( border: 1px solid #333; border-left: none; )

These properties add free space between objects, and also help to align and place them as needed. For example, if a block with an image needs to be shifted from the left edge to the center by 20%, you assign a margin-left value of 20% to the element:

Block-with-img( margin-left: 20%; )

Elements can also be formatted using their width values ​​and negative padding. For example, there is a block with dimensions 200px by 200px. First, let's assign it an absolute position and move it to the center by 50%.

Div( position: absolute; left: 50%; )

Now, to ensure that the centered DIV is positioned perfectly, we give it a negative margin to the left equal to 50% of its width, that is -100 pixels:

Margin-left: -100px;

In CSS this is called "air removal". But it has a significant drawback in the need to make constant calculations, which is quite difficult to do for elements with several levels of nesting. If the padding and border-width values ​​are specified, the browser will by default calculate the dimensions of the container as the sum of the thickness of the borders, the padding on the right and left, and the content itself inside, which can also come as a surprise.

So when you need to center a DIV, use the box-sizing property with the value border-box. This will prevent the browser from adding padding and border values ​​to the overall width of the DIV element. To raise or lower an element, also use negative values. But in this case, they can be assigned to either the top or bottom field of the container.

How to center a DIV block using automatic margins

This is an easy way to center large blocks. You simply assign the width of the container and the margin property to auto. The browser will place a block in the middle with equal margins on the left and right, doing all the work itself. As a result, you do not risk getting confused in mathematical calculations and significantly save your time.

Use the auto-field method when developing responsive apps. The main thing is to assign a width value to the container in em or percentage. The example code above will center the DIV on any device, including mobile phones, it will occupy 90% of the screen.

Alignment via display property: inline-block

By default, DIV elements are considered block elements, and their display value is block. For this method you will need to override this property. Only suitable for DIVs with a parent container:

Any text

An element with the outer-div class is assigned a text-align property with a value of center, which centers the text inside. But for now the browser sees the nested DIV as a block object. For the text-align property to work, the inner-div must be treated as lowercase. So in the CSS table for the inner-div selector you write the following code:

Inner-div( display: inline-block; )

You change the display property from block to inline-block.

transform/translate method

Cascading style sheets make it possible to move, skew, rotate, and otherwise transform web elements at will. The transform property is used for this. The values ​​indicate the desired transformation type and degree. In this example we will work with translate:

transform: translate(50%, 50%);

The translate function moves an element from its current position left/right and up/down. Two values ​​are passed in brackets:

  • degree of horizontal movement;
  • degree of vertical movement.

If an element needs to be moved along only one of the coordinate axes, then after the word translate you indicate the name of the axis and in parentheses the amount of the required displacement:

Transform: translateY(-20%);

In some manuals you can find transform with vendor prefixes:

Webkit-transform: translate(50%, 50%); -ms-transform: translate(50%, 50%); transform: translate(50%, 50%);

In 2018, this is no longer necessary; the property is supported by all browsers, including Edge and IE.

In order to center the DIV we want, the CSS translate function is written with a value of 50% for the vertical and horizontal axis. This will cause the browser to offset the element from its current position by half its width and height. The width and height properties must be specified:

Document

Keep in mind that the element to which the transform property is applied moves independently of the objects surrounding it. On the one hand, this is convenient, but sometimes by moving, the DIV can overlap another container. Therefore, this method of centering web components is considered non-standard and is used only in cases of extreme necessity. Transformations according to all CSS canons are used for animation.

Working with Flexbox layout

Flexbox is considered a sophisticated way to design web layouts. But if you master it, you will understand that it is much simpler and more enjoyable than standard ways formatting. The Flexbox specification is a flexible and incredibly powerful way to handle elements. WITH English language The name of the module is translated as “flexible container”. The values ​​of width, height, and arrangement of elements are adjusted automatically, without calculating indents and margins.

In previous examples, we already worked with the display property, but we set it to block and inline-block values. To create flex layouts we will use display: flex. First we need a flex container:

To convert it to a flex container in cascading tables, we write:

Flex-container( display: flex; )

All nested objects, but only direct descendants, will be flex elements:

First
Second
Third
Fourth

If you place a list inside a flex container, then the li list items are not considered flex elements. Flexbox layout will only work on ul:

Rules for placing flex elements

To manage flex items, you need justify-content and align-items. Depending on the values ​​you specify, these two properties automatically place objects as needed. If we need to center all nested DIVs, we write justify-content: center, align-items: center and nothing else. The browser will do the rest of the work itself:

Document

First
Second
Third
Fourth

To center text on DIVs that are flex items, you can use the standard text-align technique. Or you can make each nested DIV also a flex container and manage the content using justify-content. This method is much more rational if it contains a variety of content, including graphics, other nested objects, including multi-level lists.

Task

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

Solution

By default, a block element's width is set to 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.

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 alignment using style sheets. Unlike blocks, for which you need to change the margins, in CSS alignment Centering the text is done using one 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 that 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 used much more often.

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.

A layout task that is very common is aligning text vertically in a div block.

If there are usually no problems with horizontal text alignment (we use the text-align:center property and everything will be fine), then with vertical alignment everything is a little more complicated.

There is one property in CSS called vertical-align. It would seem that using it you can solve all problems. But that was not the case.

It is necessary to take into account the fact that vertical-align can only be used to align the contents of table cells or for inline elements, to align them relative to each other within the same line.

For block elements, the vertical-align property does not work.

There are two ways to get out of this situation:

For those who prefer to watch everything in video:

For those who love text, read below for a solution to this problem.

Method A. One solution is to place the text not in a div element, but in a table cell.

Line 1

Line 2

Line 3

Method B. Use the display:table-cell property;

Line 1

Line 2

Line 3

One problem, this property is not supported Internet Explorer 6-7 versions.

Situation 1.Align one line of text.

Let's look at a simple example.

A line of text is positioned along the top edge. Because We have only one line of text, so for alignment we can use the most in a simple way: This is adding a line-height property with a value equal to the height of the div element in which the text is located.

The line that should be vertically aligned

This method works well when you only have one line of text.

Situation 2. If you know the exact width and height of the child block, where the text itself is located.

This solution involves using the position:absolute property for the child block, positioning it absolutely relative to the parent block with position:relative.

Line 1

Line 2

Line 3

Knowing the width and height of the block, you can take half of this value and set it with negative values ​​for the margin-left and margin-top properties.

If you do not need support for older browsers, this option will be the most optimal.

As you can see, such a simple task as centering text turned out to be not so simple in practice.


Close