Is there a way to reduce the size of a div within another div using CSS?

Trying to resize a nested div (divB) within another div (divA) is proving challenging. The issue arises when the height of divA is determined by its content. When divB is resized, divA's height remains unchanged... This occurs due to the application of a transform because it does not alter the pixel count; instead, it adjusts the size of the pixels themselves (or at least that's what seems to be happening). To resolve this dilemma, one can manually set the height of divA to the product of divB's size and the scaling factor.

However, manual adjustment of divA's height becomes tedious whenever changes occur in the content of divA. In my scenario, where there will be numerous alterations to divA's content, this method proves cumbersome. Hence, I am curious if there exists a simpler approach to address this issue, preferably utilizing CSS.

The problem can be visually demonstrated through a simple JSFiddle: http://jsfiddle.net/turtlewaxer1100/82cux/8/

To experience the issue firsthand, add elements, scale down, and observe the lack of adjustment in height. Clicking "Fix Height" rectifies the height measurement but necessitates readjustment upon further element addition...

html

<div>
    <div class="wrapper">
        <div id="scalar"></div>
    </div>
    <div class="buttons">
        <div id="button">
            <input type="button" value="Add" />
        </div>
        <div id="scaleDown">
            <input type="button" value="Scale Down" />
        </div>
        <div id="scaleUp">
            <input type="button" value="Scale Up" />
        </div>
        <div id="fixHeight">
            <input type="button" value="Fix Height" />
        </div>
    </div>
</div>

css

.wrapper {
    float:right;
    width: 200px;
    background-color: black;
}
.section {
    margin-left:75px;
    height: 50px;
    width: 50px;
    background-color: red;
}
.buttons {
    float:left;
}
.scaleDown {
    -webkit-transform: scale(0.75);
    -moz-transform: scale(0.75);
    -ms-transform: scale(0.75);
    transform: scale(0.75);
    -webkit-transform-origin: 50% 0 0;
    -moz-transform-origin: 50% 0 0;
    -ms-transform-origin: 50% 0 0;
    transform-origin: 50% 0 0;
}

jquery

var section = $("<div class='section'></div>")

$(document).ready(function () {
    $("#button").children().click(function () {
        $("#scalar").append(section.clone(false));
    });

    $("#scaleDown").children().click(function () {
        $("#scalar").addClass("scaleDown");
    });

    $("#scaleUp").children().click(function () {
        $("#scalar").removeClass("scaleDown");
    });

    $("#fixHeight").children().click(function () {
        $(".wrapper").height($("#scalar").height()*.75)
    });
});

Answer №1

After exploring various options, I didn't come across a CSS-based solution for the dynamic height change issue. However, I managed to find a simple JavaScript workaround. By utilizing the DOM event "DOMSubtreeModified," which triggers whenever an element within the current hierarchy is altered, I created a script that compares the element's height with its previous value upon this event trigger. If there's a difference, the height is adjusted accordingly. This method ensures capturing all dynamic height changes without being dependent on what specifically modified the height.

To illustrate this concept, here's a jsfiddle demonstration: http://jsfiddle.net/turtlewaxer1100/E6D2H/5/

HTML

<div class="wrapper">
    <div id="scalar"></div>
</div>
<div class="buttons">
    <div id="button">
        <input type="button" value="Add" />
    </div>
</div>

CSS

.wrapper {
    float:right;
    width: 200px;
    background-color: black;
}
.section {
    margin-left:75px;
    height: 50px;
    width: 50px;
    background-color: red;
}
.buttons {
    float:left;
}
#scalar
{
    -webkit-transform: scale(0.75);
    -moz-transform: scale(0.75);
    -ms-transform: scale(0.75);
    transform: scale(0.75);
    -webkit-transform-origin: 50% 0 0;
    -moz-transform-origin: 50% 0 0;
    -ms-transform-origin: 50% 0 0;
    transform-origin: 50% 0 0;
}

JS

var section = $("<div class='section'></div>")
var scaleFactor = 0.75;
var originalHeight = 0;

$(document).ready(function () {
    $("#button").children().click(function () {
        $("#scalar").append(section.clone(false));
    });

    $(".wrapper").bind('DOMSubtreeModified', function() {
        var height, heightOffset;

        height = $("#scalar").height();
        if (height && originalHeight !== height) {
            heightOffset = height * scaleFactor;
            $(this).height(heightOffset);
            return originalHeight = height;
        }
    });
});

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

Having trouble incorporating autocomplete search results into an HTML table using Jquery, Ajax, and JSP

My current project involves an App that utilizes AJAX with jQuery to communicate with a Spring-boot REST controller. While the app is functional, I am facing difficulty in displaying the search results neatly within HTML tables. https://i.sstatic.net/7sw8 ...

The React Component is caught in a loop of continuous re-rendering and reloading

Just starting out with React and tackling my first project. Running into a bit of trouble here, so I'm sharing my code for some insight. When users input their search term and hit 'search,' they are redirected from another page to this one. ...

