Formatting a chat with CSS

In this post I will show you how to format a chat line with CSS. This useful exercise will involve the use of a definition list to mark up our chat that will be later formatted by CSS. The basic markup is as follows:

<dl id="chat">
 
 <dt>
  
  <img src="css-chat/1.jpg" alt="Jane" />
  
 </dt>
 <dd>Hi Joe!</dd>
 
 <dt><img src="css-chat/2.jpg" alt="Joe" /></dt>
 
 <dd>Hi Jane!</dd>
 
 <dt>
  
  <img src="css-chat/1.jpg" alt="Jane" />
  
 </dt>
 <dd>How you doing?</dd>
 
 <dt><img src="css-chat/2.jpg" alt="Joe" /></dt>
 
 <dd>Fine.</dd>
 
 <!-- more chat messages -->
 
</dl>

We have the following elements:

  1. The dt element will contain the chat avatar of each user. Note that each image has a proper alt attribute.
  2. The dd element will contain the actual content of each chat message.

And here's our CSS code:

body {
 
 margin: 0 auto;
 width: 50%;
 padding: 2em 0;
 background: gray;
 color: #333;
 font: 62.5% Arial, Helvetica, sans-serif;
 
}

#chat {
 
 margin: 0;
 padding: 1em;
 background: #fff;
 border: 2px solid silver;
 -moz-border-radius: 6px;
 border-radius: 6px;
 font-size: 1.3em;
 overflow: hidden;
 height: 100%;
}

#chat dt {
 
 float: left;
 width: 110px;
 height: 110px;
 margin-right: 1em;
 clear: left;
 padding-bottom: 0.5em;
 
}

#chat dt img {
 
 display: block;
 width: 100%;
 height: 100%;
 
}

#chat dd {
 
 float: right;
 width: 70%;
 background: #eee;
 margin: 0;
 padding: 0.5em;
 -moz-border-radius: 6px;
 border-radius: 6px;
}

Since we use floating, we also provide a self-clearing mechanism to avoid the overlapping of content. You can see this demo here.

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

Leave a Reply

Note: Only a member of this blog may post a comment.