我正在尝试创建一个背景图像,该图像会随着划分的大小而缩放。我正在使用的图像需要以3X3网格布局,拐角尺寸固定不变,而其他部分则扩展以适合该分区。
但是,当我尝试放置图像时,它们都保持垂直堆叠,而不是相对于它们所在的分区。
测试图案的边角应为蓝色,边缘应为红色,中间应为橙色。
body {
background-color:black
}
#test > #Background_UL {
background-color: powderblue;
background-size: 40px 40px;
height: 40px;
width: 40px;
position: relative;
}
#test > #Background_ML {
background-color: red;
background-size: 100% 100%;
height: calc(100% - 80px);
width: 40px;
position: relative;
}
#test > #Background_LL {
background-color: powderblue;
background-size: 40px 40px;
height: 40px;
width: 40px;
position: relative;
}
#test > #Background_UM {
background-color: red;
background-size: 100% 100%;
height: 40px;
width: calc(100% - 80px);
top: 0;
position: relative;
left: 40px;
}
#test > #Background_MM {
background-color: orange;
background-size: 100% 100%;
height: calc(100% - 80px);
width: calc(100% - 80px);
top: 40px;
position: relative;
left: 40px;
}
#test > #Background_LM {
background-color: red;
background-size: 100% 100%;
height: 40px;
width: calc(100% - 80px);
bottom: 0;
position: relative;
left: 40px;
}
#test > #Background_UR {
background-color: powderblue;
background-size: 40px 40px;
height: 40px;
width: 40px;
position: relative;
right: 40px;
}
#test > #Background_MR {
background-color: red;
background-size: 100% 100%;
height: calc(100% - 80px);
width: 40px;
position: relative;
right: 40px;
}
#test > #Background_LR {
background-color: powderblue;
background-size: 40px 40px;
height: 40px;
width: 40px;
position: relative;
right: 40px;
}
<div id="test" style="width:400px;height:400px;">
<div id="Background_UL"></div>
<div id="Background_ML"></div>
<div id="Background_LL"></div>
<div id="Background_UM"></div>
<div id="Background_MM"></div>
<div id="Background_LM"></div>
<div id="Background_UR"></div>
<div id="Background_MR"></div>
<div id="Background_LR"></div>
</div>
您可以通过在容器上使用display: grid;
并指定grid-template-columns
和grid-template-columns
来轻松实现此目标,所需的代码更少。您还需要重新组织div,以便从左到右移动然后向下倾斜。请参阅我为您制作的此示例:
body {
background-color:black
}
#test > #Background_UL {
background-color: powderblue;
}
#test > #Background_ML {
background-color: red;
}
#test > #Background_LL {
background-color: powderblue;
}
#test > #Background_UM {
background-color: red;
}
#test > #Background_MM {
background-color: orange;
}
#test > #Background_LM {
background-color: red;
}
#test > #Background_UR {
background-color: powderblue;
}
#test > #Background_MR {
background-color: red;
}
#test > #Background_LR {
background-color: powderblue;
}
#test {
display: grid;
grid-template-columns: 40px auto 40px;
grid-template-rows: 40px auto 40px;
}
<div id="test" style="width:400px;height:400px;">
<div id="Background_UL"></div>
<div id="Background_UM"></div>
<div id="Background_UR"></div>
<div id="Background_ML"></div>
<div id="Background_MM"></div>
<div id="Background_MR"></div>
<div id="Background_LL"></div>
<div id="Background_LM"></div>
<div id="Background_LR"></div>
</div>