CSS element location. Positioning elements

If you cut into any website created on the basis of html, then you will see a certain layered structure. Moreover, its appearance will be similar to a layer cake. If it seems like this to you, then most likely you haven’t eaten for a long time. So first satisfy your hunger, and then we will tell you how to center a div layer on your site:

Advantages of layout using a tag

There are two main types of website structure:

  • Tabular;
  • Block.

Tabular layout was dominant even at the dawn of the Internet. Its advantages include the accuracy of the specified positioning. But, nevertheless, it has obvious disadvantages. The main ones are the length of the code and low loading speed.

When using table layout, the web page will not be displayed until it is completely loaded. While when using div blocks, the elements are displayed immediately.

In addition to high loading speed, block construction of a website allows you to reduce the amount of html code several times. Including through the use of CSS classes.

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

Block construction based on tags is also called layer-by-layer, and the blocks themselves are called layers. This is because when certain property values ​​are used, they can be stacked on top of each other, similar to layers in Photoshop.

Positioning aids

In block layout, it is better to position layers using cascading style sheets. The main CSS property responsible for layout is float.
Property syntax:
float: left | right | none | inherit
Where:

  • left – align the element to the left edge of the screen. The flow around the remaining elements occurs on the right;
  • right – alignment on the right, flow around other elements – on the left;
  • none – wrapping is not allowed;
  • inherit – inherits the value of the parent element.

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

#left ( width: 200px; height: 100px; float: left; background: rgb(255,51,102); ) #right ( width: 200px; height: 100px; float: right; background: rgb(0,255,153); ) Left block Right block


Now we will try to use the same property to position the third div in the center of the page. But unfortunately float does not have a center value. And when you give a new block an alignment value to the right or left, it is shifted in the specified direction. Therefore, all that remains is to set float: left to all three blocks:


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

Centering layers

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

#container ( width: 600px; margin: 0 auto; ) #left ( width: 200px; height: 100px; float: left; background: rgb(255,51,102); ) #right ( width: 200px; height: 100px; float : left; background: rgb(0,255,153); #center ( width: 200px; height: 100px; float: left; background: rgb(255,0,0); ) Left block Center block Right block


The same example shows how you can center a div horizontally. And if you edit the above code a little, 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 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 regardless of browser window size. Here's what vertically centering a div looks like:


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

#container ( width: 450px; height:150px; margin:0 auto; background-color:#66CCFF; ) #left ( width: 100px; height: 100px; background: rgb(255,51,102); display: inline-block; vertical-align: middle; margin-left: 35px; ) #right ( width: 100px; height: 100px; background: rgb(0,255,153); display: inline-block; vertical-align: middle; margin-left: 35px; ) #center ( width: 100px; height: 100px; background: rgb(255,0,0); display: inline-block; vertical-align: middle; margin-left: 35px; )


A short description of the css properties and their values ​​that we used in this example to center a div within a div:

  • display: inline-block – aligns a block element into a line and ensures it wraps around another element;
  • vertical-align: middle – aligns the element in the middle relative to the parent;
  • margin-left – sets the left margin.
How to make a link from a layer

Strange as it may sound, this is possible. Sometimes a div block as a link may be needed when laying out various types of menus. Let's look at a practical example of implementing a link layer:

#layer1( width: 500px; height: 100px; background: rgb(51,255,204); border:groove; ) a ( display: block; text-align: center; height: 100%; color: rgb(255,0,51) ; ) Link to our website


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

Hiding and showing block elements

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

This is especially true for the main page, the cost of advertising on which is the highest. Therefore, the problem arises of where to “shove” another advertising banner. And here you can’t get away with aligning the div to the center of the page!

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

#layer1( display:block; width: 500px; height: 100px; background: rgb(51,255,204); border:groove; ) function show() ( if(layer1=="none") ( layer1="block"; ) else ( layer1="none"; ) document.getElementById("layer1").style.display=layer1 )

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


In this example, the location of the div blocks does not change in any way. This uses a simple JavaScript function that changes the value of the css display property after a button is clicked (onclick event).

display syntax:
display: block | inline | inline-block | inline-table | list-item | none | run-in | table | table-caption | table-cell | table-column-group | table-column | table-footer-group | table-header-group | table-row | table-row-group

As you can see, this property can take on many values. Therefore it is very useful and can be used to position elements. In one of the previous examples, we used one of its values ​​(inline-block ) to center a div within a div.

We used two values ​​for the display property to hide and show the layer.

They work with all positioned elements except static ones.

Positioning example.

Elements can overlap each other!

Displaying an element above the rest!

The position property has 4 values: static, fixed, relative and absolute. Each of these meanings will be demonstrated below with an example of use.

Before we examine in detail all types of positioning of elements on a page, we will have to consider what document flow is.

Document flow

By default, elements on a web page are displayed in the order in which they appear in the HTML document, that is, block elements occupy the full width available to them and are stacked vertically one below the other. Inline elements are lined up horizontally until the entire available width is occupied, after the entire width is occupied, a line break is made and everything starts again. This arrangement of elements is called normal flow (also called document flow or general flow).

