JavaWeb_CSS(13)_定位_相对定位

定位

相对定位

  • 相对定位是一个非常容易理解的概念,如果对一个元素先对定位,可以设置其水平位置和垂直位置,这个元素相对于元素的 起点 *(没有定位的左上角原始位置)开始移动。
  • 注意:在使用相对定位的时候无论是否进行移动,元素仍然会占据原有的空间,因此移动元素可能覆盖其他元素。
示例代码
<!DOCTYPE html>
<html>

	<head>	
		<meta charset="UTF-8">
		<title> www.weiyuxuan.com </title>
	</head>
	
	<style type="text/css">
	
		body
		{
			margin: 10px;
			font-size: 12px;
			font-family: Arial;
		}
		
		.outside
		{
			width: 500px;
			height: 200px;
			background-color: #a9d6ff;
			border: 1px dashed black;
		}
		
		.inside
		{
			padding: 10px;
			background-color: #fffcd3;
			border: 1px dashed black;
			width: 100px;
			position: relative;
			
			left: 20px;
			top: 80px;					
		}
		
	</style>
	
	<h1> 定位  </h1>
	
	<hr>
	
	<body>
	
		<div class="outside">
			<div class="inside"> 相对原点的定位 </div>
		</div>
	
	</body>
	
</html>

结果图:
JavaWeb_CSS(13)_定位_相对定位

CSS 中 div 相对定位对文档流的影响

  • div1 相对定位脱离了文档流,但是后续的 div 还会认为 div1 是在没有定位之前的状态,所有后续的 div 不会填补 div1 的空缺位置,而是继续按着文档流来排序。
示例代码
<!DOCTYPE html>
<html>

	<head>	
		<meta charset="UTF-8">
		<title> www.weiyuxuan.com </title>
	</head>
	
	<style type="text/css">
	
		body
		{
			margin: 10px;
			font-size: 12px;
			font-family: Arial;
		}
		
		.outside
		{
			width: 500px;
			height: 200px;
			background-color: #a9d6ff;
			border: 1px dashed black;
		}
		
		.inside
		{
			margin:10px;
			padding: 10px;
			background-color: #fffcd3;
			border: 1px dashed black;
			position: relative;
			
			left: 100px;
			top: 220px;					
		}
		
		.inside1
		{
			margin:10px;
			padding: 10px;
			background-color: #fffcd3;
			border: 1px dashed black;			
		}
				
	</style>
	
	<h1> 定位  </h1>
	
	<hr>
	
	<body>
	
		<div class="outside">
			<div class="inside"> 相对原点的定位 div1 </div>
			<div class="inside1"> 相对原点的定位 div2 </div>
		</div>
	
	</body>
	
</html>

结果图:
JavaWeb_CSS(13)_定位_相对定位
如有错误,欢迎指正!