Block in the center of the css. Centering tools in css. How to center align a DIV block using auto margins

02/18/15 21.4K

If you cut any site created on html based , then you will see a certain layer-by-layer structure. And their appearance it will be like a puff pastry. If you think so, then most likely you have not eaten for a long time. So satisfy your hunger first, and then we'll show you how to center the div layer on your site:

Benefits of layout with a tag

There are two main types of building a site structure:

  • Tabular;
  • Blocky.

Table layout has been dominant since the dawn of the Internet. Its advantages include the accuracy of a given positioning. But, nevertheless, it has obvious drawbacks. The main ones are the volume of the code and low speed downloads.

When using tabular layout, the web page will not be displayed until it is fully loaded. Whereas when using div blocks, the elements are displayed immediately.

In addition to the high loading speed, the block construction of the site allows several times to reduce the volume html code ... Including through the use of CSS classes.

However, table layout should be used to structure the display of data on a page. A classic example of its use is displaying tables.

Block building based on tags

also called layer-by-layer, and the blocks themselves are layers. This is because when using certain property values, they can be stacked one on top of the other, like layers in Photoshop.

Positioning aids

In block layout, layer positioning is best done using cascading style sheets. The main CSS property responsible for positioning

, is a float.
Property syntax:
float: left | right | none | inherit,
Where:

  • left - aligns the element to the left of the screen. The flow around the rest of the elements occurs on the right;
  • right - alignment to the right, flow around other elements - to the left;
  • none - no wrap is allowed;
  • inherit - inherit the value of the parent element.

Let's look at a lightweight example of positioning divs using this property:

Left block




Now let's try to use the same property to position the third div in the center of the page. But unfortunately float has no center value. And when you set a new block to the alignment value to the right or left, it is shifted in the specified direction. Therefore, it remains only to set float: left to all three blocks:


But this is not the best option either. When the window is reduced, all layers are arranged in one row vertically, and when the size is increased, they stick to the left edge of the window. Therefore, we need a better way to center align the div.

Centering layers

In the next example, we will use a container layer to place the rest of the elements. This solves the problem of blocks shifting relative to each other when the window is resized. Centering the container in the middle is done by setting the margin properties to zero for the top margin and auto on the sides (margin: 0 auto):

Left block

Central block




This same example shows how you can center a div horizontally. And if you slightly edit the above code, you can achieve vertical alignment of the blocks. To do this, you just need to change the length of the container layer (reduce it). That is, after editing its css, the class should look like this:

After the change, all blocks will line up strictly in a row in the middle. And their position will not change at any size of the browser window. This is what the vertical centering of the div looks like:


In the following example, we used a number of new css properties to center the layers inside the container:


A short description of the css properties and their values \u200b\u200bthat we used in this example to center a div inside a div:
  • display: inline-block - Aligns a block element to a line and ensures that it is wrapped around another element.
  • vertical-align: middle - aligns the element in the middle with respect to the parent;
  • margin-left - sets the margin to the left.

How to make a link from a layer

As strange as it sounds, this is possible. Sometimes a div block as a link may be needed when laying out various types of menus. Let's consider a practical example of implementing a link layer:

Link to our website



In this example, using the line display: block, we set the link to the value of the block element. And to make the entire height of the div block a link, set height: 100%.

Hiding and Showing Block Elements

Block elements provide more options for extending the functionality of the interface than the outdated table layout. It often happens that the site design is unique and recognizable. But for such an exclusive you have to pay with a lack of free space.

Especially it concerns home page, the cost of placing an advertisement on which is the highest. Therefore, there is a problem where to "shove" another advertising banner. Aligning the div to the center of the page is not enough!

A more rational solution is to make some block hidden. Here's a simple example of such an implementation:

This is a magic button. Clicking on it will hide or show the hiding block.



Centering items vertically with using CSS is a challenge that presents 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 general description tasks.

Vertical centering problem

Centering horizontally is very simple and easy. When the centered element is inline, use the parent-align property. When the element is block-based, we set its width and automatic installation left and right margins.

