惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
雷峰网
雷峰网
The Register - Security
The Register - Security
The Cloudflare Blog
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
I
InfoQ
博客园 - 三生石上(FineUI控件)
H
Help Net Security
博客园 - 司徒正美
Vercel News
Vercel News
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
B
Blog
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
L
LangChain Blog
人人都是产品经理
人人都是产品经理
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recorded Future
Recorded Future
小众软件
小众软件
Martin Fowler
Martin Fowler
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Apple Machine Learning Research
Apple Machine Learning Research
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
Y
Y Combinator Blog
V
Visual Studio Blog
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
V
V2EX
Blog — PlanetScale
Blog — PlanetScale

CSS Articles by Temani Afif

Get Ready For the Powerful CSS border-shape Property! | CSS-Tricks Let’s Play With Gap Decorations! How to Control Infinite CSS Animations (Part 2 of 2) How to Control Infinite CSS Animations (Part 1 of 2) Two Circles, One Arrow, and Anchor Positioning Making a Responsive Pyramidal Grid With Modern CSS | CSS-Tricks How to Create a CSS-only Elastic Text Effect Making Complex CSS Shapes Using shape() | CSS-Tricks Responsive Hexagon Grid Using Modern CSS | CSS-Tricks Responsive List of Avatars Using Modern CSS (Part 2) | CSS-Tricks Responsive List of Avatars Using Modern CSS (Part 1) | CSS-Tricks Perfectly Pointed Tooltips: To The Corners Perfectly Pointed Tooltips: All Four Sides Perfectly Pointed Tooltips: A Foundation Sequential linear() Animation With N Elements | CSS-Tricks Infinite Marquee Animation using Modern CSS Better CSS Shapes Using shape() — Part 4: Close and Move | CSS-Tricks Drawing CSS Shapes using corner-shape Better CSS Shapes Using shape() — Part 3: Curves | CSS-Tricks Better CSS Shapes Using shape() — Part 2: More on Arcs | CSS-Tricks Better CSS Shapes Using shape() — Part 1: Lines and Arcs | CSS-Tricks Creating Blob Shapes using clip-path: shape() Creating Flower Shapes using clip-path: shape() Custom progress element using the attr() function A CSS-Only Star Rating Component and More! (Part 2) | CSS-Tricks A CSS-Only Star Rating Component and More! (Part 1) | CSS-Tricks How to Create Wavy Boxes Using CSS Full-Bleed Layout with Modern CSS Fancy Menu Navigation Using Anchor Positioning | CSS-Tricks How to Create a Zig-Zag Box Using CSS How to Create Zig-Zag CSS Loaders Using One Element Custom Progress Element Using Anchor Positioning & Scroll-Driven Animations How to Create Filling CSS Loaders Using One Element How to Create Curved-Edge and Rounded-Edge Shapes Using CSS CSS Tricks That Use Only One Gradient | CSS-Tricks How to create Shapes with Inner Curves using CSS Mask Custom Range Slider Using Anchor Positioning & Scroll-Driven Animations How to Get the Width/Height of Any Element in Only CSS How Keyboard Navigation Works in a CSS Game How To Create Cut-Out Shapes using The clip-path property The Modern Guide For Making CSS Shapes — Smashing Magazine css-shape.com: The Ultimate Collection of CSS-only Shapes ⚡️ Sliding 3D Image Frames In CSS — Smashing Magazine CSS Tricks To Master The clip-path Property Creating Wavy Circles with Fancy Animations in CSS Modern CSS Tooltips And Speech Bubbles (Part 2) — Smashing Magazine Do you need a Tooltip or a Speech Bubble? I have created 100 using CSS 😲 Modern CSS Tooltips And Speech Bubbles (Part 1) — Smashing Magazine Creating Flower Shapes using CSS Mask & Trigonometric Functions CSS Shapes: The Triangle The Complex But Awesome CSS border-image Property — Smashing Magazine CSS Tricks to add 3D Effects to your Text CSS Responsive Multi-Line Ribbon Shapes (Part 2) — Smashing Magazine CSS Responsive Multi-Line Ribbon Shapes (Part 1) — Smashing Magazine I have made 100+ CSS-only Ribbon Shapes | The Perfect Collection 🎀 How to create a CSS-only infinite scroll animation Re-Creating The Pop-Out Hover Effect With Modern CSS (Part 2) — Smashing Magazine Re-Creating The Pop-Out Hover Effect With Modern CSS (Part 1) — Smashing Magazine How to Create CSS Ribbon Shapes with a Single Element CSS Shapes: The Ribbon Revealing Images With CSS Mask Animations — Smashing Magazine css-loaders.com: The Biggest Collection of Loading Animations (more than 500 🤯) How To Define An Array Of Colors With CSS — Smashing Magazine CSS effects on images II Shines, Perspective, And Rotations: Fancy CSS 3D Effects For Images — Smashing Magazine What's your Lucky CSS Pattern? Check It Now! How to Add a CSS Reveal Animation to Your Images Modern Layouts using CSS Grid I created 100+ unique CSS patterns | The best collection 🤩 How to Create a Custom Range Slider Using CSS CSS Shapes: The Heart CSS Shapes: Polygon & Starburst A Text Reveal Animation using CSS CSS Tip: learn CSS the easy way! How to create Breadcrumb Navigation with CSS Different Ways to Get CSS Gradient Shadows | CSS-Tricks A CSS-only responsive Stepper component A Fancy Hover Effect For Your Avatar | CSS-Tricks How to make a zoom effect using CSS Creating a Custom Cursor using CSS CSS Infinite 3D Sliders | CSS-Tricks CSS Infinite Slider Flipping Through Polaroid Images | CSS-Tricks How to create a responsive sidebar menu using CSS CSS Infinite and Circular Rotating Image Slider | CSS-Tricks Making Static Noise From a Weird CSS Gradient Bug | CSS-Tricks CSS Grid and Custom Shapes, Part 3 | CSS-Tricks Fancy Image Decorations: Outlines and Complex Animations | CSS-Tricks Fancy Image Decorations: Masks and Advanced Hover Effects | CSS-Tricks Fancy Image Decorations: Single Element Magic | CSS-Tricks How to create an infinite image slider using CSS How to Create Wavy Shapes & Patterns in CSS | CSS-Tricks How I Made a Pure CSS Puzzle Game | CSS-Tricks How to create a Tooltip/Speech Bubble using CSS CSS Grid and Custom Shapes, Part 2 | CSS-Tricks CSS Grid and Custom Shapes, Part 1 | CSS-Tricks Zooming Images in a Grid Layout | CSS-Tricks How to create a CSS-only loader with one element Exploring CSS Grid’s Implicit Grid and Auto-Placement Powers | CSS-Tricks How to create background pattern using CSS & conic-gradient Single Element Loaders: The Bars | CSS-Tricks
How to build a CSS-only accordion
2023-03-25 · via CSS Articles by Temani Afif

