Add A Caption To An Image Using :before and :after
Step By Step Guide
Step One
Add the images in an unordered list and add a title to each list item that will be used as the caption
Code
HTML
- <ul>
- <li title="Bassenthwaite, Keswick"><img src="image01.jpg" width="200" height="133" alt="Bassenthwaite"></li>
- <li title="Somewhere near Keswick"><img src="image02.jpg" width="200" height="133" alt="Above Keswick"></li>
- <li title="Grizedale, Cumbria"><img src="image03.jpg" width="200" height="133" alt="Grizedale"></li>
- </ul>
CSS
Result
Step Two
Add an id to the <ul> tag so we can style it seperately from other unordered lists
Code
HTML
- <ul id="caption">
- <li title="Bassenthwaite, Keswick"><img src="image01.jpg" width="200" height="133" alt="Bassenthwaite"></li>
- <li title="Somewhere near Keswick"><img src="image02.jpg" width="200" height="133" alt="Above Keswick"></li>
- <li title="Grizedale, Cumbria"><img src="image03.jpg" width="200" height="133" alt="Grizedale"></li>
- </ul>
CSS
- ul#caption {
- list-style-type:none;
- }
- l#caption li{
- display:inline-block;
- padding:0 20px;
- font-size:90%;
- font-family:'droid sans', sans-serif; /*Droid Sans is available at Google Webfonts*/
- color:#525252;
- text-align:center;
- }
- #caption img{
- -webkit-box-shadow: 2px 2px 10px #919191;
- -moz-box-shadow: 2px 2px 10px #919191;
- box-shadow: 2px 2px 10px #919191;
- }
Result
Step Three
Add a class to each list item, 'above' or 'below' depending on where the caption is to appear
Code
HTML
- <ul id="caption">
- <li class="below" title="Bassenthwaite, Keswick"><img src="../assets/before01.jpg" width="200" height="133" alt="Bassenthwaite"></li>
- <li class="above" title="Somewhere near Keswick"><img src="../assets/before02.jpg" width="200" height="133" alt="Above Keswick"></li>
- <li class="below" title="Grizedale, Cumbria"><img src="../assets/before03.jpg" width="200" height="133" alt="Grizedale"></li>
- </ul>
CSS
- li.below:after{
- content: attr(title);
- display:block;
- }
- li.above:before{
- content: attr(title);
- display:block;
- }
Result
Back to the demo More CSS3 Demos This Way