Centering the div and other positioning subtleties. CSS Positioning

Positioning in CSS seems pretty simple. Indicate which block and where it should be located. However, everything is not as simple as it seems at first glance. There are several points that can confuse newbies. You can get much more value out of positioning if you understand in detail how it works.

Box model in CSS and positioning types.

Before you begin, I advise you to read the article Box Model in CSS. In a nutshell: each element in html is a rectangle for which you can specify the values ​​of the inner and outer margins, as well as the border that separates them.

Positioning schemes define where this rectangle should be located, as well as how it should affect the elements around it.

The position property in CSS can take on five values:

  • absolute
  • relative
  • fixed
  • static
  • inherit

The value static is the default. Any element with static positioning is in the general flow of the document. The rules for its placement are determined by the Box model. For such elements, the top , right , bottom and left properties will be ignored. To use these properties, the element's positioning must be absolute, relative, or fixed.

The inherit value, as with all other CSS properties, is used to ensure that the element uses the same value as its parent element.

Absolute positioning

Absolute positioning removes an element from the overall flow of the document. As for the elements around, in this case they simply ignore the searched one, as if it had the display: none; property set. . If you don't want the space for such an element to be filled with other elements, then you need to come up with a different approach.

You set the position of an element with absolute positioning using the top , left , right and bottom properties. You just need to specify two of them, top or bottom and left or right. If no properties are specified, then the top-left pair is set to 0.

The key to absolute positioning is understanding what your reference point is. If the top property is set to 20px, then where should they be counted from?

The answer is simple: such elements are positioned relative to the nearest parent element, which has a positioning other than static . If there is no such element, then the element is positioned relative to the main document. That is, when setting absolute positioning, CSS tells the browser to look at the parent element and, if its positioning is not static, then it should align the current element relative to it.

Relative positioning.

Relatively positioned elements are placed based on their own position, a normal shift relative to their normal location. This is similar to adding padding to an element using the margin property. However, there is one significant difference: adjacent elements, when using positioning, do not take this shift into account.

Imagine it this way: a certain image is shifted, and in its place a “ghost” remains; all elements are located relative to this “ghost”. This allows us to layer elements on top of each other.

Thus, elements with relative positioning are taken from the element's normal flow, but still influence the placement of neighboring elements, which behave so that the original element is still in the document flow.

In this case, we should not ask the question regarding what the element is positioned here. The answer is always: normal document flow. It looks very much like you added padding to an element, but at the same time did not affect neighboring elements.

Fixed positioning

Fixed positioning acts similar to absolute positioning, with minor differences.

First, a fixed-position element is always positioned relative to the browser window, and parent elements are ignored.

The second difference comes from its name. Fixed elements are fixed on the page. They do not move when scrolling.

Z-index

The site page is two-dimensional. It has width and height. Z-index adds a third dimension, depth.

The higher this index, the higher the element is located on the page. With it we can ensure that one element is placed on top of another. By default, its value is zero. Negative values ​​are also acceptable.

In fact, z-index is much more complex than I describe it here, but that is a topic for another article. Now, the main thing to remember is the very idea of ​​the third dimension and the fact that only positioned elements can use this property.

Positioning problems.

Let's look at a few common problems associated with positioning, as well as a few words about how to solve them.

  1. You cannot use the position property and the float property on the same element at the same time. Both of these properties affect the position of the element, so the last property specified will be used.

    From the comments:

    You can use position:relative and float at the same time.

    When position:absolute and float are specified simultaneously, it is not the last specified property that is applied. In this case, regardless of the order of these styles, position:absolute is applied, and the resulting (or calculated) value of the float property is set to none, regardless of the initial value, i.e. ignored.

  2. Margins do not collapse on absolute positioned elements. Let's say there is a paragraph on the page with a bottom margin of 20px. Following it is an image with a top margin of 30px. The distance between the image and the text will not be 50px (20px + 30px), but 30px (30px > 20px). This behavior is called collapsing margins. Two indents are combined into one. Absolutely positioned elements do not have margins to collapse, so the result may not be what you expect.
  3. IE and z-index. In IE6, an element is always selected at the top of the stack, regardless of its z-index or the z-index of surrounding elements.

IE6 and IE7 have another problem with z-index. IE looks at the parent element to determine which group of elements the top of the stack is in, other browsers use the global context. For example:

We expect the paragraph to appear higher than the image because its z-index is higher. However, IE6 and IE7 place the image higher because they are in different document stacks. One stack is for div, the second is for img, and the image has a higher z-index than the div.

