Adjusting the parent with CSS transitions to perfectly align with the final height of a

Jade example

div.parent
    div.child1
    div.child2

Upon initial load, Child1 is visible. Clicking will hide Child1 and make Child2 visible. Another click will reverse this action.

During the transition between hiding and showing the children, there should be a smooth height change from 100% to 0% and vice versa. The parent element should also adjust its height accordingly to match the newly visible child.

Visually, Child1 will appear to roll up while Child2 rolls down, and the parent element will extend or contract based on the final size after transition.

The question then arises: Is it possible to achieve this effect using CSS transitions alone?

Answer №1

Only if the final height of the children is known beforehand, can it be achieved.

var button = document.querySelector('button');
var parent = document.querySelector('.parent');

button.onclick = function(){
  parent.classList.toggle('toggle');
}
.child1,
.child2 {
  height: 100px;
  background: #faa;
  overflow: hidden;
  transition: all .3s;
}

.child2 {
  background: #aff;
  height: 0;
}

.toggle .child1 {
  height: 0;
}

.toggle .child2 {
  height: 100px;
}
<div class="parent">
  <div class="child1">Something here</div>
  <div class="child2">Or here</div>
</div>
<button>Click me</button>

Alternatively, even without knowing the final height, it can still be accomplished, but using this method in pure CSS could be seen as overly complicated and not worth implementing. It involves adding a transition and setting a max-height significantly larger than the actual height, which can cause delays during collapsing due to % calculations based on the difference between X and the height.

In an interesting twist (just for fun), you could also achieve this without JavaScript, although I wouldn't recommend it since it's less clear (typically JS handles these interactions):

.child1,
.child2 {
  height: 100px;
  background: #faa;
  overflow: hidden;
  transition: all .3s;
  cursor: pointer;
}

.child2 {
  background: #aff;
  height: 0;
}

.toggle {
  display: none;
}

:checked ~ .child1 {
  height: 0;
}

:checked ~ .child2 {
  height: 100px;
}
<label>
  <input class="toggle" type="checkbox" name="el" />
  <div class="child1">Click me</div>
  <div class="child2">Now me</div>
</label>

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

Instructions for changing the background color continuously

One of my templates includes the following input: <div class="form-group" LayoutDirective=""> <label>Background color for views</label> <input type="text" name="background_color" id="background_color" ng-model="selectedLayout. ...

Tips on utilizing HTML tags in shiny context to highlight or potentially enlarge the font size for sprintf使

Can anyone help me figure out how to bold or increase the font size for my sprintf in R? I attempted the code below but it didn't work as expected. Instead of bolding the text, the "<strong" tags became part of the label. Any suggestions on how to ...

"Exploring the possibilities of customizing Material UI tabs and implementing a tabs scroller

I'm currently trying to customize the appearance of these MUI tabs, specifically the tab color and bottom border color. Despite my attempts using makeStyles and other methods, I haven't been able to achieve the desired result. https://i.sstatic.n ...

Implementing an interactive tab feature using jQuery UI

Recently, I was working on a project involving HTML and jQuery. Now, my goal is to create a dynamic tab with specific data when a button is clicked. This is my code for the JQuery-UI tab: $(document).ready(function() { var $tabs = $("#container-1 ...

Generating custom-styled entries using Word VBA

I have set up styles in my Word document, such as My_Style (which I use for titles). I am looking to create entries for illustrations that correspond to the number from that particular style. Here is the code snippet I am using: Sub Macro4() ' &apos ...

Encountered a problem while attempting to create two separate div elements. The template root is designed to have only one element. This issue

<template> <div class="footerpart-container"> <div class="general-container"> dadada </div> <div class="legal-container"> dadad </div> <div class="helpsupport-container"> dada ...

Wrapping a series of grids within a parent container to manage height effectively with grid960

Testing on the following browsers: Internet Explorer, Chrome, Firefox; Check out this example of an ideal layout in a PDF: Here is the link to the direct page: While Grid systems work well for width layout, I struggle with setting height constants. In ...

Activating the CSS :active selector for elements other than anchor tags

How can I activate the :active state for non-anchor elements using JavaScript (jQuery)? After reading through Section 5.11.3 of the W3C CSS2 specification in relation to the :hover pseudo selector in hopes of triggering the activation of an element, I stu ...

Why is there a thin line still visible on the other sides when a transparent background is used, but only on mobile devices, with a curved border on one side?

Recently, I've delved into the world of creating CSS art and stumbled upon a peculiar issue with CSS borders that has left me puzzled. When I apply a border to only one side of an element with a transparent background and rounded edges, I notice a fa ...

Disregard the significance of radio buttons - iCheck

I have been attempting to retrieve values from radio buttons (using iCheck), but I am consistently only getting the value from the first radio button, while ignoring the rest. Despite following what seems to be correct code theory, the output is not as exp ...

PDFMAKE: A Guide to Duplicating Elements in the 'Content' Array

I have an Array within Items. My goal is to display them in a Table format using PDFMake. table: { multiple pages headerRows: 2, widths: ['auto', 100, 200, 'auto', 'auto', 'auto'], body: [ ...

"Enhance Your Website with Creative Image Hover Effects using HTML

I'm looking to add a simple hover effect to the images AboutUsLink.png and AboutUsColourLink.png, but I'm unsure of the process. Here is the HTML code: <section class="link1"> <a href="#SecondLink"><img src="images/LogoAndLin ...

What could be causing this jQuery to malfunction?

Having trouble with the functionality of hasclass and this.addclass. if ($('.sidebar-menu-container li').hasClass('current-menu-item')) { $(this).addClass('expanded'); } Check out this CodePen for reference. ...

Pictures change positions in online email interfaces like gmail

Hey there! I'm encountering an issue with the image on my website. The image is contained within a container and seems to extend a bit to the right. Everything looks perfect in all email clients except for web-based ones like Hotmail and Gmail. Here a ...

Unexpected behavior with HTML Bootstrap's dl-horizontal layout

Despite having the div class "dl-horizontal" within the table, the dl-horizontal fields are displaying outside the table. Here is the code I used: <!DOCTYPE html> <html lang="en> <head> <title>Bootstrap Example</title> ...

Navigating Liferay Portlet in reverse order

I am facing an issue with right to left alignment in my portlet. It displays correctly when tested on a regular HTML page, but switches to left to right alignment when integrated into a Liferay portlet. Below is the code snippet causing this problem: < ...

Encountering issues with the hyperlink tag '<a>' in an HTML document

I've encountered an issue with the code on my HTML page: <body> <div align="center"> <a href="../index.html"> <img border="0" src="banner1.jpg" width="800" height="120" alt="Ecommerce Knowledge Base"> &l ...

Is it possible to use the HTML script tag without specifying the type attribute as JavaScript? <script type="text/html"></script>?

While examining the source code of an HTML page, I stumbled upon the following snippet: <script id="searchItemTemplate" type="text/html"> <# var rows = Math.floor((Model.RecordsPerPage - 1) / 3 + 1); for (var i = 0; i < rows; ++i){ ...

What is the best way to ensure that a header with SVG graphics is SEO-friendly and accessible to screen readers?

My website currently features an <h1> tag with an SVG logo, but unfortunately it is not accessible to webcrawlers and screen readers. What steps can I take to ensure that it can be properly accessed by them? ...

Postback does not show updates made by JQuery

On Page_Load, I have two asp:BulletedLists - one is already filled with data while the other remains empty. Users have the ability to drag and drop <li>'s between these lists using the following function: function Move(element, source, target) ...