Most people, when using the text-align: property, refer to the vertical-align property to center vertically. Everything looks logical enough. If you've used tabular templates, you've probably used the valign attribute heavily, 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 to it. It also affects table cells and some inline elements.

The value of the vertical-align property acts in relation to the parent inline element.

  • In a line of text, alignment is performed in relation to the line height.
  • Alignment is used in the table cell in relation to the value calculated by a special algorithm (usually the row height is obtained).

Unfortunately, the vertical-align property has no effect on block-level elements (like 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 for centering block elements, the choice of which depends on what is 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, the free space will be distributed evenly at the top and bottom of the text. And the line will be centered vertically. Often, the line height is made equal to the element height.

HTML:

Desired text

CSS:

#child (line-height: 200px;)

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

Centering an image using line-height

What if the content is a picture? Will the above method work? The answer lies in one more line of CSS.

HTML:

CSS:

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

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

CSS tables method

It was mentioned above that 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 for it to vertically center the content.

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 tabular display for the parent div, and the nested div is displayed 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 above method, 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. We 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 the same horizontal and vertical centering:

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 type of positioning of the elements. Then, for the nested div, set the top and left properties to 50%, which is the center of the parent. But the top-left corner of the nested element is centered. Therefore, you need to raise 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 knowledge of the element's height is necessary in this case. Then we set the element to 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 does centering vertically and horizontally.

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 borders of the parent element by setting the top, bottom, right, and left properties to 0.

Setting it to auto-form margins on all sides will set equal values \u200b\u200bon all 4 sides and place our nested div in the center of the parent element.

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

Equal top and bottom margins

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

HTML:

Content

CSS:

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

The example CSS code sets the top and bottom margins for both elements. For a nested element, setting the padding will serve for vertical centering. And the padding of the parent element will center the nested element in it.

For dynamic change element sizes used relative units measurements. And for absolute units of measurement, you have to do calculations.

For example, if the parent element is 400 px and the nested element is 100px, then 150px top and bottom margins are required.

150 + 150 + 100 = 400

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

This method works everywhere. Back side is the need for calculations.

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

Floating div

This method uses an empty div element that floats and helps control the position of our nested element in the document. Note that the floating div is positioned 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 set its height to 50% of the parent element. This way it will fill the top half of the parent.

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

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

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

Conclusion

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

I think many of you who have done layout have come across the need to align elements vertically and know what difficulties arise when aligning an element to the center.

Yes, for vertical alignment, CSS has a special vertical-align property with multiple values. In practice, however, it does not work at all as expected. Let's try to figure it out.


Let's compare the following approaches. Align with:

  • tables,
  • indents,
  • line-height,
  • stretching,
  • negative margin,
  • transform,
  • pseudo-element,
  • flexbox.
As an illustration, consider the following example.

There are two divs, with one nested within the other. Let's give them the corresponding classes - outer and inner.


The challenge is to align the inner element to the center of the outer element.

To begin with, consider the case when the dimensions of the external and internal block known... Let's add display: inline-block to the inner element, and text-align: center and vertical-align: middle to the outer one.

Remember that alignment is only applied to elements that have inline or inline-block display mode.

Give the blocks sizes and background colors to see their borders.

Outer (width: 200px; height: 200px; text-align: center; vertical-align: middle; background-color: #ffc;) .inner (display: inline-block; width: 100px; height: 100px; background-color : #fcc;)
After applying the styles, we will see that the inner block is aligned horizontally, but not vertically:
http://jsfiddle.net/c1bgfffq/

Why did it happen? The point is that the vertical-align property affects alignment the element itself, not its content (except when it applies to table cells). Therefore, applying this property to an external element did nothing. Moreover, applying this property to an inner element will also do nothing, since inline-blocks are vertically aligned relative to adjacent blocks, and in our case we have one inline block.

There are several techniques for solving this problem. Below we will take a closer look at each of them.

Align with a table

The first solution that comes to mind is to replace the outer block with a one-cell table. In this case, the alignment will be applied to the contents of the cell, that is, to the inner block.


http://jsfiddle.net/c1bgfffq/1/

An obvious disadvantage this decision - from the point of view of semantics, it is wrong to use tables for alignment. The second drawback is that creating the table requires adding one more element around the outer block.

The first minus can be partially removed by replacing the table and td tags with div and setting the table display mode in CSS.


.outer-wrapper (display: table;) .outer (display: table-cell;)
Nevertheless, the outer block will still remain a table with all the ensuing consequences.

Align with indents

If the heights of the inner and outer boxes are known, then the alignment can be set using the vertical padding of the inner box using the formula: (H outer - H inner) / 2.

Outer (height: 200px;) .inner (height: 100px; margin: 50px 0;)
http://jsfiddle.net/c1bgfffq/6/

The disadvantage of the solution is that it is applicable only in limited number cases when the heights of both blocks are known.

Aligning with line-height

If you know that the inner block should occupy no more than one line of text, then you can use the line-height property and set it equal to the height of the outer block. Since the content of the inner block should not wrap to the second line, it is recommended to also add the white-space: nowrap and overflow: hidden rules.

Outer (height: 200px; line-height: 200px;) .inner (white-space: nowrap; overflow: hidden;)
http://jsfiddle.net/c1bgfffq/12/

Also this technique can also be used to align multiline text by redefining the line-height value for the inner block and adding display: inline-block and vertical-align: middle rules

Outer (height: 200px; line-height: 200px;) .inner (line-height: normal; display: inline-block; vertical-align: middle;)
http://jsfiddle.net/c1bgfffq/15/

Minus this method is that the height of the outdoor unit must be known.

Stretch alignment

This method can be used when the height of the outdoor unit is unknown, but the height of the indoor unit is known.

For this you need:

  1. set the outer block relative positioning, and the inner one - absolute;
  2. add the rules top: 0 and bottom: 0 to the inner block, as a result of which it will stretch to the entire height of the outer block;
  3. set to auto for the vertical padding of the inner block.
.outer (position: relative;) .inner (height: 100px; position: absolute; top: 0; bottom: 0; margin: auto 0;)
http://jsfiddle.net/c1bgfffq/4/

The gist of this technique is that specifying the height for a stretched and absolutely positioned box forces the browser to calculate vertical margins in equal proportions when set to auto.

Aligning with negative margin-top

This method has become widely known and is used very often. Like the previous one, it is applied when the height of the outer block is unknown, but the height of the inner block is known.

You need to set the outer block relative positioning, and the inner one - absolute. Then you need to nudge the inner box down half the height of the outer box top: 50% and raise it up half its own height margin-top: -H inner / 2.

Outer (position: relative;) .inner (height: 100px; position: absolute; top: 50%; margin-top: -50px;)
http://jsfiddle.net/c1bgfffq/13/

The disadvantage of this method is that the height of the indoor unit must be known.

Aligning with transform

This method is similar to the previous one, but it can be applied when the height of the indoor unit is unknown. In this case, instead of setting a negative pixel padding, you can use the transform property and move the inner block up using the translateY function and a value of -50%.

Outer (position: relative;) .inner (position: absolute; top: 50%; transform: translateY (-50%);)
http://jsfiddle.net/c1bgfffq/9/

Why in the previous way it was impossible to set a value in percentage? Since the percentage values \u200b\u200bof the margin property are calculated relative to the parent element, a 50% value would be half the height of the outer box, and we needed to raise the inner box half its own height. The transform property is just right for this.

The disadvantage of this method is that it cannot be applied if the internal block has absolute positioning.

Align with Flexbox

The most modern way to vertically align is to use Flexible Box Layout (popularly known as Flexbox). This module allows you to flexibly control the positioning of elements on the page, placing them almost anywhere. Center alignment for Flexbox is a very simple task.

The outer box needs to be set to display: flex, and the inner box needs to be set to margin: auto. And it's all! Beautiful, is not it?

Outer (display: flex; width: 200px; height: 200px;) .inner (width: 100px; margin: auto;)
http://jsfiddle.net/c1bgfffq/14/

The disadvantage of this method is that Flexbox is only supported by modern browsers.

Which way to choose?

It is necessary to proceed from the statement of the problem:
  • For vertical alignment of text, it is better to use vertical padding or the line-height property.
  • For absolutely positioned elements with a known height (like icons), the negative margin-top property is ideal.
  • For more complex cases, when the block height is unknown, you need to use a pseudo-element or the transform property.
  • Well, if you are so lucky that you do not need to support older versions of the IE browser, then of course it is better to use Flexbox.

Tags: Add Tags

The alignment of elements horizontally and vertically can be done different ways... The choice of method depends on the type of element (block or inline), on the type of positioning, dimensions, etc.

1. Horizontal alignment to the center of the block / page

1.1. If the block has a width:

div (width: 300px; margin: 0 auto; / * center the element horizontally within the parent block * /)

If you need to align line element in this way, it needs to set display: block;

1.2. If the block is nested in another block and no width is set / set for it:

.wrapper (text-align: center;)

1.3. If the block has a width and needs to be fixed to the center of the parent block:

.wrapper (position: relative; / * set the relative positioning for the parent box, so that later it will absolutely position the box inside it * /) .box (width: 400px; position: absolute; left: 50%; margin-left: -200px; / * shift the block to the left by a distance equal to half of its width * /)

1.4. If no width is specified for the blocks, you can center using the parent wrapper block:

.wrapper (text-align: center; / * position the content of the block in the center * /) .box (display: inline-block; / * arrange the blocks in a row horizontally * / margin-right: -0.25em; / * remove the right indent between blocks * /)

2. Vertical alignment

2.1. If the text spans one line, for example, for buttons and menu items:

.button (height: 50px; line-height: 50px;)

2.2. To align a block vertically within a parent block:

.wrapper (position: relative;) .box (height: 100px; position: absolute; top: 50%; margin: -50px 0 0 0;)

2.3. Vertical alignment by table type:

.wrapper (display: table; width: 100%;) .box (display: table-cell; height: 100px; text-align: center; vertical-align: middle;)

2.4. If a block has a width and height and needs to be centered on the parent block:

.wrapper (position: relative;) .box (height: 100px; width: 100px; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; overflow: auto; / * to content did not creep * /)

2.5. Absolute positioning in the center of the page / block using CSS3 transform:

if the element is dimensioned

div (width: 300px; / * set the width of the block * / height: 100px; / * set the height of the block * / transform: translate (-50%, -50%); position: absolute; top: 50%; left: 50% ;)

if the element has no dimensions and is not empty

Some text here

h1 (margin: 0; transform: translate (-50%, -50%); position: absolute; top: 50%; left: 50%;)

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

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

Html and its brainchild
and align

This method is almost never used, since it was supplanted by the cascading style sheet tools. Knowing that such a tag exists, however, doesn't hurt you.

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

This type skips prohibited items.

CENTER



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

Below I will give an example in which the picture and paragraph will be centered.

align

This content will be centered.



Note that the attribute we parsed has slightly different meanings for the picture.

In the example I used align \u003d "middle "... This aligns the image so that the sentence is clearly in the middle of the image.

Centering tools in css

Css properties for aligning blocks, text and graphic content are used much more often. This is primarily due to the convenience and flexibility of the styles implementation.

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

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

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

text-align

Offer on the right

Sentence using end



I'll tell you about a little trick. When choosing a value justify the last line can dangle ugly from below. In order to position it, for example, in the center, you can use the property text-align-last.

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

Keyword Purpose
baseline Specifies the alignment with the ancestor line, which is called the baseline. If the ancestor object does not have such a line, then the alignment occurs according to the lower border.
middle The center of the mutable object is aligned to the baseline, to which the parent element's height floor is added.
bottom The bottom of the selected content adjusts to the bottom of the object below all.
top Similar to bottom, but with the top of the object.
super Makes a character superscript.
sub Descends the element.
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 INE TABOUTTO


vertical-align

C INE TABOUTTO


Indentation

And finally, we have come to the indentation in the paragraph. The css language uses a special property called text-indent.

It can be used to make both a red line and a ledge (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.



Did you like the article? To share with friends: