CSS: sticky blog dates

In this post I'm going to show you how to create sticky dates for your blog with CSS. Sticky dates are always placed in a certain position just next the post they're attached to and they don't move, they always stay in the place assigned to them. To accomplish this task, we're going to use absolute positioning with a newly created context to be used with CSS positioning. Let's start with our markup structure:

<div id="content">

	<div class="post">

		<div class="post-content">

		<h2>Post title</h2>
		<span class="post-date">
			<span class="day">23</span>
			<span class="month-year">Feb 2011</span>
		</span>

		<p>...</p>

		</div>
   </div>

   <!--more posts-->
</div>

As you can see, our post date is placed inside a span element with several other similar elements inside that will allows us to style all the components of a date. Now, let's move on our global and generic styles:

body {
	margin: 0;
	padding: 2em 0;
	font: 76% Arial, sans-serif;
	background: #aaa;
}

h2 {font: 100% Georgia, serif;}

p {line-height: 1.4; margin-top: 0;}

#content {
	width: 50%;
	margin: 0 auto;
}

div.post {
	width: 100%;
	position: relative;
	margin-bottom: 1em;
}

div.post-content {
	height: 100%;
	margin-left: 80px;
	padding: 0.5em;
	background: #fff;
}

div.post-content h2 {
	margin: 0;
	font-size: 1.6em;
	color: #a40;
}

Each post container has the declaration position: relative to create a contextual positioning for our dates. Finally, our dates themselves:

span.post-date {
	width: 70px;
	padding: 5px;
	position: absolute;
	top: 0;
	left: 0;
	background: #000;
	color: white;
	font-weight: bold;
	display: block;
	border-radius: 6px 0 0 6px;
	text-align: center;
	line-height: 1.3;
}

span.day {font-size: 1.3em; color: #f50;}
span.month-year {
	display: block;
}

Note that the overall dimensions of our date container is exactly equal to the left margin assigned to the .post-content element. You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Comments are closed.