CSS定位之相对定位

在下面代码中,有三个盒子,如何才能把中间的盒子移动到第三个盒子的右边

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>定位练习1</title>
		<style type="text/css">
			.box1{
				width: 100px;
				height: 100px;
				background-color: red;
			}
			.box2{
				width: 100px;
				height: 100px;
				background-color: yellow;
				/*
				 * 左外边距和上外边距移动
				 */
				margin-left: 100px;
				margin-top: 100px;
			}
			.box3{
				width: 100px;
				height: 100px;
				background-color: yellowgreen;
				/*上外边距移动*/
				margin-top: -100px;
			}
		</style>
	</head>
	<body>
		<!--问题:如何把box2放到box3的右边-->
		<div class="box1"></div>
		<div class="box2"></div>
		<div class="box3"></div>
	</body>
</html>
如图所示:

但是这种方法太麻烦了,我们可以采用开启相对定位的方式

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>相对定位2</title>
		<style type="text/css">
			.box1{
				width: 100px;
				height: 100px;
				background-color: red;
			}
			.box2{
				width: 100px;
				height: 100px;
				background-color: yellow;
				
				/*
				 * 当元素的position设置为relative时,则开启了元素的相对定位
				 * 1、元素开启相对定位时,如果不设置偏移量则元素位置没有变化
				 * 2、相对定位是相对于原来元素在文档流中的位置
				 * 3、相对定位的元素不会脱离文档流
				 * 4、相对定位会使元素提升一个层级
				 * 5、相对定位不会改变元素的性质,块还是块,内联还是内联
				 * */
				position: relative;
				left: 100px;
				top: 100px;
				/*
				 * 
				 * 当开启了定位时,(position属性值是一个非static时)
				 * 可以通过left、right、top、bottom四个属性来设置元素的偏移量
				 */
			}
			.box3{
				width: 100px;
				height: 100px;
				background-color: yellowgreen;
				
				
			}
		</style>
	</head>
	<body>
		<!--问题:如何把box2放到box3的右边-->
		<div class="box1"></div>
		<div class="box2"></div>
		<div class="box3"></div>
	</body>
</html>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值