使用div作为装饰方块,使用img html元素作为图像,并将它们都放置在容器中是什么?
这是正方形的CSS:
.square {
width: 80%;
height: 80%;
margin-left: auto;
margin-right: auto;
margin-top: 10%;
background-color: red;
z-index: -1;
}
图片的CSS:
.shirtImage {
width: 100%;
margin-left: auto;
margin-right: auto;
}
容器只是一个div。
答案 0 :(得分:1)
您需要使用伪值,以便div成为父级,然后从此处使用垂直填充或边距将div拉伸为正方形。可以将图片放置在绝对位置,以避免修改div的高度。
https://developer.mozilla.org/en-US/docs/Web/CSS/padding
<percentage>
相对于包含块的宽度,以百分比为单位的填充大小。
可能的例子
.square {
width: 80%;
height: 80%;
margin-left: auto;
margin-right: auto;
margin-top: 10%;
background-color: red;
z-index: -1;
position: relative;
overflow: hidden;
}
.square:before {
content: '';
display: block;
padding-top: 100%;/* equals width of parent */
}
.shirtImage {
width: 95%;/* 95 instead 100 for the demo*/
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom:0;
right:0;
}
<div class="square">
<img class="shirtImage" src="http://dummyimage.com/100/fe0">
</div>