What is preventing my accordion from closing completely?

I'm currently working on creating FAQ questions in an accordion format. However, I've encountered an issue where adding padding around the answer section prevents the accordion from closing completely. Removing the padding solves the problem, but I prefer to have the padding for aesthetic reasons.

Prior to this, everything was functioning perfectly without any issues when the padding was not applied. Once the padding is added back, the collapsed answer still displays a few lines of text, which is not desired.

(The problematic accordion is the final entry on the page labeled "0002.")

The structure and styling code for the page can be seen below:

body {
  font-family: 'work sans', Arial, sans-serif;
  font-size: 14px;
  color: #999;
  margin: 0px;
  padding: 0px;
  background-color: #010101;
  background: url(https://imgur.com/YRl8KNP.png) fixed center;
  background-size: cover;
  text-align: left;
}

/* Additional CSS Code Snippets */

...

This world involves collaborative storytelling efforts where lore-related queries are answered by staff or community members. If you encounter questions related to the world-building aspect, feel free to explore them using the provided quick links or consult the relevant sections within the content.

Remember that your active participation and curiosity contribute to shaping the narrative of this expansive and immersive setting!

Answer №1

To address your initial inquiry, it seems that the .panel div is not closing all the way due to its intrinsic minimum height caused by the top and bottom padding.

A simple way to achieve the desired outcome without major code changes is to nest the text within a child div of .panel and transfer the padding property (and optionally the line-height property) to this nested element, named .panel__content.

div.panel {
  margin:10px 30px 20px 30px;
  background:rgba(0,0,0,0.3);
  display:block;
  max-height: 0;
  overflow: hidden;
  transition: 0.2s ease-out;
}

.panel__content{
  padding:40px;
  line-height: 170%;
}
<div class="panel">
  <div class="panel__content">English has now emerged as the predominant language globally, yet with easy access to information, one can learn any language, even those considered extinct! Linguistic diversity thrives in today's world, with many individuals being bilingual. The top three languages spoken in City 0023 are English, French, and Chinese.</div>
</div>

See working example on JSFiddle


Additional Notes:

  1. I recommend validating your HTML and CSS to resolve existing errors. Use W3C's online validators for best results:

  2. You might exclude the use of div in your .panel selector for a more concise approach. Shorter selectors are generally preferred.

  3. The display:block; property may be unnecessary for .panel, as divs default to block-level elements.

Answer №2

Here's a suggestion to enhance your panel:

box-sizing: border-box;

This addition will ensure that the padding is included in the height calculation. If necessary, you can make adjustments to other properties if there are slight shifts. Alternatively, you could consider setting the padding top and bottom to 0 when the panel is closed, and smoothly transition these values when collapsing.

Answer №3

When it comes to CSS, the max-height property takes precedence over the height property. However, keep in mind that any padding specified for the top and bottom will be added to the total height of the element when the CSS is compiled. In this case, the final height will be 80px.

To address this issue, adjust the padding as follows:

div.panel { padding: 0 40px; }

Furthermore, make sure to update your script accordingly:

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
      panel.style.paddingTop = 0;
      panel.style.paddingBottom = 0;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
      panel.style.paddingTop = null;
      panel.style.paddingBottom = null;
    } 
  })
}

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 process for incorporating a custom script into a pre-existing node.js library?

I am facing a challenge with integrating a personal script with custom functions into my local copy of the hls.js library. How can I successfully add a new script to the library and then utilize the functions written within it? To provide context, let&apos ...

Verifying password authenticity using AngularJS

Hi there! I'm currently troubleshooting some code that is meant to validate passwords with specific requirements, such as having a certain length and containing special characters. I've managed to set the correct password length, but I'm en ...

After a group of floated items, there will be an automatic "clear: both" applied

Within my Content Management System, I have custom Elements that need to be floated next to each other. Instead of adding an extra div with a class of "clear", I want to automatically insert a clear: both at the end using CSS3. I attempted this workaround ...

What is the process for utilizing SWR to display information from a GraphQL Apollo Server within a NextJS application?

While I can successfully access my GraphQL query using apollo-graphql-studio, and the resolver is configured correctly, I am facing difficulty in rendering the data. Being aware of the performance benefits of swr react-hook in next-js, I intend to fetch d ...

