【发布时间】:2019-07-18 09:49:55
【问题描述】:
我的页面上有一个矩形区域,需要在中心填充一个正方形。这个矩形既可以是水平的,也可以是垂直的。这意味着基于仅从包含框的宽度制作正方形的大量现有问题不起作用。 [1][2]
这个方块也可以动态改变,这种方法不会调整方块的大小。如果可能的话,我也不想使用 JavaScript 或 JQuery。这是我唯一会使用 JQuery 的事情。
您可以在下面看到代码在开始时应该做什么,但是当您调整框的大小时,它不会调整正方形的大小。
/* based on https://stackoverflow.com/a/5445536*/
$('.body').resizable();
var containingBlock = $('.box-rect');
var cmin = Math.min(containingBlock.width(), containingBlock.height());
$('#box-square').css({
'height': cmin+'px',
'width': cmin+'px'
});
.body{
width: 200px;
height: 100px;
}
.box-rect {
width: 100%;
height: 100%;
min-width: 50px;
min-height: 50px;
display: flex;
justify-content: center;
align-items: center;
/* example bounding box */
border: 1px solid gray;
}
.box-square {
width: 50px; /* min(box-rect.height, box-rect.width) */
height: 50px; /* box-rect min */
}
/*
The following is using a mix between the following two answers:
https://stackoverflow.com/a/6615994
https://stackoverflow.com/a/20117454
*/
.box-reset {
position: relative;
height: 100%;
width: 100%;
}
.box-reset:before {
content: "";
display: block;
padding-top: 100%;
}
.box {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
/* example gray box */
height: 100%;
background-color: gray;
}
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class='body'>
<div class="box-rect">
<div class="box-square">
<div class="box-reset">
<div class="box">
Not working at all
</div>
</div>
</div>
</div>
</div>
<br />
<div class='body'>
<div class="box-rect">
<div class="box-square" id="box-square">
<div class="box-reset">
<div class="box">
Fills to the bounds of the rectangle on load.
</div>
</div>
</div>
</div>
</div>
完全清楚:
- 上面的第一个示例根本没有调整灰色方块的大小。
-
第二个示例将灰色正方形的大小调整为矩形的边界。 (我想要的)
但是,在调整包含块的大小时,它不会将灰色正方形的大小调整到矩形的边界。
我想将正方形调整为矩形的边界。就像在第二个示例中一样,当我调整包含块的大小时。
我更愿意在纯 CSS 中完成这一切。
【问题讨论】:
标签: css autoresize