首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将div样式化为响应式正方形?

如何将div样式化为响应式正方形?
EN

Stack Overflow用户
提问于 2013-09-28 22:37:03
回答 4查看 311K关注 0票数 211

我想让我的div调整它的高度,使其始终等于宽度。宽度是有意义的。当父对象的宽度减小时,长方体应该通过保持其纵横比来减小。

CSS是怎么做的?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-09-28 23:28:49

几乎可以在所有浏览器上运行。

您可以尝试以百分比形式给出padding-bottom

代码语言:javascript
复制
<div style="height:0;width:20%;padding-bottom:20%;background-color:red">
<div>
Content goes here
</div>
</div>

外部div是一个正方形,内部div包含内容。这个解决方案多次对我起作用。

这是一个jsfiddle

票数 220
EN

Stack Overflow用户

发布于 2015-03-11 19:29:33

HTML

代码语言:javascript
复制
<div class='square-box'>
    <div class='square-content'>
        <h3>test</h3>
    </div>
</div>

CSS

代码语言:javascript
复制
.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/

票数 66
EN

Stack Overflow用户

发布于 2015-02-02 19:31:18

另一种方法是将透明的1x1.png与width: 100%height: autodiv中的绝对定位内容一起使用:

html:

代码语言:javascript
复制
<div>
    <img src="1x1px.png">
    <h1>FOO</h1>
</div>

css:

代码语言:javascript
复制
div {
    position: relative;
    width: 50%;
}

img {
    width: 100%;
    height: auto;
}

h1 {
    position: absolute;
    top: 10px;
    left: 10px;
}

空闲:http://jsfiddle.net/t529bjwc/

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19068070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档