在下面代碼中,有三個盒子,如何才能把中間的盒子移動到第三個盒子的右邊
<!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>