Creating a Parent Container to Maintain the Height of the Tallest Offspring

I've been searching online for solutions, but so far I haven't found one that meets all the requirements.

<div class="parent">
    <div class="child1">I am 60px tall and always visible; my parent is 100px tall</div>
    <div class="child2">I am 80px tall and initially hidden until needed</div>
    <div class="child3">I am 100px tall and also hidden until needed</div>
</div>
  • I need to have multiple child Divs within a parent Div.
  • Only one child should be displayed at a time.
  • The height of the parent Div must match the height of the tallest child and not change.

I plan to use jQuery to handle toggling between the visible children, but I would prefer a CSS-based solution for setting the heights if possible.

No need to support IE8/9/10.

Does anyone have any suggestions?

Answer №1

Here is the solution you need:

  1. Utilize the flex display property to organize the child elements in a column layout.
  2. Adjust the opacity of the child elements to 0, ensuring they remain within the parent div and setting the parent's height equal to the tallest child element.
  3. Create a new CSS class called visible to style the visible child element. The default hidden children should have a width of 0px, while the visible child will expand to 100% width.

function show(element) {
  $('.parent div').removeClass('visible');
  $('.' + element).addClass('visible');
}
.parent {
  border: 1px dashed #000;
  display: flex;
}

.child1 {
  height: 60px;
  background: red;
}

.child2 {
  height: 80px;
  background: yellow;
}

.child3 {
  height: 100px;
  background: orange;
}

.parent div {
  opacity: 0;
  width: 0px;
}

