Accordion using only CSS

An accor­dion effect can be achieved using CSS3’s :target pseudo-class, with­out requir­ing JavaScript. Using the pro­pri­etary -webkit-transition prop­erty this accor­dion can also be ani­mated.

Result

CSS3 Accor­dion
Works in browsers that sup­port the :target pseudo-class, see the Quirks Mode com­pat­i­bil­ity tables. Ani­ma­tion works in recent WebKit based browsers.

How To

Each part of the accor­dion has an ID, head­ing and con­tent region. The header includes a link that matches the section’s ID, whilst the con­tent is wrapped in a con­tainer which will con­trol its display.

<div class="accordion">
	<h2>Accordion Demo</h2>
	<div id="one" class="section">
		<h3>
			<a href="#one">Heading 1</a>
		</h3>
		<div>
			<p>Content</p>
		</div>
	</div>
	<div id="two" class="section">
		<h3>
			<a href="#two">Heading 2</a>
		</h3>
		<div>
			<p>Content</p>
		</div>
	</div>
</div>

The CSS then relies on the :target pseudo-class to apply dif­fer­ent styles to the cho­sen sec­tion — increas­ing the height and, in large con­tent cases, alter­ing the over­flow behav­iour to allow scrolling. To ani­mate the open­ing and clos­ing of sec­tions the -webkit-transition prop­erty is needed (doc­u­men­ta­tion), in this case act­ing on the height attribute for a dura­tion of 0.3 sec­onds using the ease-in tim­ing function.

Strip­ping out the styling, the CSS boils down to:

.accordion h3 + div {
	height: 0;
	overflow: hidden;
	-webkit-transition: height 0.3s ease-in;
}

.accordion :target h3 + div {
	height: 100px;
}

.accordion .section.large:target h3 + div {
	overflow: auto;
}

Cri­tique

Obvi­ously this approach has its lim­i­ta­tions. Mul­ti­ple open accor­dions on one page wouldn’t be pos­si­ble — restricted by a URI’s one frag­ment iden­ti­fier limit; as one accor­dion opens the other would lose the tar­get and auto­mat­i­cally close. Sim­i­larly, pages that use a frag­ment iden­ti­fier for every­day use will notice odd­i­ties — take for instance when using top links to return to the top of the page, any accor­dion would, in this case, reset. Other uses include acces­si­bil­ity links and sim­u­lated page his­to­ries when using Ajax.

5 Comments

  1. Alejandro

    Check http://​aranedaale​jan​dro​.word​press​.com for another CSS only accor­dion menu (last ver­sion with slid­ding effect with SMIL for IE and CSS3 tran­si­tions for the rest)

  2. Juegos

    Love it, thank you for this trick. Your effort is appreciated.

  3. Greg Babula

    this is great, thanks!

  4. Deepak Kaletha

    Great Arti­cle … thnks

  5. biner

    good,非常好!