Looking to fill a rectangular area on my page with a square positioned in the center, regardless of whether the rectangle is horizontal or vertical. Many existing solutions focus solely on creating a square from the width of a containing box, which doesn't suit this specific need.
The square should adapt dynamically without resizing itself. Ideally, I would like to achieve this effect using pure CSS, without relying on JavaScript or JQuery for implementation.
The initial code provided demonstrates the desired outcome, but it falls short when the box is resized, as the square remains static and unchanged.
/* 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>
To clarify:
- The initial example does not adjust the size of the gray square when the container is resized.
The second example correctly resizes the square to match the dimensions of the rectangle, which is the desired behavior.
However, it fails to resize the square accordingly when the container is resized.
The goal is to have the square automatically resize to fit the dimensions of its surrounding rectangle, similar to how it behaves initially. This functionality should be achieved using only pure CSS.