flex布局把div放右边
时间: 2023-07-05 12:32:11 浏览: 79
可以使用 flex 布局的 justify-content 和 align-items 属性来实现将一个 div 元素放置在另一个 div 元素的右侧。
首先,将两个 div 元素的外层容器设置为 flex 布局:
```
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
<style>
.container {
display: flex;
}
</style>
```
然后,通过设置 justify-content 属性为 flex-start 或者 flex-end,可以控制子元素的排列方向。如果设置为 flex-start,子元素将从左边开始排列;如果设置为 flex-end,子元素将从右边开始排列。
```
<style>
.container {
display: flex;
justify-content: space-between;
}
.left {
width: 50%;
height: 50px;
background-color: red;
}
.right {
width: 50%;
height: 50px;
background-color: blue;
}
</style>
```
在上面的示例中,我们将 justify-content 属性设置为 space-between,这样左右两个元素之间会有一定的间距。如果想要两个元素之间没有间隔,可以将 justify-content 属性设置为 flex-start。
同时,可以通过设置 align-items 属性来控制子元素的垂直对齐方式。如果设置为 center,子元素将垂直居中对齐;如果设置为 flex-start,子元素将垂直对齐容器的顶部;如果设置为 flex-end,子元素将垂直对齐容器的底部。
```
<style>
.container {
display: flex;
justify-content: space-between;
align-items: center;
}
.left {
width: 50%;
height: 50px;
background-color: red;
}
.right {
width: 50%;
height: 50px;
background-color: blue;
}
</style>
```
在上面的示例中,我们将 align-items 属性设置为 center,这样左右两个元素会垂直居中对齐。