CSS only accordion divs that are all opened by default with no need for jquery

My current setup involves:

jsfiddle.net/wromLbq5

I would like to enable the functionality of having multiple accordion sections open simultaneously upon page load. This means that when one section is opened, the others should not close. Is there a way to achieve this without the use of javascript?

(Please disregard the sub accordions - I only require a single layer)

HTML

<ul class="accordion">
  <li id="one" class="files">
    <a href="#one">My Files<span>495</span></a>
    <ul class="sub-menu">
      <li><a href="#one"><em>01</em>Dropbox<span>42</span></a></li>
      <li><a href="#one"><em>02</em>Skydrive<span>87</span></a></li>
      <li><a href="#one"><em>03</em>FTP Server<span>366</span></a></li>
        <li><a href="#one"><em>01</em>Dropbox<span>42</span></a></li>
        <li><a href="#one"><em>01</em>Dropbox<span>42</span></a></li>
    </ul>
  </li>
  <li id="two" class="mail">
    <a href="#two">Mail<span>26</span></a>
    <ul class="sub-menu">
      <li><a href="#two"><em>01</em>Hotmail<span>9</span></a></li>
      <li><a href="#two"><em>02</em>Yahoo<span>14</span></a></li>
      <li><a href="#two"><em>03</em>Gmail<span>3</span></a></li>
    </ul>
  </li>
  <li id="three" class="cloud">
    <a href="#three">Cloud<span>58</span></a>
    <ul class="sub-menu">
      <li><a href="#three"><em>01</em>Connect<span>12</span></a></li>
      <li><a href="#three"><em>02</em>Profiles<span>19</span></a></li>
      <li><a href="#three"><em>03</em>Options<span>27</span></a></li>
    </ul>
  </li>
  <li id="four" class="sign">
    <a href="#four">Sign Out</a>
    <ul class="sub-menu">
      <li><a href="#four"><em>01</em>Log Out</a></li>
      <li><a href="#four"><em>02</em>Delete Account</a></li>
      <li><a href="#four"><em>03</em>Freeze Account</a></li>
    </ul>
  </li>
</ul>

CSS

body {margin:50px;}

/* CSS Styles */
/* Add your CSS styles here */

I am trying to accomplish this without any java script. Do you have any suggestions on achieving this?

Answer №1

Unfortunately, achieving this functionality solely with CSS is not possible in this scenario. The CSS3 :target selector you are utilizing changes the target when another item is clicked, making it impossible to maintain the desired state.

While CSS cannot set state, it can style elements accordingly. If you wish to keep each section open after clicking, JavaScript is required. jQuery is not necessary for this task.

If JavaScript is preferred, the following code closely mimics the CSS behavior while allowing the accordions to remain open. Closure of the accordion can be done by clicking on the title once more.

var lists = document.querySelectorAll('.accordion > li > a'); // Retrieve list title links
for (var i = 0; i < lists.length; i++) { // Iterate through each list title link
  lists[i].href = "javascript:void()"; // Prevent page from jumping
  lists[i].onclick = function(e) { // Handle link click event
    var items = e.target.parentNode.querySelectorAll('li'); // Get sibling list items of clicked link
    for (var x = 0; x < items.length; x++) { // Iterate through each list item
      if (items[x].style.height != '33px') { // Check if item is not open
        items[x].style.height = '33px'; // Open item
      } else { // Otherwise
        items[x].style.height = '0px'; // Close item
      }
    }
  };
}

Wrap this code within a script tag and insert it at the end of the body or enclose it in

document.onload = function() {  /*  Script Here  */  }

Feel free to check out the Demo for a visual representation.

Note: Even though styles with the :target selector will no longer work, it is recommended to keep them in the CSS as a backup in case the user has JavaScript disabled.

Answer №2

This particular css code is currently displaying all of the accordions in a closed state by utilizing the following style:

    .accordion li > .sub-menu li {
      height: 0px;
    }

While it is possible to adjust the height to 33px to display all accordions as open when the page loads, this adjustment would disrupt the functionality. This is because the :target selector is responsible for setting the height dynamically, allowing the selected section to appear open.

Therefore, the most viable solution would be to incorporate javascript into the implementation....

Answer №3

Is it achievable? Absolutely

Is it necessary to modify your HTML? Definitely

Is it aesthetically pleasing? Not really

Instead of Target maintaining its state, utilize a checkbox to replace your top-level a tags with label.

body {margin:50px;}
/* Reset */
.accordion,
.accordion ul,
.accordion li,
.accordion label,
.accordion span {
  margin: 0;
  padding: 0;
  border: none;
  outline: none;
}
.accordion li {
  list-style: none;
}... (CSS code continues)
... (HTML code continues)

No need for Javascript!

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

Guide to transforming plain text into HTML format using Angular 4

In my Angular application, I am facing the task of adding a value to an array where the value itself needs to be in HTML format. This means that when the value is displayed, it should render as HTML text. For instance, if someone hovers over the text, I ...

