Thursday, 6 September 2012

Add popups to your links with CSS3 and HTML5

Here are some styles for making some fancy links using pure CSS3 and HTML5 (data- attributes) without using any additional tags for layout. They make use of the ::before and ::after pseudo-elements as discussed in one of my recent posts in Growing with the Web.

The styles are compatible with the latest Chrome, Firefox, Opera, Safari as well as IE9. They also degrade gracefully by simply not displaying the popup to IE8 and below.

CSS

a[data-popup] {
    position: relative;
    display: inline-block; 
}

a[data-popup]:hover::after {
    content: attr(data-popup);
    display: block;
    position: absolute;
    background: black;
    opacity: 0.75;
    min-width: 70px;
    max-width: 250px;
    white-space: pre;
    padding: 8px;
    top: 35px;
    color: white; 
    z-index: 100;
}

a[data-popup]:hover::before {
    content: " ";
    display: block;
    position: absolute;
    bottom: 0;
    border-left: 15px solid transparent;
    border-right: 15px solid transparent;
    border-bottom: 15px solid black;
    opacity: 0.75;
    top: 20px;
    left: 20px; 
}

SASS

a[data-popup] {
    $popup-background-color: #000;
    $popup-color: #FFF;
    $popup-opacity: .75;
    $popup-top: 20px; // Should be >= line-height
    $popup-left: 20px;
    $popup-arrow-size: 15px;
    $popup-padding: 8px;

    position: relative;
    display: inline-block; // Fixes links that wrap
    
    &:hover {
        &::after {
            content: attr(data-popup);
            display: block;
            position: absolute;
            background: $popup-background-color;
            opacity: $popup-opacity;
            min-width: ($popup-left + $popup-arrow-size) * 2
            max-width: 250px;
            white-space: pre;
            padding: $popup-padding;
            top: $popup-top + $popup-arrow-size;
            color: $popup-color;
            z-index: 100; // We want this on top of everything
        }

        &::before {
            content: " ";
            display: block;
            position: absolute;
            bottom: 0;
            border-left: $popup-arrow-size solid transparent;
            border-right: $popup-arrow-size solid transparent;
            border-bottom: $popup-arrow-size solid $popup-background-color;
            opacity: $popup-opacity;
            top: $popup-top;
            left: $popup-left;  
        }
    }
}