Square Division, width set to match 100% of the height

I have been attempting to create a square shape that is responsive, with the width determined by the height of the element (100%). I personally think achieving this using CSS alone is not possible.

The goal is for the square's width to match its height (which is 100% of the larger container's height, exceeding 100% of the screen size). This ratio must be maintained to retain the square shape.

Answer №1

One way to achieve this is by incorporating a small inline image without the need for JavaScript or additional files.

.container {
  height: 150px;
  width: 100%;
  text-align: center;
  background: #acd;
}
    
.square {
  display: inline-block;
  height: 100%;
  background: #691;
}
<div class="container">
  <div class="square">
    <img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" height="100%">
  </div>
</div>

Answer №2

Have a look at the aspect-ratio property to understand how it works.

This property simplifies the process of creating a square div based on height. Below is an example code snippet:

h2 {
  font-family: calibri;
}

#parent {
  height: 96px;
  width: 256px;
  background: grey;
  margin-bottom: 16px;
}

#child {
  height: 80px;
  aspect-ratio: 1 / 1;
  background: lightgrey;
}

#anotherParent {
  height: 96px;
  width: 256px;
  background: grey;
}

#anotherChild {
  height: 50%;
  aspect-ratio: 1 / 1;
  background: lightgrey;
}
<h2>Absolute height (80px/96px)</h2>
<div id="parent">
  <div id="child">
  </div>
</div>

<h2>Relative height (50%)</h2>
<div id="anotherParent">
  <div id="anotherChild">
  </div>
</div>

For more information about the aspect-ratio property, check out these helpful links:

Answer №3

If you're looking for a CSS-only solution to size elements relative to the screen, consider using viewport units. Here's an example:

@media screen and (orientation:landscape) {
    .box{
        height: 100vh;
        width: 100vh;
    }
}
@media screen and (orientation:portrait) {
    .box{
        height: 100vw;
        width: 100vw;
    }
}

(You may want to reduce it slightly to eliminate scrolling)

This technique works well for divs that need to take up a specific proportion of screen space.

View the JSFiddle example here.

Answer №4

Given that a square has equal width and height, you can easily set the height based on the known width of the square.

If you have access to JavaScript, you might want to consider using this handy jQuery code snippet:

var wiDth = $('div').css('width'); // retrieve width
$('div').css('height', wiDth); // set the height to match the width

Feel free to experiment with it yourself at: http://jsfiddle.net/afzaal_ahmad_zeeshan/vpGUK/

Answer №5

If you're looking to achieve this effect using JavaScript, the setup involves having a larger container div with a square element inside that matches its height. Here's the HTML structure:

<div id="container">
  <div id="square" style="height:100%;">
  
  </div>
</div>

To implement this in JavaScript, you can use the following code:

<script>
  var container = document.getElementById("container");
  var square = document.getElementById("square");

  square.style.width = container.style.height;

  window.onresize=function(){
    square.style.width = container.style.height;
  };
<script>

I hope this solution works for you!

Answer №6

Check out this amazing 'css only' solution that I believe will work great for your needs. It is compatible across different browsers.

This article emphasizes an interesting css rule:

If you specify vertical paddings (and margins) in percent (%) values, the size will be a percentage of the width of the containing element.

Answer №7

Embed this code in your website:

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
and experiment with jQuery:

let containerHeight = 0;
$("#yourContainer").children().each(function(){ 
    containerHeight += $(this).height;  
});
$("#yourContainer").css('width', containerHeight + 'px');

Answer №8

Here is the solution to your problem:

<div id="square" style="background-color:black;height:100%">test</div>

$(window).ready(updateWidth);
$(window).resize(updateWidth);

function updateWidth()
{
var square = $('#square');
var size = square.height();

square.css('width',size);
}

Check out this jsFiddle link for a demo.

Answer №9

To create a square div with 100% height and width, simply assign the desired values to the container.

.container {
    width: 100%;
    height: 100%;
}

This will ensure that the div maintains a perfect square shape with equal height and width dimensions.

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

Increase the number of button groups when clicked

I have a button group with three buttons: left, middle, and right. I want to enhance this functionality so that when any of the main buttons are clicked, the corresponding sub-buttons (left-sub, middle-sub, or right-sub) appear accordingly: <div class= ...

Customize the CloseIconButton in Material-UI Autocomplete for a unique touch

Hello everyone, I have a simple dilemma. I am trying to implement a custom closeIconButton, but the only available prop is closeIcon. However, this prop is not sufficient because I need this custom button to also have an onClick property. If I add the onC ...

Iterate through the .json file and add markers to a leaflet map

