Generate a div with a 1:1 aspect ratio using only its height specified in a percentage

Can you assist me with this task? I have a white div where I need to place two circular green buttons on the borders. The entire layout should be created using CSS. Here is an example of how it should look: Screenshot

The challenge is that I do not know the size of the white div upfront, as it will be added to the DOM dynamically with a percentage-based width and height relative to its parent. This means that traditional methods like width(), height(), or accessing CSS values directly won't work during creation. I've come across solutions for fixed aspect ratios in divs, but they all rely on knowing one dimension to calculate the other. In my case, I only know the height (100%) and want the width to adapt accordingly. How can I achieve this?

Here is the code snippet I am working with:

LINK TO CODE SNIPPET

If you have any insights on achieving this without hardcoded values (and jQuery, if necessary), I would greatly appreciate your help. Thank you.

Answer №1

There are several factors at play in this scenario:

  • The container's height is set in percentage while the circle's radius is in pixels, resulting in one being static and the other resizing accordingly.
  • To maintain a 1:1 ratio using only HTML/CSS without fixed dimensions, it would be necessary to isolate the circle's div width and height with static units like pixels.
  • If fixed dimensions are not allowed, an alternative approach could involve commenting out the arrow's height at 100% to prevent resizing and nesting a div inside the arrow to maintain a 1:1 ratio with static units.

In order for the circle to remain circular as the content expands, the height should dynamically adjust to match the width. Using JavaScript can achieve this, but the border-radius is tied to the container in static pixel units.

body {
  background-color: #DCDCDC;
}
body,
html {
  height: 100%;
}
.container {
  width: 50%;
  height: 37%;
  background: white;
  border-radius: 20px;
  position: relative;
}
.arrow {
  background: green;
  border-radius: 20px;
  /*height: 100%;*/
  position: absolute;
  overflow: hidden;
}
.bLimit {
  height: 40px;
  width: 40px;
  line-height: 40px;
}
.arrow:after {
  content: "";
  display: block;
  padding-right: 100%;
}
.arrow:last-child {
  right: 0;
}
<div class="container">
  <div class="arrow">
    <div class="bLimit">button overflow</div>
  </div>
  <div class="arrow">
    <div class="bLimit">button</div>
  </div>
</div>

Answer №2

Have you considered using a percentage-based fixed width for your arrow design instead?

.arrow {
  background: green;
  border-radius: 20px;
  height: 100%;
  position: absolute;
  width: 10%;
}

Answer №3

body{
  background-color: #DCDCDC;
}
.container {
  width: 50%;
  height: 7%;
  background: white;
  border-radius: 20px;
  position: absolute;
}
.container:after,.container:before{
  content: " ";
  display: block;
  padding: 4%;
  z-index: 999;
  top: 0;
  position:absolute;
  background: green;
  border-radius: 50%;
}
.container:before {
  left: 0;
}
.container:after{
  right: 0;
}
<div class="container">
</div>

You can style the container using the CSS pseudo selectors before and after. Here is an example for reference: Example.

Answer №4

If you wish to achieve this outcome, consider utilizing an image of the required aspect ratio that remains hidden from view.

For example, if the ratio is 1:1, you can employ an image with dimensions of 50px (although any size will suffice).

.container {
  width: 300px;
  height: 20px;
  border: solid 1px blue;
  margin: 40px;
  position: relative;
}
.container:nth-child(2) {
  height: 40px;
}
.container:nth-child(3) {
  height: 60px;
}
.arrow {
  height: 100%;
  background-color: red;
  opacity: 0.5;
  position: absolute;
  border-radius: 50%;
  transform: translateX(-50%);
}
.arrow:last-child {
  right: 0px;
  transform: translateX(50%);
}
img {
  height: 100%;
  opacity: 0;
}
<div class="container">
  <div class="arrow">
    <img src="https://placehold.it/50x50">
  </div>
  <div class="arrow">
    <img src="https://placehold.it/50x50">
  </div>
</div>
<div class="container">
  <div class="arrow">
    <img src="https://placehold.it/50x50">
  </div>
  <div class="arrow">
    <img src="https://placehold.it/50x50">
  </div>
</div>
<div class="container">
  <div class="arrow">
    <img src="https://placehold.it/50x50">
  </div>
  <div class="arrow">
    <img src="https://placehold.it/50x50">
  </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

Customize the active text color of breadcrumbs in Bootstrap

My goal is to change the text color "About us" in the breadcrumb to black, but my attempts have been unsuccessful. <ol class="breadcrumb"> <li class="disabled"><a href="index.html">Home</a></li> <li class="active"& ...

Creating a function inside of setInterval does not refresh

