CSS3 - Generated Content

CSS3 - Generated Content

by Colin Soderstrom

HTML

<div class="container">
    <span data-title="I have an awesome title!!!">I am</span>
    <span data-title="These titles are shown using CSS only!!! No Javascript is used">I am</span>
    <span data-title="Hello World">I am</span>
    <span data-title="Generated Content is awesome!!!">I am</span>    
</div>

CSS

.container {
    /* Set a counter named  cnt to 0 */
    counter-reset: cnt;
    
    position: relative;
    text-align: center;
    padding: 20px 0;
    width: 420px;
    height: 160px;
    margin: 0 auto;
}

/* You can style pseudo-elements and give them content as if they were real elements on the page */

.container::before {
    display: block;
    content: 'Hover over these items.';
    font-size: 18px;
    font-weight: bold;
    text-align:center;
    padding: 15px;
}

.container span {
    display: inline-block;
    padding: 2px 6px;
    background-color:#78CCD2;
	color:#186C72;
	border-radius:4px;
	margin:3px;
	cursor:default;
}

/* Create a counter with a pseudo-element */
.container span::after {
    /* Every time this rule is executed the counter value is increased by 1 */
    counter-increment: cnt;
    
    /* Add the counter value as part of the content */
    content: ' #' counter(cnt);
    
    display: inline-block;
    padding: 4px;
}

/* Pseudo-elements can even access attributes in their parent elements */
.container span::before {
    position:absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    content: attr(data-title);
    color: #666666;
    
    opacity: 0;
    /*Animate the transistions */
    -webkit-transition: opacity 0.4s;
    transition: opacity 0.4s;
}

.container span:hover::before {
    opacity: 1;
}

JavaScript

/* Helpful article: 
    http://coding.smashingmagazine.com/2013/04/12/css-generated-content-counters/
*/