You can use the float or position property to remove an element from the normal flow. If an element "falls out" of the normal flow, then elements that are located in the code below that element will be shifted into its place on the web page.

Static positioning

Static is the default positioning for all elements on a web page. If you don't apply the position property to an element, it will be static and will appear on the web page according to the general flow of elements.

When applying the CSS properties top , left , right or bottom to a statically positioned element, they will be ignored.

If necessary, you can set static positioning in the style sheet using the static value:

Document title p ( position: static; )

First paragraph.

Second paragraph.

Try »

Elements with fixed positioning are located on the page relative to the browser window. Such elements are removed from the general flow; elements following the fixed element in the flow will ignore it, moving and taking its place on the web page.

It is worth paying attention to the fact that elements with fixed positioning can overlap other elements, hiding them completely or partially. When scrolling through long pages, they create the effect of motionless objects remaining in the same place:

Document title img ( position: fixed; top: 5%; left: 40% ) Text Text Text Text Text Text Text Some text Text Text Text Text Text Try »

Relative positioning

Elements with relative positioning, like static elements, remain in the general flow. When applying the top , left , right , or bottom properties to relatively positioned elements, they will move relative to their location, leaving empty space where the element was originally located.

Such elements do not affect the position of the elements surrounding them; the remaining elements remain in place and can be overlapped by a relatively positioned element:

Document title h2 ( position: relative; top: 30px; ) First level heading.

Relatively positioned title.

Third level heading.

Try »

Note: Elements with relative positioning (relative) are usually used as a parent for elements with absolute positioning (absolute).

Absolute positioning

Absolutely positioned elements are completely removed from the overall flow, the remaining elements will take up the free space, completely ignoring absolutely positioned elements. You can then position the element wherever you want on the web page using the top , left , right , or bottom properties.
All absolutely positioned elements are placed relative to the browser window or relative to the nearest positioned ancestor (if there is one) that has a position property of absolute , fixed , or relative .

Second paragraph.

Document title img ( position: absolute; right: 0px; top: 0px; )

When elements are outside the overall flow of the page, they can overlap each other. Typically, the order of elements corresponds to their order in the HTML code of the page, however, it is possible to control the order of overlap using the CSS property z-index , the higher its value, the higher the element will be.