How to build a CSS-only accordion

Written on by Temani AfifWeb Developer

Estimated read time 5 minutes

In this article, we will create an accordion using CSS. Another common component that we create using minimal code. Most of the tricks rely on <input> hacks but we will do something different here.

Overview of the CSS accordion

The above figure illustrates what we are going to build together.

The HTML markup

For this component, the important part will be the HTML. We are going to use the <details> element that already comes with what we want. Our code will look like below:

<div class="accordion">
 <details>
   <summary>Sesame snaps</summary>
   <div> ... </div>
 </details>
 <details>
   <summary>Chocolate bar</summary>
   <div>...</div>
 </details>
 <details>
   <summary>Donut gummies</summary>
   <div>...</div>
 </details> 
</div>

If you run the code and click on the titles you can expand/collapse the content

We are almost done! We already have the functionality of an accordion using a native HTML element.

The <details> HTML element creates a disclosure widget in which information is visible only when the widget is toggled into an "open" state. A summary or label must be provided using the <summary> element. ref

Now, all we need to do is to style it.

40%

💰 40% OFF YOUR FIRST MONTH WITH VERPEX MANAGED HOSTING PLANS FOR WORDPRESS

with the discount code

SERVERS-SALE

Styling the accordion

The <details> element comes with two interesting features that we are going to use to style our accordion.

