Use percentages for the width in CSS and pixels for the height, ensuring that both dimensions are equal

I'm attempting to create a square that adjusts its size according to the screen size.

Currently, I have the width set to 25%. Is there a way to ensure that the height remains the same length in pixels as the width?

Appreciate any assistance on this matter.

Answer №1

To achieve the desired result, consider using the top/bottom padding property in percentage.

Check out this example.

.box {
    width: 25%;
    padding-bottom: 25%;
}

The use of a percentage value on top/bottom padding or margins is relative to the width of the container block of the box.

8.4 Padding properties: 'padding-top', 'padding-right', 'padding-bottom', 'padding-left', and 'padding'

<percentage> The percentage is calculated with respect to the width of the generated box's containing block, even for 'padding-top' and 'padding-bottom'.


Adding Content

If you want the height of the box to adjust dynamically with added content, one approach is to wrap the content within an element called .wrapper and position it absolutely relative to the box. Then, utilize the top, right, left, and bottom properties to fill the entire space of the box.

View this example

<div class="box">
  <div class="wrapper">
    <!-- Your content here... -->
  </div>
</div>
.box {
  width: 25%;
  position: relative;
}

.box:after {
  content: "";
  display: block;
  padding-top: 100%; /*  1:1 square */
}

.box > .wrapper {
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
}

For more information, you can refer to this answer (Responsive Container section).

Answer №2

If you set the width value as a percentage, you can then use jQuery to grab it and set it as the height value. Take a look at this example:

var box = $(".box");
var width = box.css("width");
box.css("height", width);

Example link here

Answer №3

If you're looking to include content, consider utilizing pseudo elements and float behavior: http://codepen.io/anon/pen/fklAr/

div {
  width:25%;
  background:red;
  margin:auto;
}
div:before, div:after {
  content:'';
}
div:before {
  float:left;
  padding-top:100%;
}
div:after {
  display:block;
  clear:both;
}

A helpful resource for centering content within a div container: Center content in the middle of div container

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

Executing a function within the same file is referred to as intra-file testing

I have two functions where one calls the other and the other returns a value, but I am struggling to get the test to work effectively. When using expect(x).toHaveBeenCalledWith(someParams);, it requires a spy to be used. However, I am unsure of how to spy ...

Gridsome's createPages and createManagedPages functions do not generate pages that are viewable by users

Within my gridsome.server.js, the code snippet I have is as follows: api.createManagedPages(async ({ createPage }) => { const { data } = await axios.get('https://members-api.parliament.uk/api/Location/Constituency/Search?skip=0&take ...

JavaScript method that accepts two functions as arguments

What is the proper syntax for passing two or more functions to a method, like in this example setInterval("javascript function",milliseconds); is the following correct? setInterval("pushmarkers();clearOverlays();loadmarkers();",5000); ...

Ways to activate an event based on the dimensions (width/height) of

Exploring ways to implement an if statement based on specific width/height values using this code example. Check out the code snippet here My approach: <p id="confirmation">Try again!</p> <script> if (new dynamicSize.width() < ...

A guide on how to alternate between ng-hide and ng-show using separate controllers by utilizing a shared factory toggle state instance

Using Angular 1.x, I have implemented two controllers where I want to display controller_2 if controller_1 is hidden. To achieve this, I am utilizing a factory method. Here is the snippet of my HTML code:- <div ng-controller="controller_1 as c1" ng- ...

Tips for choosing a dynamically generated ajax element

Question for you: I have a snippet of HTML code that looks like this: <li class='entry'> <div class='entryContent'> <p class='entryText'>Entry text></p> <a href="#" c ...

Steps to deactivate the select element in backbone.js

Can someone help me with disabling the select option in my MVC template code using backbone.js? I tried using readonly="readonly" and disable="disable", but it sends null as value and doesn't update my address. <div class="login-register" data-val ...

Using ValidationGroup to trigger JavaScript calls from controls

Is it possible to trigger a JavaScript function from the "onclientclick event" of a button that has a ValidationGroup assigned? <asp:Button ID="btnTest" runat="server" Text="Test" OnClick="btnTest_Click" ValidationGroup="Valid ...

vee-validate remains consistent in its language settings

Having trouble changing the error message in vee-validate, any suggestions on how to fix this? import VeeValidate from "vee-validate"; import hebrew from "vee-validate/dist/locale/he"; Vue.use(VeeValidate, { locale: "he", dictionary: { he: { me ...

The Python error message, "JSONDecodeError: Expecting value: line 1 column 1 (char 0)," indicates that there

What is causing this error to occur? Are there any alternative methods available for converting it into a json file? import requests import json url = 'https://finance.yahoo.com/quote/AMZN/balance-sheet?p=AMZN&.tsrc=fin-srch' r = requests. ...

Empty placeholder image appearing at the beginning of JavaScript slideshow in Ruby on Rails

As a newcomer, I ask for your understanding if I lack knowledge in some areas. I have been working on a project and using the cycle2 plugin successfully to create a slideshow on my index page with images pulled from the internet. Now, I am trying to impl ...

Example of Node-gallery used in isolation, displaying an error event with the message "ENOENT"

I am currently experiencing an issue with the node-gallery npm module. After installing dependencies inside the /example directory, I attempted to run the app. The result was a localhost:3000/gallery page, but upon the page fully loading, I encountered the ...

Obtaining the current value with each keystroke

While working with vue.js, I'm building a table that contains an input field called quantity. However, when I start typing the first word, it shows 'empty' on the console. If I type 3, it displays empty; and if I type 44, it prints 4. I am ...

Achieving left alignment for Material-UI Radio buttons: Float them left

Click here to view the demo https://i.stack.imgur.com/Yt4ya.png Check out the demo above to see the code in action. I'm currently struggling to align the radio buttons horizontally, wondering if there's an easier way to achieve this using Mater ...

Retrieve JSON data within React without the need for importing it

Recently, I've been incorporating data from a JSON file into a React component in a unique way: import data from '../../public/json/data.json'; Using the innovative create-react-app tool, upon running npm run build, the expected behavior o ...

Achieving the resolution of a Promise amidst the failure of a separate promise

I need to handle a situation where a promise is resolved regardless of the success or failure of an ajax call. I attempted to use the following code snippet: new Promise(function(resolve, reject) { $.ajax({ url: "nonExistentURL", headers: { ...

What is the proper method for implementing an event listener exclusively for a left mouse click?

Is there a way to make Phaser recognize only left mouse clicks as click events, excluding right and middle clicks? Check out this Phaser example at the following link: https://phaser.io/examples/v2/basics/02-click-on-an-image. ...

Obtaining specific data from the forEach iteration, post-click event with JavaScript

Trying to access the value from a Tree-structured Array of Objects stored in Local Storage, Created a function that retrieves values from local storage using forEach and displays them on the screen. Clicking on the Yes/No button triggers the same functio ...

Utilize React Material UI Slider to dynamically adjust Border Radius in your web design

Utilizing React Material UI's components like the slider and button is essential for this project. The main objective is to dynamically change the border radius of the button using the value obtained from the slider. However, there seems to be a chall ...

Enhancing CSS and HTML: Increasing the Border Color of Dropdown Menus and Utilizing Multiple Words per Dropdown Item

CODE div.box { display: block; text-align: center; margin: auto; z-index: 5 } #navMenu { margin: 0; padding: 0; } #navMenu ul { margin: 0; padding: 0; line-height: 30px; } #navMenu li { margin: 0; padding: 0; list-style: none; float: left; positio ...