Updating front end data using Node.js - A Comprehensive Guide

I am looking to create a website using node.js that can dynamically display a plot and update the data every minute without needing to refresh the entire page. As someone new to node.js, I am interested in learning how to use "get" requests to update the d ...

Selecting JavaScript Libraries During the Development of a Web Application

Transitioning from PHP & Java/Android development to web app development can feel overwhelming, especially with the abundance of Javascript Frameworks available. Check out this comparison of popular JavaScript frameworks View a list of the top JavaSc ...

After attempting to install @mui/system, I encountered an error. I decided to uninstall it, but now I am consistently facing this

ERROR in ./node_modules/@mui/material/Unstable_Grid2/Grid2.js 6:14-25 export 'createGrid' (imported as 'createGrid2') was not found in '@mui/system/Unstable_Grid' (module has no exports). Encountering an issue after installin ...

The onChange method seems to be malfunctioning when used with radio buttons

I'm having an issue with my form's radio button. It is supposed to do something when the selected item changes, but it only works when the page first loads and not when I select a different item. Below is the code snippet: <div key={item} cla ...

Creating a dynamic shift in background color

Is it possible to use jQuery to slowly change the color of diagonal lines in a background styled with CSS, while also adding a fading effect? I have created a fiddle with the necessary CSS to display a static background. You can view it here: http://jsfid ...

Next.js fails to refresh the content upon initial view

Snippet from my index.js file: import Post from "@/components/Post" import Modal from "@/components/Modal" import {useState} from "react" export default function Home() { // Setting up states const [modalTitle, setModalTitle] = useState('Title&a ...

Error: Bootstrap 4 Container Size Issue

I am having an issue with the width of my footer when using a Bootstrap 4 "Container". The Container does not cover the entire bottom of the screen as expected. Even changing it to Container-Fluid does not resolve the issue. For reference, here is a JSFid ...

Using a conditional statement to wrap a react Route

Currently, I am facing a challenge while working with react router. Initially, I had two distinct components being rendered under the same route - one with a parameter and one without (this was how the routes were distinguished). Now, my goal is to add opt ...

The parameters used in the json.parse function in javascript may be difficult to interpret

Currently, I am examining a JavaScript file on this website. It contains the following code: let source = fs.readFileSync("contracts.json"); let contracts = JSON.parse(source)["contracts"]; I'm curious about what exactly the JSON.parse function is d ...

Enhance your website with the jQuery autocomplete feature, complete with

Is there a way to incorporate smaller text descriptions alongside the search results displayed on my website? The descriptions are available in the data array used by autocomplete and can be accessed using the .result function by calling item.description. ...

Merge arrays to form nested structures

Here's a mind-bending scenario for you. Imagine I have two arrays - one containing categories and the other containing arrays that follow the structure of those categories. For example: var categoryArray = ["Name", "Title", "Hire Date"]; var infoArr ...

Stop the inheritance of CSS and JavaScript in ASCX files

Currently, I have an application that consists of only one aspx page called Default.aspx. This page dynamically loads .ascx controls as required, all of which utilize the same JS and CSS file. I am now considering implementing Bootstrap on specific control ...

Is there a way to enclose a mention within a unique span tag after highlighting it? Similar to how tags are implemented on platforms such

Currently utilizing an AngularJS plugin called ment.io for incorporating mentions. However, I am having difficulty figuring out how to customize the appearance of the selected mention. For example, in Stackoverflow: https://i.sstatic.net/bZrkh.png Or i ...

Divide Angular ngFor into separate divs

Here is an example of my current array: [a, b, c, d, e, f, g, h, i] I am aiming to iterate through it using ngFor and split it into groups of 3 elements. The desired output should look like this: <div class="wrapper"> <div class="main"> ...

Exploring the concept of $http/$q/promise in Angular

I am struggling to understand when $q/$http should trigger the onReject block. For example, if I have a simple call like this: $http.get('/users') .then(function(res) { return res.data; }, function(err) { console.log(err); }); If ...

What methods can be used to ensure a required minimum delay time between function executions?

For my node function, I am aiming for a specific execution delay of around 5 seconds. The minimum delay needs to be implemented within the function itself, not externally, so external users are unaware of the delay. Therefore, I cannot rely on modules l ...