I'm facing an issue with a method that involves the use of setInterval public retrieveMessages(route: string) { this.http.get(this.url + route + "?page=" + MessageService.plus) .subscribe(function(response) { if (response.json.length ...

How can a variable be exported from a React component?

Is there a technique to export a variable from a React component for use in a custom hook? The code snippet is as follows:- function App() { const SignIn=()=>{ //Some code here var userId = data.info.username; //Some code h ...

Discovering a full class entity within an array using Javascript

I am currently working with an array of objects that serves as the datasource for a materials table. Before adding a new row, I need to ensure that it does not already exist in the array. Since there is no key value assigned to the objects in the array, I ...

Harness the power of multiple backgrounds with just one CSS style!

I'm exploring a way to incorporate multiple images as backgrounds into my website design. For instance, having a car image on the index page and a notepad image on the about me page. My attempt involved using the following code: body { back ...

Challenge with collapsing a button within a Bootstrap panel

Check out this snippet of code: <div class="panel panel-default"> <div class="panel-heading clearfix" role="tab" id="heading-details" data-toggle="collapse" data-target="#details" data-parent="#panel-group" href="#details"> <h4 c ...

AngularJS version 1.2.0 is experiencing an issue where the $http service is not properly sending requests

Why is AngularJS 1.2.0 $http not sending requests in $eval? Here is the code you can refer to: http://jsbin.com/oZUFeFI/3/watch?html,js,output ...

I am having trouble getting Google Maps to load

Why does the map on my website only load when the browser window is resized? Below is the JavaScript code being used: <div class="map-cont"> <div id="map" class="location-container map-padding" style="width:100%;height:400px;background:y ...

Flex container has images stretched, but align-self-center cannot be utilized

Looking for a solution to resolve an issue with the following Bootstrap 4 markup: <div class="col-3 d-flex flex-column"> <img class="align-self-center" src="#"/> </div> The problem arises when using align-self-center in a flex conta ...

Implementing automatic token refreshing and automatic logout features in Vue

I am a novice web developer looking to enhance my skills. For my initial project, I decided to incorporate Laravel and Vue. My main objectives are to: Implement an auto-logout feature after 3 minutes of user inactivity Create an automatic ping to my token ...

Setting a JavaScript value for a property in an MVC model

I am currently working on an asp.net mvc application and I am in the process of implementing image uploading functionality. Below is the code for the image upload function: $(document).ready(function () { TableDatatablesEditable.init(); ...

Issues with npm installation

Having trouble installing 'react-navigation' in my expo (react native) project using the command 'npm install --only=dev react-navigation'. I keep receiving warnings and am unsure how to proceed. See image link for details: enter image ...

Does Google's web crawler have the ability to index content created by javascript?

Our web app generates content using javascript. Can Google index these pages? In our research on this issue, we primarily found solutions on older pages suggesting the use of "#!" in links. Within our app, the links are structured as follows: domain.co ...

How to include a listview in the footer navbar using jQuery Mobile

Is there a way to include areas instead of links in the footer navbar, and then incorporate a list view within one of those areas? The navbar only seems to accept anchors, not divs, and the styling of the list view is not displaying correctly in the provid ...

When using a routerlink in an a tag with Bootstrap 4, the navigation tab functionality may not work as expected

I've been working on bootstrap4 tabs and everything is working smoothly until I add a router link to the anchor tag. Strangely, only the hover effect works in this case. Can anyone help me troubleshoot this issue? Below is my code snippet: <link ...

Centered Alignment for Bootstrap Carousel Captions

I'm attempting to make a simple change here. Rather than having the Bootstrap Carousel Captions automatically align at the bottom of the Carousel, I would like them to align at the top by default. Any suggestions on how I can achieve this? ...

Modifying selections within a select box generated dynamically using JQuery

Looking for help on how to delegate to a static DOM element in my current situation. I need to create a dynamic select box .userDrop when .addNew is clicked, and then have the user select an option from #secDrop, triggering a change event that calls the da ...

Check the box to show the corresponding sections of the form

https://i.sstatic.net/oXw8K.png.If there are two checkboxes with options true or false, how should I handle a third checkbox? I want to display different parts of the form based on the selection of the checkboxes. ...

Struggling to extract a specific value from a JSON string?

I am trying to retrieve the first element of a JSON object, but using data.first returns nothing. However, when I use alert(data), it prints the full JSON string. Can someone please help me troubleshoot this? <?php include_once '../con_db.php&apo ...

Is it possible to iterate and add an array to another array using a loop?

Looking for a more efficient way to organize my code using loops let tmpD = []; let tmpS = [[], [], []]; for(let i = 0; i < tmpD.length; i++) { signed = doctors.doc(tmpD[i].key).collection('schedule').get(); signed.then(function(ss){ ...