如何通过父元素使这些sequares响应?
<svg style="width: 100px; height: 100px;" id="square">
<g>
<rect height="50" width="50" y="0" x="0" stroke-width="2" stroke="gray" fill="#B0b0b0"/>
<rect height="50" width="50" y="50" x="50" stroke-width="2" stroke="gray" fill="#B0b0b0"/>
<rect height="50" width="50" y="0" x="50" stroke-width="2" stroke="gray" fill="#B0b0b0"/>
<rect height="50" width="50" y="50" x="0" stroke-width="2" stroke="gray" fill="#B0b0b0"/>
</g>
</svg>
答案 0 :(得分:1)
您必须使用viewBox来"0 0 100 100"
。
解决方法:
<div style="width: 400px; height: 400px;border:1px solid red;">
<svg id="square" viewBox="0 0 100 100">
<g>
<rect height="50" width="50" y="0" x="0" stroke-width="2" stroke="gray" fill="#B0b0b0"/>
<rect height="50" width="50" y="50" x="50" stroke-width="2" stroke="gray" fill="#B0b0b0"/>
<rect height="50" width="50" y="0" x="50" stroke-width="2" stroke="gray" fill="#B0b0b0"/>
<rect height="50" width="50" y="50" x="0" stroke-width="2" stroke="gray" fill="#B0b0b0"/>
</g>
</svg>
</div>
答案 1 :(得分:0)
您可以使用CSS和背景实现相同的功能,然后轻松更改大小:
.box {
width:100px;
height:100px;
display:inline-block;
background:
linear-gradient(gray,gray),
linear-gradient(gray,gray),
#B0b0b0;
background-size:100% 2px,2px 100%;
background-position:center;
background-repeat:no-repeat;
border:1px solid gray;
}
<div class="box">
</div>
<div class="box" style="width:200px;height:200px;">
</div>
使用SVG,您可以考虑百分比值:
rect {
width: 50%;
height: 50%;
}
<svg style="width: 100px; height: 100px;" id="square">
<g>
<rect y="0" x="0" stroke-width="2" stroke="gray" fill="#B0b0b0"/>
<rect y="50%" x="50%" stroke-width="2" stroke="gray" fill="#B0b0b0"/>
<rect y="0" x="50%" stroke-width="2" stroke="gray" fill="#B0b0b0"/>
<rect y="50%" x="0" stroke-width="2" stroke="gray" fill="#B0b0b0"/>
</g>
</svg>
<svg style="width: 200px; height: 200px;" id="square">
<g>
<rect y="0" x="0" stroke-width="2" stroke="gray" fill="#B0b0b0"/>
<rect y="50%" x="50%" stroke-width="2" stroke="gray" fill="#B0b0b0"/>
<rect y="0" x="50%" stroke-width="2" stroke="gray" fill="#B0b0b0"/>
<rect y="50%" x="0" stroke-width="2" stroke="gray" fill="#B0b0b0"/>
</g>
</svg>
答案 2 :(得分:-2)
如果您想创建响应式元素,则有一个很好的技巧。您可以使用padding-top:100%;
使它适应所需的任何比例,从而获得1:1的比例。
.ratio{
width: 50%;
position: relative;
border: 2px solid #ff0000;
}
.ratio:before{
content: '\0020';
display: block;
padding-top: 100%;
}
.box{
border: 1px solid green;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
<div class="ratio">
<div class="box"></div>
</div>