html怎么用div做正方形盒子,css - 如何设计div作为响应方块?

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:

1x1px.png

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

这就是我提出的。 这是一个小提琴。

首先,我需要三个包装元素,用于方形和居中文本。

Lorem ipsum dolor sit amet, consectetuer adipiscing elit,

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值