我有100*100px
的方块,有一个可以调整大小的容器块。我想调整内部块的大小,因此它总是在父级内部而不会溢出并且总是方形(要动态调整大小)
注意:我想保持内部div
#child {
height: 100px;
width: 100px;
background-color: red;
}
#par {
height: 200px;
width: 200px;
border: 2px solid black;
}

<div id="par">
<div id="child">
</div>
</div>
&#13;
答案 0 :(得分:2)
如果您希望元素为正方形(比例为1:1),则只需添加padding-bottom: 100%
即可。如果您希望该正方形具有内容,则该正方形的内部内容必须位于absolutely
。
body { width: 200px; }
.square {
padding-bottom: 100%; /* 1:1 aspect ratio (square) */
border:1px solid red;
position: relative;
}
&#13;
<div class="square"></div>
&#13;
您可以将方块放在容器/父容器中,但是您没有说溢出应该如何表现?
.parent {
height: 200px;
width: 80%;
border: 1px dashed black;
}
.square {
padding-bottom: 100%; /* 1:1 aspect ratio (square) */
border:1px solid red;
position: relative;
}
.square .inner {
position: absolute;
top: 0; left: 0;
width: 100%;
overflow: auto;
}
&#13;
<div class="parent">
<div class="child square">
<div class="inner">responsive square 1:1</div>
</div>
</div>
&#13;
jsFiddle:https://jsfiddle.net/azizn/mheoqbnw/
答案 1 :(得分:2)
你想要的是这个: http://marcj.github.io/css-element-queries/ 元素查询,未来
答案 2 :(得分:0)
试试这个
#par{
width: 200px;
height: 200px;
border:2px solid black;
overflow: hidden;
}
#par #child{
position: relative;
width: 50%;
height: 50%;
margin: auto;
margin-top: 25%;
background-color:red;
}
答案 3 :(得分:0)
只需为#child
元素提供max-height
和max-width
100%:
#child{
height:100px;
max-height:100%;
width:100px;
max-width:100%;
}
答案 4 :(得分:0)
给孩子最小,最大和最高100%它会去看它的父母和100%它采取相同的高度
答案 5 :(得分:0)
你在这里: -
.child
{
height:100px;
width:100px;
background-color:red;}
.par
{
position: relative;
height:200px;
width:200px;
border:2px solid black;
}
.par:before{
content: "";
display: block;
padding-top: 100%; /* initial ratio of 1:1*/
}
.par > .child{
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
&#13;
<html>
<body>
<div class="par">
<div class="child">
</div>
</div>
</body>
</html>
&#13;
如果有帮助,请标记问题已解决。
答案 6 :(得分:0)
我使用EQCSS,这是一个元素查询插件,可以让我从JavaScript中获取值,以便在我的CSS中使用。这是一个带有33%宽的列的演示,其中有一个正方形,可以在其内部响应调整大小:
<section>
<div></div>
</section>
<style>
section {width: 33%;}
@element 'div' {
$this {
width: auto;
height: eval("clientWidth")px;
background: red;
}
}
</style>
<script src=http://elementqueries.com/EQCSS.js></script>
在此代码段中,width: auto
表示它会展开以填充其容器。 eval('clientWidth')
位于元素查询内部,因此它引用this.clientWidth
,其中this
是与查询匹配的元素。这意味着我们的方块的高度将始终等于其宽度! (一个正方形)。
检查出来:http://elementqueries.com
我也使用相同的技术,允许我根据宽高比调整Youtube和Vimeo iframe的大小而不需要包装器:
@element 'iframe' {
$this {
margin: 0 auto;
width: 100%;
height: eval("scrollWidth/(width/height)")px;
}
}
响应式视频缩放演示:http://elementqueries.com/demos/video-scaling.html
希望这有帮助!