【CSS】Positioning ⑤ (Absolute positioning of child elements and relative positioning of parent elements | Code example)





1. Absolute positioning of child elements and relative positioning of parent elements



Absolute positioning should be used with a parent container with positioning;

The child element uses absolute positioning, and the parent element uses relative positioning;


Child elements use absolute positioning and do not retain their position in the layout.

Child elements are completely dependent on the position of the parent container,

At this time, the parent container is required to be stable. If the parent container uses an absolute layout, the parent container will not retain its position.

The child element depends on the parent element. At this time, the parent element is recommended to use relative positioning, which can ensure the stability of the page;


The parent element needs a placeholder and must use relative positioning;

Child elements need to be placed arbitrarily, and absolute positioning must be used;





2. Code example



The parent element uses relative positioning, and the child element uses absolute positioning;

The two child elements are placed in the left and right center respectively;


Code example:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>绝对定位示例</title>
	<style>
		/* 父元素设置相对布局 */
		.father {
      
      
			position: relative;
			width: 800px;
			height: 90px;
			background-color: pink;
		}

		/* 子元素设置绝对布局 */
		.son {
      
      
			/* 绝对布局 */
			position: absolute;
			/* 放置在左侧中心位置 */
			top: 25px;
			left: 0;

			width: 40px;
			height: 40px;
			background-color: blue;
		}

		/* 子元素设置绝对布局 */
		.son2 {
      
      
			/* 绝对布局 */
			position: absolute;
			/* 放置在右侧中心位置 */
			top: 25px;
			right: 0;

			width: 40px;
			height: 40px;
			background-color: red;
		}
	</style>
</head>
<body>
	<div class="father">
		<div class="son"></div>
		<div class="son2"></div>
	</div>
</body>
</html>

Display of results :
insert image description here

Guess you like

Origin blog.csdn.net/han1202012/article/details/130092375