Html centered. Centering the div and other positioning subtleties. To align a block vertically inside the parent block

Very often the task is to align the block to the center of the page / screen, and even so that without a java script, without setting hard sizes or negative indents, so that the scrollbars work on the parent if the block exceeds its size. There are quite a lot of monotonous examples on the net of 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 indicated.

Option 1. Negative padding.

Positioning block 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 behaves not quite correctly in the environment of scrollbars - it is simply cut off because it has negative indents.

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 indent.

Less common, but similar to the first. For block set the width and height, position the top right bottom left attributes to 0, and set the margin auto. The advantage of this option is the working scrollbars parent, if the latter has 100% width and height. The downside of this method is the rigid sizing.

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.

We ask parent table styles, cell parent Set text alignment to center. A bloc set the inline block model. The disadvantages are not working scrollbars, and in general, not the aesthetics of the "emulation" of the table.

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 structure.
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 tasks. The point is to have parent set styles pseudo element before, namely 100% height, center alignment and inline box model. Same with block put the model of the inline block, center alignment. To block didn't fall under pseudo element when the dimensions of the first one are greater than parent, specify parent white-space: nowrap and font-size: 0 after which y block cancel these styles with the following - white-space: normal. In this example, font-size: 0 is needed in order to remove the resulting space between parent And block in connection with code formatting. The gap can be removed in other ways, but it is considered best to simply not allow 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 want the parent to only take up the height and width of the window, 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, describes the essence of what is happening quite clearly, and has high flexibility. The only thing to remember 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 translate() css function will come to the rescue. A value of 50% absolute position will position the box's top-left corner exactly in the center, then a negative translate value will move the box relative to its own dimensions. Please note that negative effects may appear in the form of blurry edges or font style. Also, a similar method can lead to problems with calculating the position of the block using java-script "a. Sometimes, to compensate for the loss of 50% of the width due to the use of the left css property, the rule set on 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 option where block wrapped in a button tag. The button has the ability to center everything that is inside it, namely the elements of the inline and block-line (inline-block) model. I don't recommend it in practice.

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 margins for block, and at the same time the latter will be adequately displayed in the environment of scrollbars.
Example: jsfiddle.net/serdidg/nfqg9rza/2 .

You can also align the picture in the center, and if the picture is larger parent, scale it to size parent.
Example: jsfiddle.net/serdidg/nfqg9rza/3 .
Big picture example:

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

If there are usually no problems with text alignment horizontally (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 can solve all problems. But it was not there.

It is necessary to take into account such a moment 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 a video:

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

Method A. As one solution, you can place the text not in a div element, but in a table cell.

Line 1

Line 2

Line 3

Method B. Use property display:table-cell;

Line 1

Line 2

Line 3

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

Situation 1.Alignment of a single line of text.

Let's consider a simple example.

The line of text is at the top. Because we have only one line of text, then for alignment you 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 that the text is in.

Line to be vertically aligned

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

Situation 2. If the exact values ​​of the width and height of the child block are known, where the text itself is located.

This solution involves using the position:absolute property for the child block, its absolute positioning 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 to negative values ​​for the margin-left and margin-top properties.

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

As you can see, something as simple as aligning text to the center turned out to be not so easy in practice.

Horizontally aligning content that has a float property can be done very easily and is also completely cross-browser (works in Opera 8+, Firefox 3+, IE 5.5+).

div block alignment example

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

This way you can achieve the following centering:

The inner block with id = block-inner has a green border, the outer block with id = block has a dotted 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; )

Menu Item Alignment Example

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

For example, you can align the menu like this:

The li items 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.

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

Yes, for vertical alignment in CSS there is a special vertical-align property with many values. However, in practice it does not work as expected. Let's try to figure this out.


Let's compare the following approaches. Alignment with:

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

There are two div elements, with one nested within the other. Let's give them the appropriate classes − outer and inner .


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

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

Remember that alignment only applies to elements that have the inline or inline-block display mode.

Let's set the sizes for the blocks, as well as the 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 fact is that the vertical-align property affects the alignment the element itself, not its content(except when it is applied to table cells). Therefore, applying this property to the outer element did nothing. Moreover, applying this property to the inner element will also do nothing, since inline-blocks are vertically aligned with neighboring blocks, and in our case we have one inline-block.

