CSS盒子左右移动
在网页布局中,经常需要让盒子(即元素)左右移动。CSS提供了几种方式可以实现这一效果。
使用float属性
float属性可以实现将元素向左或向右移动,并让其它元素环绕在其周围。
.left {
float: left;
/*向左移动*/
width: 100px;
height: 100px;
background-color: red;
}
.right {
float: right;
/*向右移动*/
width: 100px;
height: 100px;
background-color: blue;
}
使用position属性
position属性可以实现绝对或相对定位,从而使元素左右移动。
.box {
position: absolute;
/*绝对定位*/
left: 100px;
/*向左移动*/
top: 100px;
width: 100px;
height: 100px;
background-color: green;
}
.box2 {
position: relative;
/*相对定位*/
left: 100px;
/*向右移动*/
top: 100px;
width: 100px;
height: 100px;
background-color: yellow;
}
使用transform属性
transform属性可以实现元素的平移、旋转、缩放等效果,其中平移即为元素的左右移动。
.box3 {
transform: translateX(-100px);
/*向左移动*/
width: 100px;
height: 100px;
background-color: orange;
}
.box4 {
transform: translateX(100px);
/*向右移动*/
width: 100px;
height: 100px;
background-color: purple;
}

