Decrease the width of a div element when its sibling element expands

I am working on a layout where I have two divs placed side by side within a parent div. The left div will have text content, while the right div will contain an image. I want to implement functionality where on button click, the right div can expand or reduce back to its original width.

<style>
.parent{
  width: 100%;
  border: 1px solid blue;
  padding: 2px;
  float: left;
}
.left{
  width: 60%;
  float: left;
  border: 1px solid red;
}
.right{
  width: 38%;
  border: 1px solid orange;
  float: right;
}
</style>

<input type="submit" class="toggle_div" id="button1" value="Expand"/><br>
<div class="parent">
    <div class="left">Left Content</div>
    <div class="right">Right Content</div>
</div>

To achieve this expansion/reduction effect, here is the JavaScript code:

$("#button1").click(function(){
    var inputValue=$("#button1").attr('value');

    if(inputValue=="Expand")
    {
        $(".right").animate({width:"60%"});
        $("#button1").attr('value','Reduce');
    }
    else if(inputValue=="Reduce")
    {
        $(".right").animate({width:"38%"});
        $("#button1").attr('value','Expand');
    }
});

Currently, when expanding the right div, it goes underneath the left div. My goal is for the left div to adjust its width accordingly, taking up the remaining space within the parent so that both divs stay side by side.

You can view and interact with the layout on JSFiddle.

I believe there might be a CSS solution to handle the resizing of the left div without relying entirely on JavaScript. Any suggestions or tips would be greatly appreciated!

Answer №1

There was an issue with the sizing of your left div which caused your container to exceed 100%. I have made the necessary adjustments below:

$("#button1").click(function(){
    var inputValue=$("#button1").attr('value');
    
    if(inputValue=="Expand")
    {
        $(".right").animate({width:"60%"});
        $(".left").animate({width:"38%"});
        $("#button1").attr('value','Reduce');
    }
    else if(inputValue=="Reduce")
    {
        $(".right").animate({width:"38%"});
        $(".left").animate({width:"60%"});
        $("#button1").attr('value','Expand');
    }
});
.parent{
  width: 100%;
  border: 1px solid blue;
  padding: 2px;
  float: left;
}
.left{
  width: 60%;
  float: left;
  border: 1px solid red;
}

