Rounded corners using CSS (and only 1 DIV)

July 28. 2004 08:26 2 comments Category: tips | design

Everyone likes rounded corners. Whether it's in print on the web, a rounded corner can structure content AND look pretty (oh so pretty). But creating them is a mess. Until CSS3 is widely adopted, the only way to do this is with nested DIV's, floating images, or tables (yuck!). Each technique has it's drawbacks and one similarity: they all require unnecessary code in the content of the page.

The goal of our magical div:

  • The corners be rounded (duh)
  • It can stretch horizontal and vertical
  • It can have padding
  • It can have a border that merges with the corners
  • It degrades gracefully in older browsers

The source code we want

<div class="rounded">
content text goes here
</div>

The images we'll use

Top Left
Top Right
Bottom Left
Bottom Right

The CSS we need

.rounded { 
background: #fff; 
margin: 1em 0;
padding: 15px;
border: 1px solid #D4CCCB;   
}
.rounded:before {
display: block;
line-height: 0;
height: 20px;
content: url(/images/corner-tl.png);
background: url(/images/corner-tr.png) no-repeat top right;
margin: -16px -16px 0 -16px; 
padding: 0;
}
.rounded:after {
display: block;
line-height: 0;    
height: 20px;
content:  url(/images/corner-bl.png);
background: url(/images/corner-br.png) no-repeat bottom right;
padding: 0;
margin:  0 -16px -16px -16px;
}

The issues I've come across...

It doesn't work in IE. That's to be expected, since it doesn't support the :before and :after CSS2 selectors. But it breaks downs gracefully by being a simple white box with a border and some padding. You can use Dean Edwards' IE7 to bring Internet Explorer out of the stone age, but I haven't tried this yet.

Padding and Negative Margins: The DIV uses padding, but then adds style/content to the top and bottom selectors of the DIV, which is subjected to the padding. To fix it, add negative margins to pull it back into place. Don't forget to add the border width to the negative margin!

I'll write more if it's useful, but most likely no one will read this. Just dig through my source code and figure it out on your own. That's the best way to learn!

Post RSS Tags:

Comments

10/6/2007 7:18:49 AM

Bryan Peters

I don't think there's hope for IE without using IE7.  I'm going to try setting that up for this site and see if it works.

Bryan Peters

10/6/2007 7:18:49 AM

Anonymous

dewd.... that's a tight post, man! Smile

very nice.... try'n it now under Firefox, and seems to work great, which is pretty awesome in-and-of itself.... too bad about IE, but.... well, no big surprise there really, is there? *ugh*

/foO

Anonymous

Comments are closed

Recent posts

Recent comments