Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS Create an Accordion Menu with CSS

Jim McQuarrie
Jim McQuarrie
10,597 Points

adding up down arrow img

I need to add an image on the left which is easy, but I also need it to change when the tab is clicked and open and then back again when clicked to close, live an up and down arrow or a plus munus sign. I also need the colors to change when open vs closed.

can this be done in CSS? or would I need a jQuery script?

Thanks,

Jim

3 Answers

Per Karlsson
Per Karlsson
12,683 Points

Hi Jim,

I've made a simple example for you how to toggle a picture with a little bit of CSS and a little bit of jQuery.

Hope it gives you some inspiration!

Here's some CSS that will add a little plus/minus sign that changes as you open/close:

.tab label::before,
.tab label::after {
  content: "";
  position: absolute;
  display: block;
  width: 16px;
  height: 4px;
  background: white;
  right: 8px;
  top: 22px;
  transition: transform 0.35s;
}

.tab label::after {
  transform: rotate(90deg);
}

.tab input:focus + label,
.tab label:hover {
  background: #85d8ce; /* color is already changing on focus/hover, change this value to something different to see */
  letter-spacing: 1px;
}

.tab input:focus + label::after {
  transform: rotate(180deg);
}

Note that the minus sign won't close the tab again, but as someone suggested elsewhere on the forums, you could change the radio inputs to checkboxes to achieve this, but you wouldn't get tabs closing when another is selected (so multiple can be open).

Let me know if that's what you're looking to do and I'll see if I can whip up some example CSS.

As Iain says in his comment above the minus sign won't close the tab. You could instead do something more reflective of what the behavior is, instead, having a "+" sign on tabs when they aren't active and hiding it when they are. So you might end up with something like this instead:

.tab label::after {
  content: "+";
  position: absolute;
  right: 15px;
  width: 15px;
   transition: content .75s;
}

.tab input:checked ~ label::after {
    content: "";
}

And if you wanted to enhance it on hover you could maybe do something like this:

.tab label::after {
  content: "+";
  position: absolute;
  right: 15px;
  width: 15px;
  transition: all .75s;
  opacity: .7;
}

.tab label:hover:after {
  opacity: 1;
}

.tab input:checked ~ label::after {
    content: "";
}