Tuesday

CSS Flag Banners


I'm not sure if that's what these things are called, but that's what I'm calling this thing:

Whatever we call it, I did it using only CSS, and thought I'd show how I did so.

Code

Really, it's pretty straight forward; I'm using the :before selector to my element (in this case .date-outer), to add some blank content. I need it to have dimension, so I'll add display: block, and because I want a height of 40px, I'll add that, with a width of 0 (more on that in a minute):

.date-outer:before {
 content: "";
 display: block;
 height: 40px;
 width: 0;
}

I'm going to absolutely position this thing, but because I need to set the position context to the .date-outer element, I'll add position: relative to it:

.date-outer {
 position: relative;
}

And then define my position for my flag thingy with a top offset of 0 (it will snap to the top of .date-outer), and a negative left offset so it'll hang off the left side (my -17px left offset places the flag hanging sort of half way off the left of my element):

.date-outer:before {
 content: "";
 display: block;
 height: 40px;
 width: 0;
 position: absolute;
 top: 0;
 left: -17px;
}

Now, I'll define my flag with borders. First I'll add a left border of black, and a right border of red, both of 15px. This would just make a 2 color rectangle on it's own, but by adding a transparent border-bottom of 15px as well, I get a nice upward facing transparent arrow notched out of the bottom of my rectangle. Then, I just added a border radius to round out the top-left of the flag, and presto:

.date-outer {
 position: relative;
}
.date-outer:before {
 content: "";
 display: block;
 height: 40px;
 width: 0;
 position: absolute;
 top: 0;
 left: -17px;
 border-top-left-radius: 15px;
 border-left: 15px solid #000;
 border-right: 15px solid red;
 border-bottom: 15px solid transparent;
}

A tiny step further

For fun, I wanted to alter the color of my flag for each of 3 posts on the main page. I accomplish this by utilizing nth-of-type, and for my 2nd and 3rd :before styles, I'll define my left border color as a dark gray and a lighter gray (respectively):

.date-outer:nth-of-type(2):before {
 border-left-color: #666;
}
.date-outer:nth-of-type(3):before {
 border-left-color: #999;
}

Support

This latter bit isn't supported by IE8 and older, but otherwise it's pretty safe to use.

No comments:

Post a Comment