在下面代码中,有三个盒子,如何才能把中间的盒子移动到第三个盒子的右边
<!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>