Tips for positioning fixed column headers at the bottom of the header row

I am currently working on a responsive table where the first two columns are fixed and the rest are made to float. However, I have encountered some issues and have a few questions: Why do the headers for the first two columns float to the top of the head ...

What's causing the text not to wrap when using float?

I've tried setting float:left for the image and float:right for the text, but the image is still overlapping the text. What I really want is for the text to wrap around the image - to be on the right side of the image at the beginning and below the i ...

CanvasJS with a see-through background

I am looking to make my CanvasJS background transparent, but I'm having some issues. The backgroundColor property is used in CanvasJS to set the color of the canvas background. When I tried entering "None" instead of a color code, it ended up giving ...

What is the solution to the error message "cannot find specified file or directory, lstat 'scss/'"?

I am currently following a tutorial on YouTube here where the instructor is demonstrating how to run an npm script "sass" file using the terminal. When I try executing the command npm run sass, it gives me an error message: Error: ENOENT: no such file o ...

Modify the background color of the entire page when the main div is clicked

I am attempting to alter the background color of my entire page when the div with id main is clicked. You can view the code here: $(document).ready(function() { var color = 1; $('#main').click(function(){ if (colo ...

Prevent scrolling on both md-sidenav and md-content in AngularJS Material

Currently, I am working on a website using AngularJs Material sidenav. My goal is to make both md-sidenav and md-content appear as one page, without any scroll bars showing up when the height of one element exceeds that of the other. How can I achieve th ...

Arrange divs in a stack when one becomes too full

Struggling to find a pure CSS solution for this issue, so seeking advice. Imagine three divs aligned horizontally next to each other. If one div overflows onto the next line, I want them to switch to a vertical stack layout. How can this be achieved? I h ...

What is the best way to split an array into smaller chunks?

My JavaScript program fetches this array via ajax every second, but the response time for each request is around 3 to 4 seconds. To address this delay, I attempted to split the array into chunks, however, encountered difficulties in completing the task: { ...

Troubleshooting: Issues with AngularJS Data Binding in HTML Tables

I have been working on code from an online tutorial but unfortunately, it is not functioning properly. I have checked the script, app, and controller but still cannot identify the issue. Any assistance would be greatly appreciated! ...

The animation for the Bootstrap modal is not functioning correctly

Whenever I click the button to open the modal window, it just pops up without any animation or fade effect. I attempted to add classes like .fade and .modal-fade to the modal, but nothing changed. You can see it in action on my test page. Simply click th ...

Clashing CSS Styles: Font Size Edition

Can someone explain how CSS font sizes work? I set a specific line to be 200% font size, but changing the body font size affected it. Shouldn't the line maintain its specified size? When the body font size is changed from 12pt to 8pt, the line "There ...

The JavascriptExecutor is unable to access the 'removeAttribute' property of a null object

While utilizing Javascript executor to remove the readonly attribute, I encountered an error message: Cannot read property 'removeAttribute' of null. I came across various discussions where users suggested that removing AdBlock from Chrome solve ...

Pondering in AngularJS - what is the best way to alter the DOM during an AJAX call?

I'm completely new to AngularJS and trying to transition from a jQuery background. After reading through "Thinking in AngularJS if I have a jQuery background?" on Stack Overflow, I understand the concept but am struggling to implement it without depen ...

Bootstrap doesn't display in the dropdown menu

Struggling to get a dropdown menu to display on my page, my HTML code is: <div class="dropdown d-inline"> <div class="widget-header mr-3"> <button href="#" class="icon icon-sm rounded-circle border" data-toggle="dropdown"><i cl ...

Combining several markdown files into a unified HTML document

Is there a way to merge multiple .md files into a single HTML file? I know that Pandoc can convert .md to HTML, but I'm unsure if it's capable of converting multiple files at once. Would I need to create a program to manipulate the tool in orde ...

What is the maximum number of files that FileUploader can accept when multi-select is enabled?

I encountered the following issue: A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll Additional information: Maximum request length exceeded. while attempting to upload 250 JPEG files, each around 98 KB in ...

Dealing with the overflow issue on Android 4.1 using position: relative and position: absolute

I have a question regarding creating a dynamically filling rounded button. I have successfully created an inner div inside the button with absolute positioning at the bottom. It works perfectly on Chrome webview, but I'm facing issues on Android 4.1. ...

Top-notch tools and guides for front-end web development

As I prepare to transition to a new role focused on front-end web development, specifically CSS and jQuery, I am seeking recommendations for valuable resources to enhance my skills in these areas. Whether it be books, websites, blogs, or any other medium, ...

Creating an HTML table from JSON data

Struggling to display real-time statistics in a table on an HTML web page? I have the data in JSON format, but can't seem to get it right. You can find the data at: I attempted the following code snippet, but it was not successful: <!DOCTYPE htm ...