Accordion using only CSS

An accor­dion effect can be achieved using CSS3’s :target pseudo-class, without requir­ing JavaS­cript. Using the pro­pri­et­ary -webkit-transition prop­erty this accor­dion can also be animated.

Res­ult

CSS3 Accor­dion
Works in browsers that sup­port the :target pseudo-class, see the Quirks Mode com­pat­ib­il­ity tables. Anim­a­tion works in recent Web­Kit 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 chosen sec­tion — increas­ing the height and, in large con­tent cases, alter­ing the over­flow beha­viour to allow scrolling. To anim­ate the open­ing and clos­ing of sec­tions the -webkit-transition prop­erty is needed (doc­u­ment­a­tion), in this case act­ing on the height attrib­ute for a dur­a­tion of 0.3 seconds using the ease-in tim­ing function.

Strip­ping out the styl­ing, 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­it­a­tions. Mul­tiple open accor­di­ons on one page wouldn’t be pos­sible — restric­ted 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­ic­ally close. Sim­il­arly, pages that use a frag­ment iden­ti­fier for every­day use will notice oddit­ies — 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 access­ib­il­ity links and sim­u­lated page his­tor­ies when using Ajax.

Post a Comment

Your email is never shared. Required fields are marked *

*
*