【问题标题】:create a square div with the option to make it taller创建一个方形 div 并选择使其更高
【发布时间】:2015-02-15 18:32:59
【问题描述】:
我正在使用 this method 创建响应式方块。
如果文本适合我希望 div 保持他的纵横比为 1:1 但如果文本更长我希望 div 高度扩大。这可能吗?
.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;
}
.square-content div {
display: table;
width: 100%;
height: 100%;
}
.square-content span {
display: table-cell;
text-align: center;
vertical-align: middle;
color: white
}
<div class='square-box'>
<div class='square-content'>
<div>
<span>Aspect ratio 1:1</span>
</div>
</div>
</div>
【问题讨论】:
标签:
css
responsive-design
【解决方案1】:
这是一个简单的 div 来显示高度响应的 div
.square {
background: #000;
width: 50vw;
}
.square h1 {
color: #fff;
}
<div class="square">
<h1>This is a Square</h1>
</div>
【解决方案2】:
我使用 jQuery 让它工作。它运行一个间隔,检查盒子大小是否等于内容的max-width。如果为 true,它将调整框的大小,如果为 false,则将其更改为 50% 高度。
我更改了以下 css 属性:
.square-content div {
display: table;
height: 100%;
max-width:500px;
margin:0 auto;
}
jQuery:
function change () {
if ($(".square-box").width() <= 500) {
$(".square-box").css("height", "800px");
} else {
$(".square-box").css("height", "50%");
}
}
setInterval(change, 100);
这里更容易理解:
http://jsfiddle.net/v5f8hwzo/
【解决方案3】:
而不是使用padding-top:100% - 使用视口单位。
所以如果盒子宽度是视口宽度的 50%,我们可以简单地将盒子的尺寸设置为 width: 50vw 和 min-height: 50vw
设置min-height: 50vw 确保当文本没有填满框 - 它保持1:1 的正方形纵横比,但如果文本填满了框 - 框会根据文本的长度增长。
.square-box {
position: relative;
background: #4679BD;
width: 50vw;
margin-bottom: 20px;
}
.square-content {
color: white;
padding: 10px;
width: 50vw;
min-height: 50vw;
box-sizing: border-box;
display: flex;
align-content: center;
/* vertically center text */
}
.square-content span {
color: white
}
<div class='square-box'>
<div class='square-content'>
<div><span>Not much text</span>
</div>
</div>
</div>
<div class='square-box'>
<div class='square-content'>
<div><span>Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text </span>
</div>
</div>
</div>