如何布局3个div,使得一个在div旁边,另一个在下面?

时间:2016-11-08 04:52:42

标签: html css

假设有3个矩形{1,2,3} 我想要矩形1在左边,矩形2在矩形1下面,矩形3在矩形1旁边。

.rect1{
   width: 20px;
   height: 20px;
   float: left;
}
.rect2{
   width: 20px;
   height: 20px;
}
.rect3{
   width: 40px;
   height: 40px;
   float: left;
}

<div class="rect1"></div>
<div class="rect2"></div>
<div class="rect3"></div>

我尝试过这种方法,但矩形3浮动在矩形2旁边,而不是矩形1。

4 个答案:

答案 0 :(得分:2)

你可以通过包裹.rect1&amp; .rect2 div在一个div中,float:left固定宽度。

.rect-left{
  float:left;
  width: 20px;
}
.rect1{
   width: 20px;
   height: 20px;
   float: left;
   background:red;
}
.rect2{
   width: 20px;
   height: 20px;
   background:blue;
   float: left;
}
.rect3{
   width: 40px;
   height: 40px;
   float: left;
   background:green;
}
<div class="rect-left">
  <div class="rect1">
  </div>
  <div class="rect2">
  </div>
</div>
<div class="rect3">
</div>

答案 1 :(得分:1)

让我们检查一下我的代码

<!DOCTYPE html>
<html>
<head>
<style>
body {
    background-color: lightblue;
}
.rect1{
   width: 20px;
   height: 20px;
   float: none;
   border:1px solid black;
}
.rect2{
   width: 20px;
   height: 20px;
   border:1px solid white;
   float:left;
}
.rect3{
   width: 40px;
   height: 40px;
   float: left;
   border:1px solid red;
   margin-top: -22px;
}
</style>
</head>
<body>

<div class="rect1"></div>
<div class="rect2"></div>
<div class="rect3"></div>

</body>
</html>

答案 2 :(得分:0)

您可以尝试将.rect1.rect2包装在一起,如下例所示:http://codepen.io/rebagliatte/pen/ObVgdX

答案 3 :(得分:0)

你可以不使用浮动来做到这一点。只需为要对齐的div提供左边距和上边距:

 .rect1{
 width: 20px;
 height: 20px;
 background-color:Red;
}
.rect2{
width: 20px;
height: 20px;
background-color:black;
}
.rect3{
 width: 20px;
 height: 20px;
 margin-left: 20px;
 margin-top: -40px;
 background-color:blue;
}