.parent div.visible {
  opacity: 1;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <div class="child1 visible">I'm 60px tall and visible; my parent is 100px tall</div>
  <div class="child2">I'm 80px tall and hidden until needed</div>
  <div class="child3">I'm 100px tall and hidden until needed</div>
</div>

<br/>
<button onclick="show('child1')">Child 1</button>
<button onclick="show('child2')">Child 2</button>
<button onclick="show('child3')">Child 3</button>

Answer №2

How to conceal elements using the opacity property by setting it to 0 for hidden and 1 for visible, while ensuring that the parent container adjusts its height based on the tallest child.

Refer to the code snippet below for implementation:

$(function(){ 
  $(".c").fadeTo(0,0);
  $(".child1").fadeTo(0,1).addClass("visible");
  $(".btn").click(function(){
    $(".c").fadeTo(0,0);
    $(".visible").removeClass("visible").next().fadeTo(0,1).addClass("visible");
  });
});
.parent { position:relative; border:2px solid red; display:flex  }
.c { border:2px solid blue; }
.child1 { height:60px; }
.child2 { height:80px; }
.child3 { height:100px; }
<div class="parent">
    <div class="c child1">I'm 60px tall and visible; my parent is 100px tall</div>
    <div class="c child2">I'm 80px tall and hidden until needed</div>
    <div class="c child3">I'm 100px tall and hidden until needed</div>
</div>

<button class="btn">Show Next Child</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

Encountering an error while trying to execute `$(document).ready(function() {}

Recently, I delved into the world of JavaScript, particularly Jquery. As I encountered the $(document).ready(function() {}); statement and added it to my code, I faced an issue when placing it within the header tag of my HTML. The script tag would display ...

What could be causing my iframe to not adjust its size according to its content?

My attempt at resizing a cross-site iframe is not working as expected, despite following the guidance provided here. The iframe on my page seems to remain unaltered in size, and I can't figure out what mistake I might be making. The current location ...

Run the setInterval function immediately on the first iteration without any delay

Is there a way to display the value immediately the first time? I want to retrieve the value without delay on the first load and then refresh it in the background. <script> function ajax() { ...

Tips for refreshing information in the Angular front-end Grid system?

I am currently working with the Angular UI Grid. The HTML code snippet in my file looks like this. <div ui-grid="gridOptions"></div> In my controller, I have the following JavaScript code. $scope.values = [{ id: 0, name: 'Erik&a ...

I am looking for a way to display multiple images when the user clicks a button. It needs to be done

After successfully implementing a draggable single circle image when clicking a button, I am now looking to add multiple circle images each time the button is clicked. I'm considering using the append function with the canvas tag for this purpose. Ca ...

Creating methods in Vue that can alter elements created during the mounted lifecycle hook can be achieved by defining functions

I am trying to implement a button that can recenter the canvas. The idea is that when the button is clicked, it will trigger the rec() method which should reposition the canvas that was created in the mounted() function. However, this setup is not working ...

Enhance Your Images: Creating Stunning Colored Overlay Effects using HTML and CSS

I'm currently working on implementing an overlay effect for images on a webpage. The idea is that when the cursor hovers over an image, it will change color slightly. However, I'm facing some issues and the desired effect is not reflecting. How c ...

Guide to authenticating Cashfree gateway's webhook signature using JavaScript

I have integrated the Cashfree payments gateway successfully. However, I am unsure how to verify the signature of webhooks. https://i.stack.imgur.com/TxdTx.png This is their recommended approach. Could someone guide me on writing JavaScript code for this ...

Click to Rotate the Shape

I am attempting to apply a rotation effect on a shape when clicked using jQuery and CSS. My goal is to select the element with the id of x and toggle the class rotate on and off. The rotate class utilizes the CSS transform property to achieve the desired r ...

Is there a way to utilize and incorporate Functions from a separate file within an API Server file?

I have integrated ReactJS, Firebase, and React Redux into my project. https://github.com/oguzdelioglu/reactPress Currently, I am displaying data from Firestore by utilizing Functions in https://github.com/oguzdelioglu/reactPress/blob/master/src/services/ ...

Tips on customizing styles for Material UI components using CSS override techniques

Currently, I am tackling a project that requires the use of Material UI components. To simplify things, let's focus on a basic functional component that includes two Material UI elements: a Button and a Text Field. import React from 'react'; ...

Sending a variable to a function in JavaScript (winJs) from a different function

Greetings! Currently, I am developing a Windows 8 app using Java Script. function fetchFromLiveProvider(currentList, globalList,value) { feedburnerUrl = currentList.url, feedUrl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&outpu ...

Steps to locate the incorrect text field after a validation error occurs

After creating a form with jQuery validation, I encountered an issue where the validation function did not pass due to certain conditions not being met. My focus now is on highlighting the error input field after failed validation. ...

What is the best way to track and display the window.scrollY value in the console using Next.js

Unfortunately, my ScrollToTop component is not functioning correctly within my app. I have exhausted all possible debugging methods but am still unable to determine why the scrollY value is not being logged as expected. Even after moving the snippet to a ...

Having difficulty sending data to a controller through AJAX in Code Igniter. Can anyone help troubleshoot

I recently started learning PHP OOP and am currently using the Code Igniter framework. I encountered some difficulties in sending data to the controller using AJAX, so I attempted a simple test to check if AJAX was functioning properly, but unfortunately, ...

Tips for preventing real-time changes to list items using the onchange method

I am facing an issue with a list of items that have an Edit button next to them. When I click the Edit button, a modal pops up displaying the name of the item for editing. However, before clicking the save button, the selected item in the list gets changed ...

How to dynamically reduce the number of columns in a textarea using jQuery according to its content

Does anyone know how to make a textarea shrinkwrap the text inside on blur? The default number of columns is 10 or 15 and I want the textarea to adjust its width based on the text content. I have tried the following code: $('textarea').on(&apos ...

Margin ambiguity in a vue.js application

I am facing an issue with my Vue.JS project setup. I want the App.vue to occupy the entire page and have different routes displayed within App.vue using router-view. But, when I try to add a margin to the content of my Game component, the margin seems to ...

The Google Books API has reached its limit for requests

Encountering a rate limit exceeded error from the Google Books API while using this demo: To reproduce, open the developer console in Chrome and perform some searches. The rate limit errors will be displayed in the console. [],"lazyUpdate":null},"status" ...

Utilizing Visual Studio: Implementing jsmin in post-build actions

After attempting to add jsmin.exe as a post-build event in my VS 2010 project, I encountered an "error code 9009" when building the project. I tested this in the command prompt and found that it works if I navigate to the folder and run: jsmin < debug ...