First, we have the ::marker element which is the small triangle next to the title. Each browser will define a default style to the ::marker that changes when we expand/collapse the element.

Then, we have the open attribute. The latter is automatically added to the element when this one is opened.

overview of the open attribute

We can also explicitly define that attribute if we want the element opened by default.

The open attribute is also useful to target the expanded <details> and apply a specific style to it.

Let’s start with some basic CSS:

details {
  margin: 5px;
  font-size: 18px;
}
details > * {
  padding: .75rem;
}
details > div {
  background: #ddd;
  border-radius: 0 0 5px 5px;
}
summary {
  border-radius: 5px;
  font-size: 20px;
  font-family: sans-serif;
  font-weight: bold;
  color: #fff;
  background: #0B486B;
  cursor: pointer;
}
details[open] summary {
  border-radius: 5px 5px 0 0;
}

Nothing complex so far. A few color and font changes for a good-looking accordion:

Notice the use of

details[open] summary {
  border-radius: 5px 5px 0 0;
}

This allows me to define a different border-radius for the <summary> element when the <details> is opened.

Now let’s update the ::marker. To do this, we have two methods

The first one is to override the content like the below:

summary::marker {
  content: "+";
}
summary[open]::marker {
  content: "-";
}

This method is the easiest one but it’s limited. We can change the arrow with any character we want (even an emoji) but we cannot style it like we want due to some restrictions related to the ::marker element.

Only certain CSS properties can be used in a rule with ::marker as a selector: ref

To overcome this limitation we can rely on the second method. We start by making the content of ::marker empty

summary::marker {
  content: "";
}

Then we rely on pseudo-elements to create our own indicator.

details summary::before {
  content:"";
  /* styles when the element is closed */
}
details[open] summary::before {
  /* styles when the element is opened */
}

Now, we can control the CSS as we want. Below is a basic example where I am creating a “plus” and “minus” symbol using gradients (I used the same technique in a previous article)

In addition to the style, I am also changing the position of the indicator to make it on the right. We can also apply some subtle animations to make it look better

I can hear you asking “How to add an animation when open/close the accordion?”. The answer is we cannot but things may change in the future.

Unfortunately, at this time, there's no built-in way to animate the transition between open and closed. ref

We can find some workaround to simulate an animation but for the sake of simplicity, I won’t detail them in this article.

Adding a bit of JavaScript

Now that we have our accordion we can add an optional JavaScript code in case we want to keep only one section opened at a time. There is no relation between the <details> elements and you have probably noticed that we can have all of them open at the same time. If you don’t want such behavior you can add a small JavaScript code:

let details = document.querySelectorAll('.accordion details')

details.forEach(function (d, index) {
  d.onclick = () => {
    details.forEach(function(c, i) {
      index === i ?'':c.removeAttribute('open')
    });
  };
});

We loop through all the details elements and we add an onClick event to each one. Inside the onClick even we perform another loop. For each details element, if it’s different from the clicked one, we remove its open attribute.

Conclusion

The article ends here! We have transformed a simple code into a functional accordion. We didn’t clutter our code with a complex logic. We simply used the native <details> element with a bit of JavaScript at the end. The only drawback is the lack of transition when we open/close each element.

Frequently Asked Questions

Temani Afif

Temani Afif is an expert web developer, a content creator, and a CSS addict. He is the mastermind behind CSS Loaders, CSS Generators, CSS Tip and many other CSS-related websites.

View more posts by Temani Afif