.right{
  width: 38%;
  border: 1px solid orange;
  float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" class="toggle_div" id="button1" value="Expand"/><br>
<div class="parent">
<div class="left">Left Content</div>
<div class="right">Right Content</div>
</div>

Answer №2

Personally, I don't think it's perfect, but perhaps something along the lines of http://jsfiddle.net/fd9pos8m/? It's not as seamless as I'd like it to be though.

<div style="padding:2px; width:500px; background: #FFFFFF ">
    <div class="left" style="float:left; width:50%; background: #ff0000 ">Left Content</div>
    <div class="right" style="margin-left:52%; width:38%; background: #000000 ">Right</div>
    <div style="clear:both"></div>

    <input type="button" id="button1" value="expand">
</div>
<script>
$('#button1').click(function(){
            var val = $(this).val();
            if(val == 'expand') {
                $('.right').animate({width:'60%'});
                $(this).val('reduce');
            } else {
                $('.right').animate({width:'38%'});
                $(this).val('expand');
            }
        });
</script>

Answer №3

Would you like to test this solution? http://jsfiddle.net/CFNUJ/917/ the CSS code for #right-bg { is aligned with #left-bg

The first method utilizes only CSS styling.

Answer №4

Have you considered utilizing the power of CSS flexbox? It eliminates the need to worry about elements jumping down when there isn't enough space, as it automatically handles such scenarios for you.

Just make sure to double-check the browser support for flexbox before implementing it.

Below is a snippet of the modified CSS code:

.parent{
  width: 100%;
  border: 1px solid blue;
  padding: 2px;
  display: flex;
}
.left{
  width: 60%;
  border: 1px solid red;
}

.right{
  width: 38%;
  border: 1px solid orange;
}

You can view the example on jsfiddle here

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

Setting a checkbox to true within the MUI Data Grid using my input onChange event - how can I achieve this?

I am looking to highlight the selected row in my usage input onChange event. https://i.stack.imgur.com/rp9rW.png Details of Columns: const columns = [ { field: 'part_code', headerName: 'Part Code', width: 200 }, { ...

How can I dynamically populate a multiple select box with data from a PHP query and store it in a multidimensional array using jQuery?

I apologize for any language barriers as English is not my first language. My query is as follows, I am looking to implement three multiple select boxes on a single page. How can I retrieve query data before it is executed in PHP? Each loop result will be ...

Utilizing Axios for Vue Multiselect on select/enter Event

I have successfully implemented a Vue Multiselect feature that retrieves options from my database using an axios call. This functionality works great as it allows users to select existing options or add new ones to create tags. While this setup is working ...

Establish the condition if the array is present

I am looking to conditionally set a state based on the existence of data retrieved from the server. const [names, setNames] = useState([...details?.names]) The details object is passed in as props and fetched from the database. The array details.names com ...

What is the best method for web scraping from the NVIDIA website using Python?

My current setup involves the utilization of BeautifulSoup4 and requests for web scraping. from bs4 import BeautifulSoup import requests url_NVIDIAGEFORCE = f'https://shop.nvidia.com/de-de/geforce/store/gpu/?page=1&limit=9&locale=de-de&ca ...

"div p" or "div * p"? Do they have the same meaning or is there a difference between them?

My knowledge of the "grandchild" selector in CSS was limited until I came across this insightful article. Intrigued, I decided to experiment with it and found that it resembles the universal selector (which targets all elements). Let's take a look at ...

Canvas Delays in Clearing Background

It appears to be a straightforward issue, and I might just be missing something obvious. Here is the code snippet: window.onresize = function(){ init.canvas.width = window.innerWidth; init.canvas.height = window.innerHeight; } var init = { canvas: n ...

What is the process for establishing a connection between a websocket and an external API?

Currently, I have a route configured to fetch the weather data for a specific city using the openweathermap API Here is the code snippet from my index.js file: var express = require("express"), router = express.Router(); var weather = require("ope ...

Once the page is refreshed, the checkbox should remain in its current state and

I have a challenge with disabling all checkboxes on my page using Angular-Js and JQuery. After clicking on a checkbox, I want to disable all checkboxes but preserve their state after reloading the page. Here is an example of the code snippet: $('# ...

When moving the cursor quickly, a vertical line does not appear upon hover

I am facing an issue with the vue-chartJs library. When I move the cursor fast, the vertical line on hover does not show up. However, when I move the cursor slowly, it works perfectly. Can anyone offer assistance in solving this problem? onHover: functi ...

Are there any reliable sources for a complete list of browser CSS properties?

Is there a way to easily access a comprehensive list of CSS properties supported by specific browsers, particularly IE8? Any suggestions on where I can find this information? ...

Leveraging the power of ES6 syntax in Node scripts with Babel

My npm CLI tool utilizes ES6 syntax from BabelJS, specifically arrow functions. Within the entry point of my tool, I'm using the following require: require('babel-core/register'); var program = require('./modules/program.js'); I ...

Performing two consecutive nested AJAX requests in jQuery using JavaScript

I am facing an issue with my code. My goal is to create a cryptocurrency ranking feature on my website. I have integrated an API that provides logos, symbols, indices, prices, etc. of cryptocurrencies. However, I encountered a problem as this API doesn&apo ...

The hover effect is not functioning properly after loading jQuery with load();

When loading elements into a div using the load() function, I noticed that the :hover effect in CSS stops working for those elements. It's a dynamic menu setup, as shown below: <div id='main-menu'> <ul> <li class='click ...

The side button is not functioning properly on IE Edge

Objective: The button on the right side should be functional in the latest versions of IE, Chrome, and Firefox. Challenge: It currently works in Chrome and Firefox but not in Edge. The code is extracted from this webpage () and functions perfectly wel ...

iPad2 always displays UIWebView in 'portrait' orientation

I have a sophisticated HTML5 website that includes JavaScript. It is displayed in a UIWebView. The JavaScript on the page is supposed to determine whether the iPad is in Portrait or Landscape mode. Unfortunately, I have encountered an issue. Regardless of ...

When trying to apply styles using ng-style attribute with jQuery, Angular does not seem to

Check out this plunker showcasing the issue : http://plnkr.co/edit/1ceWH9o2WNVnUUoWE6Gm Take a look at the code : var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { console.log('yeah'); ...

Creating a Bootstrap 4 table that utilizes the full width while maintaining responsiveness

Is it feasible to implement a table-responsive solution that adjusts column width based on the length of data within each column, while still allowing the thead to occupy the entire canvas width? For Example: (the last column with no content should take u ...

Reloading issue with NextJs when utilizing next-i18next for translations on a specific

Having trouble with next-i18next in my app. Implemented everything correctly, but the layout keeps rerendering on pages with getStaticProps. Need to find a way to prevent this. Created a file named withStaticTranslations.ts for pages, but when trying to l ...

When you zoom in or out, HTML5 elements styled with CSS will dynamically adjust

Hey everyone, I have a question about a problem I'm facing with my HTML and CSS page. The issue is that when I zoom in, the "Section" part moves underneath the nav bar, and when I zoom out, the footer moves next to the section part... Below is a sni ...