Document title div ( position: absolute; width: 100px; height: 100px; ) .div1 ( background-color: #66FFFF; left: 70px; top: 0px; z-index: 1; ) .div2 ( background-color: # FFFF66; left: 0px; z-index: 0; .div3 ( background-color: #66FF66; left: 33px; z-index: 2; )

z-index: 0;

z-index: 2;

As you probably already know, you can layout a website using tables, in which case the page is divided into cells. You can also use blocks for these purposes when a website page consists of individual elements.

I will probably not be mistaken if I say that a serious problem for many novice webmasters is the task of placing blocks in a given place on a web page.

One of the main difficulties when layout using blocks is the positioning (alignment) of these same blocks.

A little about layers

I think many of you have heard about such a thing as a layer. And, as a rule, a layer is understood as a block specified by the tag. In fact, everything is a little different.

There are no layers in HTML. It's just a metaphor. When we talk about layers, they mean a certain html container (element) that can be placed in a certain place on a web page.

    The second misconception is that only the block specified by the tag is classified as a layer. This is also not true. These may also include paragraphs (

    ), lists (

    ) and other elements.

    And now about ah.

    As mentioned above, you can set the location of any HTML element. There is no need to always use the tag for this. Also, the use of this tag does not obligate you to give it any position on the web page.

    The meaning of using a block specified by a tag comes down to enlargement. After all, you can place other elements inside it (paragraphs, pictures, etc.). This creates a large block with varied content, which is much easier to position on a web page than each element separately.

    Positioning of elements.
    There are four main types of positioning:
    1. Static
    2. Absolute

    3. Fixed

    Used as the default location. In this case, the browser views the HTML code, divides it into elements and composes a page from them. The result is a sequence of a number of elements. They are displayed in the order in which they are indicated in the html code.

    Applying the left, top, right and bottom parameters does not produce any results.

    Static positioning must be kept in mind when relative positioning is used.

    Absolute

    Using absolute positioning, the coordinates of the upper left corner of the block are specified. In this case, the coordinates are counted relative to the location of the parent element. If the parent element is a browser window, then the block is aligned relative to it. If there is another element within which the block is located, then the alignment occurs relative to this element.

    Fixed

    Already from the name it becomes clear that in this case the element is fixed. It is located in a specific place on the web page and does not move anywhere. This alignment is often used for pop-ups, where they are centered and do not move as you scroll the page.

    Relative

    This type of positioning can be difficult. Its name is not entirely apt. Many people confuse relative and absolute positioning of elements. It may appear that the alignment is relative to the parent element. And in the case of absolute positioning - relative to the browser window. But that's not true.

    It is necessary to understand that the location of the element in this case occurs relative to its place in a static position. This is what was mentioned above.

    Simply put, you tell the browser to move an element so many pixels relative to where it is located by default.

    There is another difficult point. What happens if the parent element has relative positioning, but the nested element has absolute positioning? In this case, the coordinates of the child element will be counted relative to the parent element, taking into account its offset, if any.

    Summarize.

    So, there is a position property. This property can take 4 values ​​Static, Absolute, Fixed and Relative. The default is Static.

    When you specify coordinates for an element, you must also tell the browser how it should calculate those coordinates. We need to give him a starting point.

    Do not forget that if the position property is absent, the coordinates will not be taken into account, the block will remain in the same place, in its static position.


    Now let's see how the coordinates are set.

    For these purposes, four types of properties are used:

    1. Top
    2.Left
    3. Right
    4. Bottom

    Top - a positive value (for example, 20px) moves the block 20 pixels down. A negative value (-20px) moves the element 20 pixels up. All this happens relative to the upper left corner.

    Left - shift to the left or right, depending on the sign. Relative to the upper left corner.

    Right - shift to the right and left, depending on the sign. Relative to the top right corner.

    Bottom - shift up or down, depending on the sign. Occurs relative to the lower left corner.

    Here's the HTML code:





    And this is the CSS:

    #1 {
    position:relative;
    top:100px;
    left:100px;
    width:500px;
    height:500px;
    background-color:#CCCCCC;
    }

    #11 {
    background-color:#003399;
    position:absolute;
    bottom: -30px;
    right: -50px;
    width:100px;
    height:100px;
    }

    #2 {
    background-color:#990066;
    width:200px;
    height:300px
    }

    Practice.

    While I was writing I figured it out myself.

    Imagine that a web developer doesn't have to think at all about what the finished page will look like visually. He simply writes the code, the elements themselves line up on the page, from top to bottom (block) and from left to right (inline). The higher up in the document the code is written, the higher it will appear on the page.

    In general, we will see the natural behavior of the elements, and the order in which they are displayed on the page - the flow of the document. But we are not at all happy with this order; we want to place the logo in the upper left corner, and the button a little to the right. We need complete control over all elements, we decide where and what will be located. And for this you need a tool (property) that changes the normal behavior of elements in the flow. What kind of property is this?

    In CSS styles this is called positioning, which can be static, relative, or absolute.

    Relative Positioning in CSS

    With relative positioning, the block moves relative to its original position. However, having written to the block:

    Position: relative;

    nothing will happen, it will remain in place. And the block is moved by a coordinate system (top, bottom, left, right), with both positive and negative values.

    How it works?

    Inside the yellow block with the block-yellow class is a red block with the block-relative class. In a normal flow, the red block overlaps the yellow one, since it is written last in the code.

    starting position
    relative position

    We need to move the red block down 10 pixels. This can only be done by forcibly changing the position of the red block. This is how we write top: 10px , but we need to indicate where these 10 pixels are to be counted from?

    By writing position: relative , we make it clear that we are counting relative to its current position.

    Block-yellow (
    background-color: #ffe70f;
    }

    Block-relative (
    position: relative;
    top: 10px;
    background-color: #ed5b77;
    }

    In the picture we see how the red block has moved down, 10 pixels down from its original position.

    If you remove position: relative from the code, the block will remain in place. And if instead of relative we write absolute , then by default these 10 pixels will be counted from the edge of the browser window and, as a result, our block will, on the contrary, rise up, reaching the bottom edge of the browser. And this was not part of our plans.

    Absolute Positioning in CSS

    In the picture, the block is positioned absolutely, this is when the coordinate system is measured from the edge of the browser. By replacing just one word, we have changed the position of the block.

    Position: absolute;

    There is one peculiarity. Absolute positioning also affects inline elements. If you set position: absolute to an inline element, it will behave like a block element. This is an analogue of the property - display: block.

    That's not all, the "absolute" element located inside the "relative" parent changes its coordinate reference point and begins to be positioned away from the parent.


    position: relative

    position: absolute;

    A block with class block-absolute is located inside the parent block-yellow .

    Block-yellow (
    position: relative;
    padding: 10px;
    background-color: #ffe70f;
    }

    Since the yellow block has relative positioning, the red block with absolute positioning is shifted relative to the red one by the specified pixels.

    Block-absolute (
    position: absolute;
    bottom: 10px;
    left: 10px;
    background-color: #ed5b77;
    }

    Fixed positioning

    When scrolling the page, a block with position: fixed will remain in place, usually this method is used to fix the navigation bar.

    z-index

    Resolves the order of overlapping "absolute" blocks. We want the red block to be on top of the yellow block, then we specify z-index: 2 for red and z-index: 1 for yellow.

    Red
    Yellow

    Block-red (
    position: relative;
    z-index: 2;
    background-color: #ffe70f;
    }

    Block-yellow (
    position: absolute;
    top: 20px;
    z-index: 1;
    background-color: #ed5b77;
    }

    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 limited 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 normal order, block elements are rendered starting from the top edge of the browser window and working toward 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 flow around elements 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