There are several techniques to solve this problem. Let's take a closer look at each of them below.

Alignment with a table

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


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

The obvious disadvantage of this solution is that from the point of view of semantics it is wrong to use tables for alignment. The second disadvantage is that to create a table, you need to add 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.

Alignment with padding

If the heights of the inner and outer block are known, then the alignment can be set using the vertical padding of the inner block, 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 a limited number of cases when the heights of both blocks are known.

Alignment with line-height

If you know that the inner block should take up 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 add white-space: nowrap and overflow: hidden rules as well.

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

This technique can also be used to align multiline text if you override the line-height value for the inner block, and add the rules display: inline-block and vertical-align: middle .

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

The disadvantage of this method is that the height of the outer block must be known.

Stretch Alignment

This method can be used when the height of the outer block is unknown, but the height of the inner one is known.

For this you need:

  1. set relative positioning to the outer block, and absolute positioning to the inner block;
  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 the value 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 essence of this technique is that setting a height for a stretched and absolutely positioned block causes the browser to calculate vertical padding in equal proportions if their value is set to auto .

Alignment 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 one is known.

You need to set the outer block to relative positioning, and the inner block to absolute positioning. You then need to move the inner box down half the height of the outer box top: 50% and move 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.

Alignment with transform

This method is similar to the previous one, but it can be applied when the height of the inner block is unknown. In this case, instead of setting a negative padding in pixels, you can use the transform property and lift the inner box up with 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 method it was impossible to set the value as a percentage? Since the percentage values ​​of the margin property are relative to the parent element, a value of 50% would equal half the height of the outer box, and we would need to raise the inner box by half its own height. This is exactly what the transform property is for.

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

Alignment 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 block needs to be set to display: flex , and the inner block 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 (such as icons), a negative margin-top approach is ideal.
  • For more complex cases where the height of the block is unknown, a pseudo-element or the transform property should be used.
  • Well, if you are lucky enough not to need to support older versions of IE, then of course Flexbox is better.

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

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

Vertical centering problem

Horizontal centering is very simple and easy. When the centered element is inline, use the alignment property relative to the parent element. When the element is a block element, 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 for vertical centering. Everything looks quite logical. If you've used table templates, you've probably used the valign attribute extensively, which reinforces the belief that vertical-align is the right way to go.

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

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

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

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

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

line-height method

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

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

HTML:

Desired text

CSS:

#child ( line-height: 200px; )

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

Centering an image with line-height

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

HTML:

CSS:

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

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

CSS Table Method

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

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

HTML:

Content

CSS:

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

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

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

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

Absolute positioning and negative margins

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

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

HTML:

Content

CSS:

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

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

This method does not work in all browsers.

Absolute positioning and stretching

The example code performs vertical and horizontal centering.

HTML:

Content

CSS:

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

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

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

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

Equal padding top and bottom

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

HTML:

Content

CSS:

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

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

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

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

150 + 150 + 100 = 400

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

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

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

floating div

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

HTML:

Content

CSS:

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

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

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

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

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

Conclusion

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

 
Articles By topic:
What is a landing page and how should it look like What is the name of a landing page on the Internet
Most owners of private businesses, various services and small organizations understand how important it is to conduct business online. Creating a website and maintaining a page in social networks is now part of the marketing strategy of any company. But few companies and
How to install your template on ucoz - A program that you did not know about, we are learning to connect!
How to Install a Joomla Template - Troubleshooting - 4.5 out of 5 based on 2 votes Selecting, installing and configuring a template is one of the most important steps in creating a Joomla site. In this tutorial, we'll look at how to install a template
Faibisovich - a guide to the design of electrical networks
HANDBOOK ON THE DESIGN OF ELECTRIC NETWORKS Edited by D. L. FAIBISOVICH Edition 4, revised and supplemented Reviewer V. V. Mogirev Authors : I. G. Karapetyan (pp. 3.2, 5.1, 5.3–5.8, sec. 6, sec. 7), D. L. Faibisovi
Computer software User computer information software
Software or software (SW) is an integral part of a computer. Software is a logical continuation of technical means that expands the possibilities and scope of the use of computers. For the functioning of the computer, a set of software is used.