css - 如何设计div作为响应方块?
这个问题在这里已有答案:
使用CSS保持div的宽高比 21个答案
我希望我的div能够调整其高度以始终等于其宽度。 宽度是百分比。 当父级的宽度减小时,框应该通过保持其宽高比来减少。
怎么做是CSS?
6个解决方案
162 votes
适用于几乎所有浏览器。
您可以尝试以百分比形式给出padding-bottom。
Content goes here
外部div正在制作正方形,而内部div包含内容。 这个解决方案很多次对我有用。
这是一个jsfiddle
rahulbehl answered 2019-05-09T07:39:56Z
151 votes
要实现您的目标,您可以使用视口百分比长度vw。
这是我在jsfiddle上做的一个简单例子。
HTML:
This is a Square
CSS:
.square {
background: #000;
width: 50vw;
height: 50vw;
}
.square h1 {
color: #fff;
}
我相信还有很多其他方法可以做到这一点,但这种方式对我来说似乎是最好的。
Daniel Burkhart answered 2019-05-09T07:39:12Z
40 votes
HTML
test
CSS
.square-box{
position: relative;
width: 50%;
overflow: hidden;
background: #4679BD;
}
.square-box:before{
content: "";
display: block;
padding-top: 100%;
}
.square-content{
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
color: white;
text-align: center;
}
[http://jsfiddle.net/38Tnx/1425/]
gidzior answered 2019-05-09T07:40:24Z
30 votes
它就像指定填充底部一样容易,宽度与百分比相同。 因此,如果宽度为50%,请使用下面的示例
id or class{
width: 50%;
padding-bottom: 50%;
}
这是一个jsfiddle [http://jsfiddle.net/kJL3u/2/]
带有响应文本的编辑版本:[http://jsfiddle.net/kJL3u/394]
Chipe answered 2019-05-09T07:41:02Z
5 votes
另一种方法是在div中使用透明的1x1.png和width: 100%,23982400289833985,并在其中使用绝对定位的内容:
HTML:
FOO
CSS:
div {
position: relative;
width: 50%;
}
img {
width: 100%;
height: auto;
}
h1 {
position: absolute;
top: 10px;
left: 10px;
}
Fidle:[http://jsfiddle.net/t529bjwc/]
gskalinskii answered 2019-05-09T07:41:39Z
2 votes
这就是我提出的。 这是一个小提琴。
首先,我需要三个包装元素,用于方形和居中文本。
sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat
volutpat.
这是样式表。 它使用两种技术,一种用于方形,一种用于居中文本。
body > div {
position:relative;
height:0;
width:50%; padding-bottom:50%;
}
body > div > div {
position:absolute; top:0;
height:100%; width:100%;
display:table;
border:1px solid #000;
margin:1em;
}
body > div > div > div{
display:table-cell;
vertical-align:middle; text-align:center;
padding:1em;
}
danijar answered 2019-05-09T07:42:18Z