Design a square confined within an adjustable rectangular container

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.

Answer №1

For a better understanding of how jQuery works, take a look at this example. Additionally, I created a similar example on jsfiddle.

* {
    margin: 0;
    padding: 0;
    box-sizing:border-box;
  }
  #resizable { 
    display:flex;
    justify-content:center;
    align-items:center;
    width: 150px; 
    height: 150px; 
    min-width:100px;
    min-height:100px;
  }

  #resizable h3 {
    display:flex;
    justify-content:center;
    align-items:center;
    height: 100px;
    width: 100px;
    text-align:center;
  }
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Resizable - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#resizable" ).resizable();
  } );
  </script>
</head>
<body>
<div id="resizable" class="ui-widget-content center-center">
  <h3 class="ui-widget-header">Resizable</h3>
</div>
</body>
</html>

<!-- Reference link https://jqueryui.com/resizable/ -->

Answer №2

Eliminated the static height and width that was being added from JavaScript and substituted it with width: 50%; and height: 50%; for .box-square

$('.box-rect').resizable();
.body{
  width: 400px;
  height: 200px;
}

.box-rect {
  width: 100%;
  height: 100%;
  min-width: 100px;
  min-height: 100px;

  display: flex;
  justify-content: center;
  align-items: center;

  /* example bounding box */
  border: 1px solid gray;
}

.box-square {
    width: 100px;
    height: 100px;
 /* width: 100px;  min(box-rect.height, box-rect.width) */
 /* height: 100px;  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 {
    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">
        </div>
      </div>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Maintaining a Multi-page template in PhoneGap: Best practices

I'm a beginner in Hybrid app development, currently using PhoneGap and Jquery Mobile. In my app, I have around 10 separate pages such as login.html, index.html, search.html, etc. My query is whether I should include all JS and CSS files on each indivi ...

Full width display without any scrollbars

I need some help with adjusting the width of a section on my webpage to fit the browser size. Currently, I am using width: 100%, but this is causing scrollbars to appear. Unfortunately, I can't use overflow-x: hidden; as it will hide some of the conte ...

Tips on avoiding quotation marks in a Less variable containing a color identifier

I'm currently working on an HTML/CSS project where I aim to establish classes for labels and texts based on their color. For instance: .text-red{ color: red; } .label-white{ color: white; } In order to achieve this, my approach involves cr ...

Arrange elements both at the beginning and the end of a line using FlexLayout in Angular

Using the Angular flexlayout library in angular 7/8, I am trying to align 4 buttons on the left side (flex-start) and two checkboxes on the right side (flex-end) at the same level. I would prefer to achieve this layout using the flexlayout Angular library. ...

Manipulating div positions using JQuery and CSS

Whenever I hover over the #HoverMe div, a hidden #hidden div appears, and when I unhover it, the hidden div disappears again. The #hidden div contains a sub-div that functions like a dropdown list. The #hidden div is styled with position: absolute;. How ca ...

Why isn't my margin: auto code centering correctly?

My current struggle involves centering a div within the document. While I have successfully achieved horizontal centering, vertical centering remains elusive: width: 950px; height: 630px; background: #FFFFFF; margin: auto; Is it not expected that margin: ...

Feeling lost and frustrated trying to align a div with a menu in the center

I've been struggling for over an hour now to center a menu on my website. Despite trying all of Google's recommendations, I still can't seem to get it right. Could someone please point out what obvious mistake I might be making? Below is ...

Ways to inspect a number within a span and adjust its color depending on the value?

Can someone help me figure out why this code is not reading the value correctly? Check it out here This is the HTML: <a class="InterestLink">Click me</a> <div id="InterestExpander"> <div id="InterestExpanderX"> ...

Is there a glitch in the Selenium Java CSS Selector functionality?

Everything seems to be working smoothly with that code! It successfully locates and clicks on my button within the span tag. driver.findElement(By.cssSelector("span[id$=somePagesCollection] a")).click(); However, after clicking the button, an input field ...

Iterating through two classes in a Javascript loop

Hello, I'm facing a small obstacle that I'm hoping to overcome using JavaScript/jquery. Essentially, I have multiple div classes and I want to create a loop that adds a class to specific divs without manually assigning an id to each one. The goal ...

Tips to detect a specific animation completion on an element?

How can I ensure that a specific animation ends when multiple animations are triggered on an element? My scenario involves an overlay song list that appears when a list icon is clicked. The challenge lies in closing the menu smoothly. I have implemented a ...

Unable to assign a className to a personalized React component - troubleshooting needed!

I have a component that relies on another component. I am trying to pass CSS positioning from the outer component to the inner one by using the following code: import OptionsMenu from './OptionsMenu' import { withStyles } from 'material-ui/ ...

Adjusting the height of a div according to the changing heights of other divs

The sidebar contains a search field, two lists, and a text div. The height of the search field and text div always remains constant, while the heights of the two lists vary dynamically. I am exploring the possibility of using only CSS to make the height o ...

How can I make <p> elements change color when scrolling?

My Goal https://i.sstatic.net/JbdXR.gif I aim to bring attention to the <p> element as the user scrolls on the page. Initially, the opacity is set to 0.3, but I want it to change to 1 gradually as the user scrolls down. My Attempt window.o ...

Achieve consistent column heights with flexbox styling

I have a solution for achieving equal height columns using the CSS property display:table. Here is an example: .row { display: table; width: 100%; } .col{ display: table-cell; } However, in my case, I am using flexbox and the row class has ...

"Step-by-Step Guide to Dividing and Centering Text Sections with Dynamic

Initially, my intention is to implement the concept outlined below. The webpage has dual potential states. In the first scenario, two texts (with potentially varying lengths) are centralized together as a header. When transitioning to the second state, the ...

Clickable functionality disabled for form elements

I am encountering an issue with my system development task. The form elements appear to be unclickable, preventing any data entry in the fields. I have attempted moving the form tag above the first div in the code structure below as a troubleshooting step, ...

JavaScript array images are not showing when using the img tag

For this module, I am working on creating a flipbook (magazine) using images stored in a JavaScript array. However, I am facing an issue where the images are not loading up properly. Instead of displaying the image, it shows as [object" htmlimageelement]=" ...

CSS: ways to set a maximum height for a datalist container

Hello, I have a datalist with over 100 options and I would like to set a maximum height for it to ensure the design looks tidy. Can anyone please help me out with this? Thank you! <input type="text" list="suggestions" class="f ...

Tips for preventing images from stretching the width and height of my HTML

I am facing an issue with my SVG files positioned as "absolute" on my page. When they are close to the corners of the page, they end up expanding the width of my Container element (using Material UI React). I have tried setting "maxWidth":"100vw" on the ...