Is it possible to make a div resize to fit its container?

I have a square block measuring 100*100px. The container block it is within can be resized. I need the inner block to adjust its size dynamically so that it always fits inside the parent container without overflow and maintains its square shape.

Important: It's crucial to keep the inner div as a square.

#child {
  height: 100px;
  width: 100px;
  background-color: red;
}
#par {
  height: 200px;
  width: 200px;
  border: 2px solid black;
}
<div id="par">
  <div id="child">
  </div>
</div>

Answer №1

To create a square element with a ratio of 1:1, simply apply the CSS property padding-bottom: 100%. If you want content within this square, the inner content must be positioned absolutely.

body { width: 200px; }

.square {
  padding-bottom: 100%; /* 1:1 aspect ratio (square) */
  border:1px solid red;
  position: relative;
}
<div class="square"></div>

You can place the square inside a container or parent element, but how should overflowing behave?

.parent {
  height: 200px;
  width: 80%;
  border: 1px dashed black;
}

.square {
  padding-bottom: 100%; /* 1:1 aspect ratio (square) */
  border:1px solid red;
  position: relative;
}

.square .inner {
  position: absolute;
  top: 0; left: 0;
  width: 100%;
  overflow: auto;
}
<div class="parent">
  <div class="child square">
    <div class="inner">responsive square 1:1</div>
  </div>
</div>

https://i.sstatic.net/EYBSz.gif

Example on jsFiddle: https://jsfiddle.net/azizn/mheoqbnw/

Answer №2

If you're looking for it, here's the link to check out: The future of element-queries is here!

Answer №3

To ensure the #child element maintains its proportions, set both the max-height and max-width to 100% in addition to the specified height and width:

#child{
  height:120px;
  max-height:100%;
  width:120px;
  max-width:100%;
}

Answer №4

Give this a go

#box{
    width: 150px;
    height: 150px;
    border:1px solid black;
    overflow: hidden;
}

#box #inside{
    position: relative;
    width: 50%;
    height: 50%;
    margin: auto;
    margin-top: 25%;
    background-color:blue;
}

http://jsfiddle.net/ab458dmy/

Answer №5

When you provide the child element with a minimum, maximum, and height of 100%, it will automatically adjust its size to match that of its parent element.

Answer №6

Check out the solution below:

.child
{
    height:100px;
    width:100px;
    background-color:red;
}
.par
{
    position: relative;
    height:200px;
    width:200px;
    border:2px solid black;
} 
.par:before {
    content: "";
    display: block;
    padding-top: 100%; /* maintain aspect ratio of 1:1 */
}
.par > .child {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}
<html>
  <body>
<div class="par">
<div class="child">
</div>
</div>
    </body>
</html>

If this resolves your issue, please mark it as solved.

Answer №7

I love using EQCSS, a unique tool that allows me to extract data from JavaScript and incorporate it into my CSS styling. Take a look at this example featuring a column that is 33% wide with a resizable square inside:

<section>
  <div></div>
</section>
<style>
  section {width: 33%;}
  @element 'div' {
    $this {
      width: auto;
      height: eval("clientWidth")px;
      background: red;
    }
  }
</style>
<script src=http://elementqueries.com/EQCSS.js></script>

The use of width: auto ensures the square fills its container. The eval('clientWidth') statement within the element query specifically refers to the width of the element itself, resulting in a square shape where the height matches the width.

Explore more at:

I apply a similar approach to dynamically adjust the size of Youtube and Vimeo iframes based on their aspect ratio without requiring additional wrapping elements:

@element 'iframe' {
  $this {
    margin: 0 auto;
    width: 100%;
    height: eval("scrollWidth/(width/height)")px;
  }
}

Witness responsive video scaling in action:

This method has been incredibly useful for me, and I hope you find it valuable too!

Answer №8

New CSS Attribute for Aspect Ratio

body { width: 200px; }

.square {
    border: 1px solid red;
    aspect-ratio: 1 / 1;
    width: 100px; /* <-- optional, this is only for the demo */
}

.not-a-square {
    border: 1px solid green;
    aspect-ratio: 2 / 1;
    width: 100px; /* <-- optional, this is only for the demo */
}
<div class="square"></div>
<div class="not-a-square"></div>

Learn more at: https://caniuse.com/mdn-html_elements_img_aspect_ratio_computed_from_attributes

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

What is the best way to set a default value for a date input field?

I am in the process of developing a form that enables users to modify the information on the form, with the initial values of the form appearing as defaults. Despite setting my variable as the value, it does not display. All other default values are visib ...

jQuery's z-index feature is malfunctioning

When I hover over my menu, a box fades in. However, there is a small icon behind this box that I want to move to the front so it can be visible during hover. To see an example of my menu, click here: Navigation I attempted to address this by using jQuer ...

