Implementation of positioning CSS child element relative to parent element

Time:2020-11-15

Solution

Add to parent element position:relative;
Add position:absolute; right:20px;

code

HTML structure


<div id="div1">
	<div id="div2"></div>
</div>

css


#div1{
	width:500px;height:500px;
	background-color:darkgray;
	position:relative;
}
#div2{
	width:30px;height:30px;
	background-color:red;
	position:absolute;
	right:20px;
}

effect

principle

Browser rendering HTML, there is a saying of document flow, block level element line feed rendering, line element in line rendering, here, two div are block level elements, one parent, one child. Normally, the result of rendering 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 need to use the position attribute.
Position property value

Property value describe
absolute The absolute positioning element is generated and positioned relative to the first parent element other than static positioning.
relative The relative positioning elements are generated and positioned relative to their normal positions.

We know that to use positioning relative to the parent element, absolute must be used. Why doesn’t absolute work directly? Because using absolute to locate 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, and know whether to find the element whose position is not static. Therefore, the position of the parent element needs to be set to relative Because relative is only positioned relative to the normal position. The normal position is the default output location of the so-called document flow. If we set position to relative and do not set the offset x, y, it is equivalent to that the position of the parent element does not change.

This article about the implementation of CSS child element positioning relative to parent element is introduced here. For more information about positioning content of CSS child element relative to parent element, please search previous articles of developeppaer or continue to browse the related articles below. I hope you can support developeppaer more in the future!