Firebase Firestore is returning the dreaded [object Object] rather than the expected plain object

I've created a custom hook called useDocument.js that retrieves data from a firestore collection using a specific ID. However, I'm encountering an issue where it returns [object Object] instead of a plain object. When I attempt to access the nam ...

Using the jQuery hover function with dynamically added classes

I'm struggling to apply the active class when hovering over a dynamically inserted element. I've tried simplifying the code below, but I haven't had any luck. I've researched using the .on method, but that hasn't worked either. $( ...

The dropdown menu on my HTML form is causing a problem by saving null values to the MySQL database

Everything in the form is functioning correctly except for the grade field, which is returning null values. Below is the HTML code: <body> <form action="/out" method="post"> <label for="grade">Grade:&emsp;&emsp;& ...

Can the operator pipeline generate interim observables in a manner akin to how filter, map, and reduce generate interim arrays?

I need some clarification regarding the efficiency of operator pipelines in RxJS. Based on my current understanding, each operator within the pipeline receives an observable and generates a new (potentially modified) observable to pass on to the next oper ...

Using the function to show content by calling its assigned ID

<script type="text/javascript"> function selectRow(id){ $.get("http://inactive/test.php?id=" + id, function(data,status){ return data; }); } </script> <script type="text/javascript"> $("tr").click(function() { window.l ...

Unraveling base64 information to display an image in Django using JavaScript

Why is the captured image only saving as a blank image when trying to encode and store it in a database from a canvas? Take a look at the following code snippet: const player = document.getElementById('player'); const docs = docu ...

Initiate a fade-in/fade-out slider when the button is clicked

I have successfully developed a fadein/fadeout slider that automatically transitions between images. However, I am now looking to implement the functionality to manually play the slider by clicking on next/prev buttons. HTML <section class="wrapper"&g ...

ASP Table extends into adjacent column

Having some trouble with the table layout here. In the screenshot, you'll notice a grid view within another gridview. There are currently 3 grid views - the main one and one in each table. I'm looking to move the description to the Price 2 column ...

Utilizing jQuery and AJAX, execute a PHP query based on the user's input and showcase the query's outcome without reloading the page

For the past 24 hours, I've been on a quest to find a solution. Although I've come across similar inquiries, either the responses are too complex for my specific scenario (resulting in confusion) or they are of poor quality. The crux of my issue ...

Is it necessary for me to add the scraped information before I can retrieve it?

I am currently extracting data from a different website and have had some success with it. However, I am facing a challenge. After fetching the data, I am required to append it inside a div to accurately extract the necessary information using getElement ...

Unusual escape_javascript quirk witnessed in Ruby on Rails

Once the ajax method is called, the escape_javascript function starts outputting </div> </div> </div> for each rendered item. Despite thoroughly checking all closing tags multiple times, I can't seem to identify any errors. Could thi ...

The uploading of a file in NodeJS is not possible as the connection was closed prematurely

When I created a website using nodejs, there was a specific page for uploading images to the server. It worked perfectly fine when tested on my computer. However, upon deploying it to the server, the upload functionality stopped working. Upon checking the ...

The jQuery date picker refuses to function correctly when I attempt to initialize it after an AJAX call

I am facing an issue with my jquery-ui datepicker not working within the document.ready function after making an ajax call. However, it works fine when I add it inside the ajax complete function. Can someone please provide assistance on what could be cau ...

Leveraging Three.js Raycaster for a seamless PDF download functionality

Is there a way to trigger a PDF download when clicking on a 3D object in a Three.js scene? Below is an example of how I have set up the Raycaster: var raycaster; var mouse = { x: 0, y: 0 }; init(); function init() { raycaster = new THREE.Raycaster() ...

Ways to tally HTML elements using VBA

Currently, I am delving into the world of creating a web scraping tool using VBA to extract event details and store them in an Excel sheet. Within this endeavor, I am faced with deciphering HTML code snippets that resemble the following: <div class="a ...

What is the process for passing a .js file into .ejs using Node.js?

I am facing an issue with loading the popmotion library into my main page, which is an .ejs file being passed to Node/Express. The code in my file popmotion.js is not running, and I want to control DOM elements mentioned in the ejs file through this file. ...

Every time Grunt detects newer files, it automatically triggers the imagemin:dynamic task

I am working with a Gruntfile that looks like this: grunt.initConfig({ imagemin: { dynamic: { files: [ src: ['lib/public/img/*.{png,jpg,jpeg,gif}'], dst: 'build/public/img/', expand: true, fl ...

When attempting to display dropdown elements in a Bootstrap navbar on different URLs within a Django project, the elements may not

I'm a newcomer to Django and currently working on developing an app that includes two models, master and details. I encountered an issue with my Bootstrap navbar dropdown while using it on a single base.html file — the dropdown works fine when displ ...