Resizing with Jquery results in sudden movement

I have used jQuery to create a set of buttons inside a <ul> element. I am now attempting to resize the <ul> by adding a handle to the top of it, but when I try to resize it, the element jumps as shown in the images below. What could be causing ...

The progress bar for uploading a file is causing issues with the redirect function in the

I am currently facing an issue with my file submission form and progress bar in JavaScript. The progress bar is interfering with the controller, preventing it from redirecting back home with the link. I have tried removing window.location.href="/"; but thi ...

Filling a blank table using jQuery

I am attempting to search for an item by sending a GET request to my service and then populating my table with the response, but I am struggling to achieve this with my current code. $(function(){ var $searchInput = $("#search"); $("#searchOptions").c ...

Limiting the length of numbers in Material UI

Is there a way to restrict user input to only numbers with a maximum length of 3 in Material UI? <TextField id="score" label="score" className={classes.textField} name="totalScore" margin="normal" defaultValue={score} /> We specifically ...

Using Styled Components to Implement Background Images in a React Application

I'm currently attempting to pass a background image using a prop, but I'm encountering an issue where it's indicating that url is undefined. const CardImage = styled.div` height: auto; width: 100%; background-size: c ...

Adjust the height of the drawer in material-ui

In my current project using react and material-ui, I am facing a simple issue that has me stumped. I am trying to create a drawer with a specific height so that it does not overlap the app bar when opened. Unfortunately, there is no built-in parameter in ...

[CSS] What's the trick to getting it to smoothly glide to the top?

As a new designer, I have a question about how to make the background color extend to the top without any white space. Can someone please guide me on how to achieve this? <!DOCTYPE html> <html> <head> <style> body{ margin: 0px; p ...

Finding the div associated with the element that triggered an event

I've recently launched a website that allows users to post questions and receive responses from others. Each question is housed in a div, which then contains another div with the CSS property of display: none. Within the main div, there's a butt ...

Struggling with clicking on an <a> tag using Python Selenium that leads to a popup dialog box

Currently, I am honing my web scraping abilities by utilizing the World Surf League website. So far, I have not extracted any data; instead, I am focusing on navigating the site using Selenium. However, I have hit a roadblock where I am unable to 'cli ...

Calculate the total of the temporary information entered into the input field

I'm totally new to all of this and definitely not an expert, but there's something that really bothers me. I found a website where you have to complete a captcha to log in. It goes like this: <input type="text" class="form-contr ...

UI experiencing issues with selecting radio buttons

When trying to select a radio button, I am facing an issue where they are not appearing on the UI. Although the buttons can be clicked, triggering a function on click, the selected option is not displayed visually. <div data-ng-repeat="flagInfo in avai ...

jQuery checkbox toggles multiple divs instead of targeting specific ones

I have set up my page to display divs containing posts using a specific format. The divs are structured as follows (replacing # with the postID from my database): <div id="post_#> <div id="post_#_inside"> <div id="like_#"> ...

Unfortunately, CSS3 PIE is not compatible with border-radius and box-shadow properties

I created a basic HTML/CSS code for testing purposes, but I'm having trouble getting the library to function properly. I've placed the .htc, .php and .js files in the same directory as index.html, but it just won't work. Check out the code ...

Hovering over a container will display the text in a single line

<div class="flex-container"> <div class="red hover flex"> <h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </h1> </div> ...

highcharts-ng expands in flexbox without contracting

I've encountered an issue while trying to incorporate a highchart within a flexbox container. The chart expands along with the container without any problems, but it fails to contract when the container size decreases. My current setup involves angul ...

Tips on changing font color within an email body in Outlook using a C#.NET Windows application

While working on a c#.net windows application, I encountered an issue with setting font color for specific lines in the email body when sending mail to Outlook. Despite trying various methods, I was unable to find a solution. Below is a snippet of my code: ...

Chrome users may encounter difficulty grabbing the horizontal textarea scrollbar if a border-radius has been applied

Check out this JSFiddle for more information <textarea wrap="off" rows="5" style="border-radius: 4px">aaaaaaaaaaa aaaaaaaaaaa aaaaaaaaaaa aaaaaaaaaaabbbbbbbbbaaaaaaaaaaabbbbbbbbbaaaaaaaaaaabbbbbbbbbaaaaaaaaaaabbbbbbbbbaaaaaaaaaaabbbbbbbbb aa ...

The font size varies depending on the language being used

On a single web page, there are 3 different language words displayed: Language / 한국어 / ภาษาไทย I am interested in enlarging the Thai word (ภาษาไทย) to make it stand out. <span class="thai">ภาษาไท ...