Conclusion

The position property sets the positioning behavior of an element according to one of the positioning schemes. Available property values ​​are absolute , relative , fixed , static (default) and inherit .

Positioning schemes define the rules for placing an element on a web page, as well as the influence on the location of neighboring elements.

The z-index property can only be applied to elements with the position property set. It adds a third dimension to the page and sets the stack order of elements.

The position property seems easy to understand, but it works a little differently than it seems at first glance. Often developers think that they need relative positioning, although most likely they should use absolute positioning. Basically, the float property is used during layout, and the position property is necessary for elements that you want to “take out” from the general flow of the document.

Unusual location!

Decide which element to display in front!

Elements may overlap!

Positioning

CSS positioning properties allow you to position an element. They can also position an element behind another, and specify what should happen when the element's contents are too large.

Elements can be positioned using the top, bottom, left, and right properties. However, these properties will not work unless the position property is set. They also work differently depending on the positioning method.

There are four different positioning methods.

Static Positioning

HTML elements are positioned statically by default. A statically positioned element is always positioned according to the standard flow of elements on the page.

Statically positioned elements are not affected by the top, bottom, left, and right properties.

Fixed Positioning

A fixed-position element is positioned relative to the browser window.

It won't move even if the window is scrolled:

Comment: IE7 and IE8 support the value fixed only if document type!DOCTYPE is specified.

Fixed elements are removed from the normal flow. The document and other elements behave as if the fixed element does not exist.

Fixed elements can overlap other elements.

Relative Positioning

A relatively positioned element is positioned relative to its normal position.

Relatively positioned elements are often used as containers for absolutely positioned elements.

Absolute Positioning

An absolutely positioned element is positioned relative to the first parent element that is positioned other than statically. :

If no such element is found, the parent element is taken as

Absolutely positioned elements can overlap other elements.

Overlapping Elements

When elements are located outside the standard flow, they can overlap other elements.

The z-index property specifies the vertical order of an element (which element should be placed in front or behind other elements).

An element can have a positive or negative vertical order:

An element with greater vertical order is always in front of elements with less vertical order.

Comment: If two positioned elements overlap and no vertical order is specified, the element located later in the HTML code will be shown on top.

More examples

Setting the element's shape
This example demonstrates how to define the shape of an element. The element is clipped to this shape and then displayed.

How to show an overflowed element using scrolling
This example demonstrates how to set the overflow property to create a scrollbar when the element's content is too large to fit in the specified area.

How to force the browser to automatically handle overflow
This example demonstrates how to force the browser to automatically handle overflow.

Cursor change
This example demonstrates how to change the cursor.

All CSS Positioning Properties

The number in the "CSS" column indicates which version of CSS the property is defined in (CSS1 or CSS2).

Property Description Values CSS

Are you still confused about how absolute positioning works in CSS and are losing elements on the screen? Let's understand this magic.

Introduction to Positioning

When you set position: absolute , it is not the element itself that comes to the fore, but its parent container, because positioning in CSS is relative to it. The difficulty is that this is not always the element's immediate parent.

Let's look at a code with four divs nested inside each other like a nesting doll.

< body >

< div class = "box-1" >

< div class = "box-2" >

< div class = "box-3" >

< div class = "box-4" > < / div >

< / div >

< / div >

< / div >

< / body >

The box-1 , box-2 and box-3 boxes are centered for beauty using the margin: auto and flex CSS properties. The box-4 block remains in its default position in the document flow.

body ( display: flex; ) .box-1, .box-2, .box-3 ( display: flex; margin: auto; )

