各位技术大牛,我像请问一下,有没有一种方法(除了position,float)可以将任意不同大小div放在一等同于任意大小div之和的盒子当中(类似于七巧板)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
* {
margin: 0px;
padding: 0px;
}
#box {
height: 300px;
width: 700px;
border: 1px solid red;
display: flex;
flex-wrap: wrap;
align-content: stretch;
}
#div1{
width: 200px;
height: 170px;
background-color: aquamarine;
}
#div2{
width: 200px;
height: 110px;
background-color: bisque;
}
#div3{
width: 300px;
height: 300px;
background-color: cadetblue;
}
#div4{
margin-top: -130px;
width: 200px;
height: 130px;
background-color: coral;
}
#div5{
margin-top: -190px;
width: 200px;
height: 190px;
background-color: cornflowerblue;
}
</style>
<title>弹性盒子</title>
</head>
<body>
<div id="box">
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>
<div id="div5">5</div>
</div>
</body>
</html>
以上是我的代码但是需要设置margin才可以实现
参考GPT和自己的思路:
您好!针对您的问题,可以使用CSS Grid布局来实现将任意不同大小的div放在一个等同于任意大小div之和的盒子中,而不使用position和float。
具体做法是,在父元素(这里是id为box的div)中设置display:grid,然后使用grid-template-columns属性来定义每列的宽度。使用grid-template-rows属性则可以定义每行的高度。
例如,如果要将div1、div2、div4放在第一行,div3、div5放在第二行,并且第一行的总高度等于第二行的高度,可以这样写:
#box {
height: 300px;
width: 700px;
border: 1px solid red;
display: grid;
grid-template-columns: 250px 250px 200px;
grid-template-rows: 150px 150px;
}
#div1{
background-color: aquamarine;
}
#div2{
background-color: bisque;
}
#div3{
background-color: cadetblue;
grid-row: 2 / 3; /*指定该div占用第二行*/
}
#div4{
background-color: coral;
}
#div5{
background-color: cornflowerblue;
grid-row: 2 / 3; /*指定该div占用第二行*/
}
其中,grid-row属性用于指定该div在哪一行显示。上述代码使用了grid-template-columns属性,将第一列和第二列的宽度都设置为250px,第三列宽度设置为200px。使用grid-template-rows属性,将第一行的高度设置为150px,第二行的高度也设置为150px。
这样就可以实现将任意不同大小div放在一个等同于任意大小div之和的盒子中了。具体实现可以根据实际需求自行调整。希望这个解决方案对您有所帮助!