How to position the css child element relative to the parent element?

In css, you can use the position attribute to achieve the relative positioning of the child element relative to the parent element by setting the relative positioning "position: relative;" style for the parent element and the absolute positioning "position: absolute;" style for the child element.



The operating environment of this tutorial: windows7 system, css2 version, this method is suitable for all brand computers.

Related recommendations: "Programming Video Course" How

to realize the positioning of the child element relative to the parent element in css

Parent element style setting:

1

position:relative;

child element style:

1

position:absolute;

sample code:

html structure

1

2

3
 




 



css

1

2

3

4

5

6

7

8

9

10

11

#div1{ width:500px;height:500px; background-color:darkgray; position:relative; } #div2{ width:30px;height:30px; background-color:red ; position:absolute; right:20px; } Effect Principle The browser renders html, it is said that there is a document flow, block-level elements are rendered in line and inline elements are rendered in-line, here, two divs are block-level elements, one parent , A child, the normal rendering result is that the parent element is in the upper left corner of the browser, and the child element is in the upper left corner of the parent element. If we want to position the child element relative to the parent element, we must use the position attribute. Position attribute value Attribute value description absolute Generates absolutely positioned element, which is positioned relative to the first parent element other than static positioning. relative generates a relatively positioned element, which is positioned relative to its normal position.




































We know that if you want to use positioning relative to the parent element, you must use absolute. Why doesn't using absolute directly work? Because absolute is positioned relative to the parent element, there is a requirement for the parent element, that is, the position of the parent element cannot be static. If the position of the parent element is static, then continue to look up the element, knowing whether to find the element whose position is not static. This element is relatively positioned, so you need to set the position of the parent element to relative. This has no effect, because relative is only positioned relative to the normal position. The normal position is the so-called default output position of the document flow. If we Setting the position to relative without setting the offset x, y is equivalent to the position of the parent element unchanged.

1606983358693844.jpg

Guess you like

Origin blog.csdn.net/ld17822307870/article/details/112798419
Recommended