body (

display: flex;

Box-1,

Box-2,

Box-3 (

display: flex;

Margin: auto;

All 4 elements have default positioning. At the moment the layout looks like this:


.box-4 without positioning

What are we positioning against?

To position itself, an element must know two things:

  • which parent will become the starting point;
  • the amount of displacement relative to the reference point (top, bottom, right or left).

If you define position: absolute for box-4 , that element will leave the normal flow of the document. But now it remains in its place, since the offset coordinates are not specified. If the width of an element is not defined in CSS, it will be equal to the width of its content (plus padding and border).


.box-4 with absolute positioning without offset

Now let's add the properties top: 0 and left: 0 . The element must determine which parent container will become the reference point for these coordinates. The closest element with a non-static position (most often position: relative) becomes it. box-4 begins to interrogate its ancestors one by one. Neither box-3, nor box-2, nor box-1 are suitable, since they have a default positioning in CSS (unset).

If a positioned ancestor is not found, the element is placed relative to the body of the document:


.box-4 with absolute positioning. Parent elements without positioning

If you set position: relative to the box-1 element, it becomes the reference point:


.box-4 with absolute positioning. .box-1 with relative positioning

An absolutely positioned element is positioned relative to its nearest positioned ancestor.

Once a reference point has been found, everything above it in the DOM tree ceases to matter.

If you set position: relative also for box-2 , then box-4 will be positioned relative to it, because this ancestor is closer.


.box-4 with absolute positioning. .box-2 with relative positioning

Likewise for the box-3 container:

Two main tools are often used for page layout - positioning And free movement (floating). CSS positioning lets you specify where an element's box appears, and free float moves elements to the left or right edge of the container box, allowing the rest of the content to "flow" around it.

Positioning and free movement of elements

1. Types of positioning

The position property allows you to precisely specify the new location of the block relative to where it would be in the normal flow of the document. By default, all elements are arranged sequentially one after another in the order in which they are defined in the structure of the HTML document. The property is not inherited.

position
Meaning:
static The default value means no positioning. Elements are displayed sequentially one after another in the order in which they are defined in the HTML document. Used to clear any other positioning value.
relative A relatively positioned element is moved from its normal position in different directions relative to the boundaries of its parent container, but the space it occupied does not disappear. However, such an element may overlap other content on the page.

If for a relatively positioned element you set the properties top and bottom or left and right at the same time, then in the first case only top will work, in the second - left.

Relative positioning allows you to set a z-index for an element, as well as absolutely position child elements within a block.

absolute An absolutely positioned element is completely removed from the document flow and positioned relative to the boundaries of its container block (another element or browser window). The container block for an absolutely positioned element is the closest ancestor element whose position property value is not static .

The location of the element's edges is determined using the offset properties. The space that such an element occupied collapses as if the element did not exist on the page. An absolutely positioned element can overlap or be superimposed by other elements (due to the z-index property). Any absolutely positioned element generates a block, that is, it takes on the value display: block; .

fixed Fixes an element at a specified location on the page. The container block of a fixed element is the viewport, that is, the element is always fixed relative to the browser window and does not change its position while scrolling the page. The element itself is completely removed from the main document flow and created in a new document flow.
initial Sets the property value to the default value.
inherit Inherits the property value from the parent element.

Rice. 1. Difference between static, relative and absolute positioning

2. Offset properties

Properties describe the offset relative to the nearest side of the container block. Set for elements for which the position property value is not static . They can take both positive and negative values. Not inherited.

For the top property, positive values ​​move the top edge of the positioned element below, and negative values ​​move the top edge of its container block. For the left property, positive values ​​move the edge of the positioned element to the right, and negative values ​​move the edge of the positioned element to the left. That is, positive values ​​move the element inside the container block, and negative values ​​move it outside it.

3. Positioning within an element

For the container block of an absolutely positioned element, the position: relative property is set without offsets. This allows elements to be positioned within a container element.

.wrap ( padding: 10px; height: 150px; position: relative; background: #e7e6d4; text-align: right; border: 3px dashed #645a4e; ) .white ( position: absolute; width: 200px; top: 10px; left : 10px; padding: 10px; background: #ffffff; border: 3px dashed #312a22;
Rice. 2. Absolute relative positioning

4. Positioning problems

1. If the width or height of an absolutely positioned element is set to auto , then its value will be determined by the width or height of the element's content. If the width or height is declared explicitly, then this is the value that will be assigned.
2. If inside a block with position: absolute there are elements for which the float is set, then the height of this element will be equal to the height of the tallest of these elements.
3. For an element with position: absolute or position: fixed, you cannot simultaneously set the float property, but for an element with position: relative, you can.
4. If the ancestor of the positioned element is a block element, then the block container is formed by the content area delimited by the border. If the ancestor is an inline element, the container block is formed by the outer boundary of its contents. If there is no ancestor, the container block is the body element.

5. Free movement of elements

In the normal order, block elements are rendered starting from the top edge of the browser window and working towards the bottom edge. The float property allows you to move any element, aligning it to the left or right edge of the web page or the container element that contains it. In this case, other block elements will ignore it, and inline elements will move to the right or left, freeing up space for it and flowing around it.

Rice. 3. Free movement of elements

A floating block takes on the dimensions of its contents, taking into account padding and borders. The top and bottom margins of floating elements do not collapse. The float property applies to both block elements and inline elements.

The left or right outer edge of a moved element, unlike positioned elements, cannot be located to the left (or right) of the inner edge of its container block, i.e. go beyond its boundaries. Moreover, if internal padding is specified for the container block, then the floating block will be spaced from the edge of the container block at the specified distance.

The property automatically changes the calculated (browser-displayed) value of the display property to display: block for the following values: inline , inline-block , table-row , table-row-group , table-column , table-column-group , table-cell . table-caption, table-header-group, table-footer-group. The value of inline-table changes to table .

The property has no effect on elements with display: flex and display: inline-flex .

When using the float property on block elements, be sure to specify a width. This will create space for other content in the browser. But if the combined width of all columns is greater than the available space, then the last element will go down.

At the same time, the vertical margins of floated elements do not collapse with the margins of neighboring elements, unlike ordinary block elements.

6. Cancel element wrapping

6.1. clear property

The clear property determines how the element that follows the floating element will be positioned. The property cancels the float on one or both sides of the element that is set by the float property. To prevent background or borders from being displayed under floating elements, use the (overflow: hidden;) rule.

6.2. Cleaning a stream with styles using the clearfix class and the :after pseudo-class

Suppose you have a block container for which the width and height are not specified. A floating block with specified dimensions is placed inside it.

.container ( padding: 20px; background: #e7e6d4; border: 3px dashed #645a4e; ) .floatbox ( float: left; width: 300px; height: 150px; margin-right: 20px; padding: 0 20px; background: #ffffff ; border: 3px dashed #666666; Rice. 4. “Collapse effect” of the container block

Solution to the problem:
We create the .clearfix class and, in combination with the :after pseudo-class, apply it to the container block.

.container ( padding: 20px; background: #e7e6d4; border: 3px dashed #645a4e; ) .floatbox ( float: left; width: 300px; height: 150px; margin-right: 20px; padding: 0 20px; background: #ffffff ; border: 3px dashed #666666; .clearfix:after ( content: ""; display: block; height: 0; clear: both; visibility: hidden; )

Second option for clearing the stream:

Clearfix:after ( content: ""; display: table; clear: both; )
Rice. 5. Applying the “cleaning” method to a container block containing a floating element

6.3. An easy way to clean a stream

There is another trick to clean up the flow for an element containing floating elements, such as a horizontal bulleted list:

Ul ( margin: 0; list-style: none; padding: 20px; background: #e7e6d4; overflow: auto; ) li ( float: left; width: calc(100% / 3 - 20px); height: 50px; margin- right: 20px; background: #ffffff; border: 3px dashed #666666; ) li:last-child (margin-right: 0;) Fig. 6. Cleaning up the horizontal list flow

A block element in HTML is an element that, by default, occupies the entire width of its parent element. The parent element can be another block element, or a browser window. You can set the width and height of a block element using CSS properties. Positioning block elements is the process of positioning them within the browser window and relative to them using the CSS properties position , left , top , right and bottom . The CSS position property is designed to set one of four available types of positioning: static (default), absolute, fixed and relative. The remaining CSS properties, namely left , top , right and bottom , are used to set distances relative to the left, top, right and bottom edges of the parent element. Also, when setting certain properties, block elements can overlap each other, and this feature can also be used on websites.

Default positioning (static)

If you did not specify a position for a block element or specified static , which is the same thing, then the block elements are arranged in order. Moreover, the next block (for example: red) is located on a new line. Also, this positioning is not affected by setting the distances left , top , right and bottom .

Absolute positioning (absolute)

With absolute positioning, the position of an element is specified relative to the edges of the browser window using distances specified by the left , top , right , and bottom properties. If you specify the distances left and right at the same time, and they conflict with each other, then preference is given to left , the same goes for top and bottom , in which the distance top takes precedence. Absolute positioning is very often used in conjunction with relative positioning for design purposes, when it is necessary to place various elements relative to each other; it can also be used to create drop-down menus, site layout, etc.


Fixed positioning

Fixed positioning is different from other types of positioning and does not move with the content as you scroll the page. Fixed-position block elements are anchored using the left , top , right , and bottom properties to the edges of the browser window. Fixed positioning is used to create frame interfaces (the browser window is divided into several areas), a fixed menu, a fixed site footer and “permanent” blocks (list of links, social buttons, etc.).


Relative positioning

Relative positioning is specified by specifying the distances left , top , right , and bottom relative to its current position.


However, this block position can also be created using the margin property.

Relative positioning isn't fun to use on its own, it's mostly used in conjunction with absolute positioning.

Let's consider the options: