Creating the CSS Accordion Effect

accordion effect css accordion effect 2


There is a quick and easy way to making a content accordion such as the one pictured above using purely CSS. Most people already know how to get this type of thing running with Javascript and CSS together and it looks a little nicer that way, but this solution is perfect for all the users who don't allow scripts to run while browsing the web.

There are a couple things to note with this implementation. The first is that it doesn't work right in many of the very old browsers out there, particularly Internet Explorer. This code also requires your users to be using a mouse to read all the content which is something else that you should consider.

Let's start with the XHTML first.

<div id="accord">
<div id="section1">
<p><h2>Section 1</h2></p>
</div>
<div id="section2">
<p><h2>Section 2</h2></p>
</div>
<div id="section3">
<p><h2>Section 3</h2></p>
</div>
<div id="section4">
<p><h2>Section 4</h2></p>
</div>
</div>

This just builds the main accordion div and defines four different section id's so that you can alter the appearance of each one.

#accord {
width: 500px;
margin: 100px auto; }

Here we are defining the width of the full accordion and centering it by giving it a nice margin.

#accord div {
float: left;
width:25%;
height: 300px;
overflow: hidden;
}

This compacts all the divs over to the left. It also sets the height of the whole div to 340 pixels. The width of the sections is set to 25% because there are four of them, if there were ten it would be set to 10%. The most important part of this code is the overflow portion. It makes sure that any part of the sections that are being pushed out of the div disappear. It makes sure that no part of the other sections visibly extend out of the div.

#accord:hover div { width: 20px; }/

This piece of code tells each of the three sections to shrink down when they are within the expanding section that we are hovering over. This is what makes them contract and makes it look animated.

#accord:hoverdiv:hover {
width: 440px;
overflow: auto; }

Here we tell any div inside of accord to expand when we hover over it and we set the width to 400 pixels which is just the total width minus the width of the three contracted sections.

#section1 {
background-color: #35a637; }
#section2 {
background-color: #ce1a4c; }
#section3 {
background-color: #36b8e6; }
#section4 {
background-color: #ca8c3d; }

To make the accordion more distinctive this code adds a different color to each of the different sections. This creates a nice visual appeal that will make your visitors more interested in each of the different sections and the content that they contain.