Apologies for the basic question, but I'm struggling with understanding JavaScript and json files. I have a .json file that updates server object locations every 5 seconds, and I want to plot these coordinates on a map using leaflet for staff access. ...

Creating a Show/Hide toggle feature in AngularJS using NG-Repeat

I'm facing an issue with my code where I have a list of items that should only open one item at a time when clicked. However, currently, all items are opening on click and closing on the second click. Can anyone help me identify the problem in my code ...

"Creating a Hyperlink that Navigates to Specific Content Within a

I have a situation where I am trying to link to sections on the page contained within collapsed fieldsets. My goal is that when a user clicks on this link, the page should scroll down and automatically expand the fieldset to display the content inside. E ...

The text content is not in alignment with the server-rendered HTML for translation purposes with i18n

I have successfully implemented i18n in my Next.js project. The folder structure for my locales is as follows: public/locales/en/translation.json and public/locales/fr/translation.json The error I am encountering is: Uncaught Error: Text content does n ...

Pass a data variable to an HTML file using express's sendfile function (quick inquiry)

Currently utilizing Node.JS, path, and express for running an HTML webpage. I need to pass a variable to the HTML file for its utilization: var client_cred_access_token = 'fakeToken'; ... app.get('/', function (req, res) { res.se ...

Navigating through a multistep form in AngularJS using UI Router and arrow keys for seamless movement

Is there a way to navigate to the next or previous form step using arrow keys in AngularJS UI Router? The code provided below is currently allowing navigation with previous and next buttons. .config(function($stateProvider, $urlRouterProvider) { $stat ...

Ensuring JSON data protection when sending Ajax requests in JavaScript (for(;;);)

After extensive research, I have not been able to find the answer I'm looking for despite similar questions being asked. My query concerns the usage of for(;;); while(1); before an Ajax response outputs a JSON string. I am curious about how this tec ...

Loading images in advance using JavaScript

I have been searching through multiple forums and cannot seem to figure out the issue. The problem I am encountering is related to a website where there are three images with a hover effect. When the page first loads, there is a delay in loading the backgr ...

The second node child process encounters execution issues in Linux

For a challenge, I needed to find a way to automatically restart my bot within itself. After some trial and error, I came up with a solution. However, when testing on a Raspberry Pi via ssh, the process exits after the first child process ends. Surprisingl ...

Rearrange lists by dragging and dropping them according to specific criteria

In my AngularJS project, I am utilizing the angular-drag-and-drop-lists library from here to create two lists with the following functionalities: Dragging items from list A to list B Dragging items from list B to list A Reordering items in list A Reorder ...

Issue with Ajax submit button failing to pass ID

I am encountering an issue while trying to update data using bootstrap modal. When the CGridView selectionChanged event is triggered, it should call a function to display a modal dialog form and populate the form with the selected data. Below is my CGrid ...

Guide to transforming Tailwind CSS into a class and saving it in a CSS document

Recently, I implemented Tailwind CSS to style my application. It has been a helpful tool, but I am looking to consolidate all the CSS into one file for better organization. I want to keep it separate from the HTML code. My attempt to convert the following ...

What is the best way to transfer JSON data to a different controller in AngularJS?

Hello, I'm still learning AngularJS and facing an issue with the following code snippet. app.config(function($routeProvider) { $routeProvider .when('/', { templateUrl: "partials/home.html", controller: "mainControlle ...

Having trouble with Webpack dynamic import not returning files in ReactJS? Here's how to fix it

Struggling with importing and using images in Reactjs? I've imported all images from a folder but it's not returning an array with links. Take a look. function importAll(r) { return r.keys().map(r); } const images = importAll(requi ...

Fetching data from a database for Vue.js using the Summernote editor

I previously inquired about integrating summernote with vue.js and received a helpful response here. It worked seamlessly with v-model binding. However, I encountered an issue when attempting to load data from the database for an edit page. The data was n ...

Having trouble with the mouse trail code on codepen.io

I am currently attempting to integrate this specific CodePen sample into a Hugo template called Somrat Theme. I'm facing challenges in deciding where to place the HTML file; only the 'no cursor' section should go into style.css, and I need ...

Is there a way to retrieve the JavaScript Console response code using Python and Selenium's execute_script method?

I am running a JavaScript fetch request in the Chrome developer console using Selenium's execute_script() function. The request performs as expected, but I want to set up a function that can verify if the response is a 403 status code. Is there any Se ...

Is it possible to nest v-for directives within a component file?

Even after going through the VueJS tutorials multiple times, I am still unable to find a solution to this problem. My issue revolves around displaying a list of lists using accordions, which is supposed to work smoothly with vue-strap components. For exa ...