Transparent custom corners and borders

Have you ever wanted to make a resizable box with rounded (or any shape) corners, custom borders, and a transparent shadow? Did you also want to do that without cluttering your markup with a bunch of non-semantic div elements? Now you can.

In June last year I wrote about a way of creating a Flexible box with custom corners and borders. While that method works, it needs some extra markup and has a few other limitations. This new technique uses no extra markup, allows the use of transparent images for the corners and borders, and has no restrictions on the background colour and margins of the elements within the main container. Skip right ahead and take a look at the final example if you can’t wait.

Wanted: less markup, more transparency

What, no extra markup? That’s right. One of my Predictions and hopes for 2005 was that we would see an increased use of sensible JavaScript. There’s been plenty of that already this year, and I hope you’ll agree that what I describe here belongs in that category.

The extra markup that is needed to get the corners and borders in place is removed from the HTML and instead inserted with JavaScript. Turn JavaScript off and the custom elements disappear, leaving a more basic looking box behind. Disable CSS and you get an unstyled document. Disable both and you get an unstyled document. You get the idea. No matter what, the content of the box should always be accessible.

To allow for the use of transparent images for the corners and borders, the CSS had to be changed a bit. It’s easier to follow when you can see all the markup, so check the CSS only example for the HTML and CSS, including the markup that is inserted by the script in the final example.

Since an element’s background properties also determine the surface colour or image of the element’s padding, I had to use margins and relative positioning instead of the padding I originally used to put the images in place. If I were to use padding, the transparency of the images would cause some unwanted overlapping, as demonstrated in the CSS only + padding example.

Just like the old version, this box will expand to contain any amount of content vertically, will handle any text size, and can become very wide before the horizontal borders start breaking up. How much it will stretch horizontally depends on the width of the background image that contains the corners.

The IE Factor

There is of course one caveat to using PNG images with alpha transparency. It’s well-known that current versions of Internet Explorer for Windows do not support it. But since IE7, due out in beta later this year, will, I think it’s reasonable to start looking at ways that transparency can be used. Obviously you will need to consider older versions of IE/Win for several years to come, but there are ways to send different images to those browsers.

In these examples I’ve used conditional comments to send GIF images to Internet Explorer browsers with a version number lower than 7, so when IE7 comes along it will use the PNG images, just like other modern browsers. Until then, IE users will get something similar to the CSS only: IE version example. I hope that doesn’t count as browser elitism ;-).

Image usage

Two images are used. First, box.png contains a complete box and is used for the corners and the horizontal borders. For the sake of this demo I’ve made it 1600 pixels wide. You may be able to get away with a narrower image, though it probably won’t save you many bytes. The other image, borders.png, contains the vertical borders.

Why use a single, large image for the corners instead of several smaller ones? There are several reasons:

  • Splitting the image into a bunch (eight in this case – one for each corner plus the top and bottom borders) of smaller images may actually increase the total file size, depending on the look of the corners and borders.
  • To minimise the number of HTTP requests sent to the server.
  • Convenience. When changing the look of the borders and corners, replacing two files is faster than replacing eight files.

Of course you can keep using the extra markup if you like. It works and won’t actually cause any problems. Well, except in IE/Mac, where the vertical borders don’t show up. If you can figure out how to fix that, please let me know. I’m not spending any time on it though, with IE/Mac being dead and not even included in a default Mac OS X installation anymore. Besides, using the JavaScript method described next will take care of IE/Mac.

Out with the divs, in with the JS

Being a sucker for clean markup, I wrote a little bit of JavaScript to help me clean things up. The script inserts the extra div elements and changes the class name of the main container. Changing the class name is done to enable different styling depending on whether JavaScript is available or not.

I’m no JavaScript expert, so while working on the script I used a few code snippets from elsewhere instead of spending three weeks trying to come up with something that wouldn’t work anyway. The createElement function that makes the script work with both HTML (served as text/html) and XHTML (served as text/html or application/xhtml+xml) was found in Simon Willison’s post Javascript, the DOM and application/xhtml. The technique for wrapping the contents of an element in other elements was, incidentally, also found in one of Simon’s articles: Rounded Corners with CSS and JavaScript. Thank you, Simon. Finally, if you recognise the addEvent script it’s because it’s one of Scott Andrew LePera’s widely spread crossbrowser event handlers.

I just adapted the scripts as needed and made them work together. Study the comments in the complete script for the full details.

To create a box with custom borders, all you need to do is wrap whatever you want to be in it in a div element with a class name of cbb (use multiple classes if you like – the script is made to handle that):

  1. <div class="cbb">
  2. Box content
  3. </div>

This is the class you want to style for browsers with JavaScript turned off (or no support for the DOM methods used). View the JavaScript off example to see the very basic styling I applied.

And obviously you need to load the file containing the JavaScript:

  1. <script type="text/javascript" src="cb.js"></script>

The script adds the extra div elements and changes the class name from cbb to cb, so cb is the class used to attach the images. If you want to use other class names, just edit the initCB function in the JavaScript file.

And we’re done

And there you have it, a resizable box with transparent custom corners and borders, no extra markup needed. To customise it, just replace the images with your own. If your custom borders have different dimensions than those used in the demo you will also need to adjust the CSS to account for that.

Got any suggestions for further improvement? Let’s hear ‘em.

Update: I’ve made some changes to fix a few of the glitches mentioned in the comments.

Problems fixed include:

  • Floating: You can now float the box without breaking it.
  • Margins: It is now easier to control the vertical margins of the box. This is especially notable when you have several boxes stacked on top of one another.

To fix this I changed the script a bit. It now inserts one more div element that wraps the box content. Doing that allowed me to ditch some of the relative positioning and negative margins, which were causing problems in some cases. I had to give one of the divs a 1px height to make IE happy, but that’s something I’m getting pretty used to doing.

Customising instructions: For details on how to make your own graphics, check out Customising custom corners and borders.

This technique has been updated! Check out Transparent custom corners and borders, version 2 for a more recent version that fixes some problems in the version described here.

Posted on May 16, 2005 in CSS, JavaScript

Comments

  1. May 16, 2005 by Chris

    Believe it or not, I’ve spent last two last days trying to create such nice, rounded, shaded corners while adding as litte extra markup as possible, and your solution uses none! Thank you, I can finally move on with my project:)

  2. Thanks much for posting this. Can’t wait to start fiddling with it on my own.

  3. Looks great. Unfortunately, I’m not seeing the same result in IE6. Am I missing something? It occurs that possibly the .gif images haven’t been uploaded or the paths are wrong.

    Sorry to complain - it really looks like a great technique.

  4. May 16, 2005 by Roger Johansson (Author comment)

    Bryan: It doesn’t look exactly the same in IE6 - there are no shadows. Is that what you’re referring to? I just double-checked, and the GIF images are there and the paths are correct.

  5. I haven’t examined your script code, but from the description it looks exactly like the solution I developed for the (still unpublished) redesign of my homepage.

    Some ideas just hang around in the air waiting to be picked like a fruited.

    I just have not managed to be the first one yet ;)

  6. Couldn’t the test for multiple class names have been done with a much simpler indexOf(“cbb”)? I realise that there is the very faint possibility that someone may name another div and include that string, but it seems very unlikely to add all that code looping for.

  7. Roger - I hadn’t noticed the lack of shadows but that’s understandable. I was more concerned with the lack of images at the corners of the box. I then cleared my cache and it now works fine. Sorry to bother you….

  8. May 16, 2005 by Roger Johansson (Author comment)

    Benjamin: Sorry! ;-)

    Matthew: Hmm. I suppose you could do it that way if you’re worried about performance. I have no idea if that is an issue though.

    Bryan: Ah, good. I was worried that there might be something I’d forgotten.

  9. May 16, 2005 by Masklinn

    I don’t really get why you’re using all GIFs for Internet Explorer: why not using 8bits PNGs instead, when they are smaller than GIFs? (the PNG version of border.gif is roughly half the size, box.gif on the other hand grows when converted).

    (It should also be noted that your two PNG files can be compressed a bit more, shaving 40% off of them)

  10. First Nifty Corners now custom borders.

    JavaScript is surely our new best friend!

  11. May 16, 2005 by Roger Johansson (Author comment)

    Masklinn: I didn’t think of using 8 bit PNGs for IE, simple as that. I’d compress the PNG files if I could, but I can’t find an option for it in Photoshop. Besides, you’re all supposed to create your own images, so feel free to use whatever file format and compression that suits you best ;-).

  12. Thanks for posting this Roger, it’ll be quite useful.

  13. Well done, this is excellent.

  14. Roger - wow.

    I had thought Nifty Corners was sweet, but was frustrated at the fact that I couldn’t change the look per stylesheet, and not have entire control over the look.

    But this, this is exactly what I need. This is great!

    Thank you so much for it. And thanks to everyone in this community, because all these ideas build off of each other.

  15. Nice bit of acrobatics, but won’t it potentially mess up AJAX applications, since the DOM is not entirely predictable, depending on how markup is going to be styled?

    Secondly, if screenreaders become javascript aware, as AJAX becomes pervasive, then the accessibility benefits are lost.

    I’m a big fan of your work and I admire the heroics that you have to undergo to workaround the limitations of CSS. It’s just an indictment of the limitations of CSS as a 100% solution to the problem of the separation of content and presentation.

  16. I’m all for this script, and am glad it was developed, however, there is a slight problem with changing the dom with useless DIVs.

    It is still not semantic, even though it is created on-the-fly. Editing the dom and adding invalid objects means you should remove the validation badge (if you have one), or at least AAA compliancy, for it is not supported as far as I know.

    Thank you.

  17. Just FYI, don’t know if it’s a matter to you, but this is sort of broken in IE5 (screenshot)

    Really nice job anyways, this is definitely my favorite design blog.

  18. May 17, 2005 by Roger Johansson (Author comment)

    Chui: You’d have to ask someone who’s used Ajax about that. I have no idea. As for screenreaders, I’m not worried about them picking up the extra markup which consists of empty div elements with no inherent semantic meaning. There aren’t any real accessibility benefits to this method, it just makes your markup cleaner.

    Jeff: The added elements are not semantic, but that doesn’t make them invalid. If I’d used h1 elements instead of divs, well that would be both invalid and problematic.

  19. May 17, 2005 by Roger Johansson (Author comment)

    Ozh: Oops. I thought I’d checked it in IE5. I’ll see what I can do about it.

  20. This makes me happy. Thank you.

    Can I ask, in the css, why does .bb have a bottom margin of 1em? That margin gives me a graphic glitch on IE6, so I erased it. Is that gonna bite me in the arse? Looks like no ill effects.

  21. May 17, 2005 by Martin Olsson

    This is excellent stuff! I’ve been prototyping a rather complex web application using -moz-border-radius to approximate rounded corners while waiting for a truly good technique to use for the final implementation. This comes closer than anything I’ve seen so far, but I have two problems:

    1. I have a navigation div absolutely positioned with lots of floats and stuff inside. Your borders “collapse” to minimum height and the stuff inside flows over the edge. I can probably work this one out on my own, but any tips are appreciated.

    2. I want one of my boxes filled to the edges with a background image or color. I can get it to the left and right edges by specifying negative margins, but I still get a white space at the top, no matter what I do. I noticed the same problem in your example where the title has a white space above it. Can this be fixed?

    Your technique is so nifty I might just change the design of the application if these problems can’t be fixed.

    Thanks! /Martin

  22. May 17, 2005 by matthijs

    Hmm, this technique makes me think. But that’s probably one of the purposes of these articles. Using javascript to add html which the css uses for presentation? How does that fit in the whole seperation of content, presentation and behavior issue? I understand your idea behind the technique. But somehow I have a feeling something’s wrong. Or isn’t it?

  23. May 17, 2005 by Mats Lindblad

    Have you tried to get it to work along with your “Fixed or fluid width? Elastic!” code?

    I tried floating the .cb (using another class like class=”cbb left-float”) and end up with screenshot

    Note the bottom right corner.

  24. May 17, 2005 by Andi

    Good, but broken on widescreen and high resolutions (1680x1050).

  25. May 17, 2005 by Roger Johansson (Author comment)

    Andi: Yeah, well that’s because the background image is only 1600px wide ;-). Make it wider if you need it to work in extremely wide windows.

    I’m looking at the other glitches that have been reported and will update as soon as I have found (or given up looking for) solutions.

  26. May 17, 2005 by Oarang Tolmeth

    Jeff, none of the divs added to the DOM make it invalid!

  27. Amazing work Roger!

    Perhaps this deserves a writeup on ALA?

    For those of you interested in squeezing your PNGs there is PNGCRUSH

    http://www.google.com/search?hl=en&q=pngcrush&btnG=Google+Search

    Reading Roger’s great piece on tables would probably be time better spent than shaving off bytes from PNG’s …

    Keep up the good work!

  28. May 18, 2005 by Alexandru Mihai Bîrsan

    Oh, my God! You are the Killer Whale! Oh, dear Lord! You’re really good!

    Thank you, thank you, and… thanks!

  29. May 18, 2005 by Mats Lindblad

    Roger, u can skip my problem, I don’t think it’s solvable. But what I did was to wrap the cb-div inside a floated div.

    Like this:

    &lt;div id="content"&gt;
    &lt;div class="cbb"&gt; ...
    
  30. May 18, 2005 by Roger Johansson (Author comment)

    Thanks for the nice feedback everyone!

    Mats: The boxes in the updated version can be floated. Are you running into other problems?

  31. May 18, 2005 by Mats Lindblad

    Thanks 4 the quick fix but I need to float the boxes both left and right and not at all, so I’ll stick to wrapping them inside div’s 4 now.

  32. Using height: 1%; for IE may cause trouble in long documents (the height will be calculated based on the document’s height and will look far too big). Use height: 1px; for IE instead - same result but no trouble…

  33. Really cool, I was also playing with JS recentrly to relieve CSS and XHTML of the heavy code overhead. I think it’s an predecessor of CSS3’s content (maybe)…

    Ad “I can’t find an option for it in Photoshop” - Save For Web > PNG8 > Select the background color you want to have transparent > Map to transparent (the chcecker icon under the pallete)

  34. May 18, 2005 by Andi

    [concerning widescreen and high resolutions (1680x1050)] Sorry, my fault ;-)

  35. May 18, 2005 by Roger Johansson (Author comment)

    Mats: Well, floating works now. Left, right and not at all :-)

    reieRMeister: Sounds reasonable. Wonder why that hack always uses % though… could there be a catch to using 1px?

    Jan: I was referring to PNG compression settings in Photoshop . It doesn’t seem to have any.

  36. Ah, I didn’t read the whole Masklinn’s post, so I lost the context… My bad.

  37. Roger: This hack just forces IE to recalculate the height by choosing a value which is smaller than the object’s real height. Since IE (incorrectly) interprets height as min-height the box will expand to the correct height. Ususally this works with 1%. But in larger (read: longer) documents the real height may be smaller than 1%. So the box will look far to big. Using 1px is safe.

  38. May 19, 2005 by David

    Can’t figure out why there is no background color for my boxes. The tops and bottoms, left and rights appear but no box bg color…I tried playing with the css but I might be missing something.

    Do I need to make the box size exactly 1600px x 75px?

    Thanks, David

  39. May 20, 2005 by Roger Johansson (Author comment)

    David: No, the background image can be any size. It’s hard to tell what’s wrong without seeing an example.

  40. Genuis! Pure Genuis! I love using rounded borders but they were always such a bastard to implement/update. This is so much easier! Thanks.

  41. May 21, 2005 by Chris

    There is a PHP work-around for .png transparency in IE without any additional markup.

    http://koivi.com/ie-png-transparency/

    Hope that helps!

  42. May 22, 2005 by Steve

    I have two problems: 1) This trick is totally broken in Firefox; it leaves a double of the left side of the box (Safari is fine) 2) I have the same problem as David; the borders are fine, but there’s no background color (it should be #fff just as with the default css).

  43. May 22, 2005 by Steve

    Update: Firefox is fine now, but still the transparent background. I assume .i3 is what handles the bg? In which case, it is going completely ignored— commented out, there’s no change.

  44. May 22, 2005 by Roger Johansson (Author comment)

    Steve: It works fine in both Firefox and Safari here. The .i3 rule handles the background colour, that is correct. Make sure you reload the JavaScript file in case the old version is stuck in your browser cache.

  45. May 22, 2005 by badrad

    Here is an idea for an improvement.

    Nifty corners (http://pro.html.it/articoli/id599/idcat31/pag_1/pag.html) has a thing where you add padding to the original div that is then removed when the new divs are put in, this prevents the visual jump that can occur when the content is replaced.

    Other then that, so far this technique is working beautifully for me. Thanks again Roger.

  46. May 22, 2005 by badrad

    Hey Roger, would you mind looking at something for me?

    http://www.pixeljunkies.com/roger/test.htm

    I renamed .cbb to .innerboxplain and .cb to .innerbox because I felt like it. But that shouldnt cause this :)

    OK, so it looks great in gecko, great in Opera 8 (wacky in Opera 7 - but I haven’t troubleshooted that cause I gotta get too bed, and its not what Im posting about), and looks almost good in IE. In IE, the top left and bottom left corners are not there.

    I’m at a loss for a reason why. But it is 3 am, so forgive me if its something stupid or I havent pointed out something I should.

  47. May 22, 2005 by badrad

    Yea, don’t worry about Opera 7. It’s not this, somewhere along the line I changed something in my style that caused it to freak out. Ill deal with it later.

  48. May 22, 2005 by badrad

    Well I should of waited half an hour before posting here to ask you - I figured it out on my own. You can go ahead and delete this and my last two comments if you want.

    It was a text-align I had done to IE only through the * html hack on a containing div for the purposes of emulating min-width. Nothing wrong with your stuff, just a case of my css screwing it up. Which I though it was, but couldnt seem to figure out on my own, but I did.

    Maybe not my mind can shut up enough to let me sleep.

  49. May 22, 2005 by Steve

    Ah weird- somehow I must have copied in the wrong js file..the new one works fine, thanks Roger.

    Question: I have a layout that I can’t seem to get to cooperate properly. I have two of your boxes on top of each other, floating left as in the css. On the right I have a narrow column “sidebar”. Because of the stacked floats, the sidebar gets pushed down. Also, as I resize the browser, the box’s width percentage causes the gap between the boxes and sidebar to increase, and I want it to be fixed. Any idea how I might correct this?

  50. May 25, 2005 by David H

    Is it possible to float two elements within the box? Doing so seems to break the model, even if I float the main div. Other than that, it’s working excellently for me, much thanks.

  51. Hi. Have you tried creating your transparent PNGs with Fireworks? Thus far - knock on wood - I haven’t had any problems with transparent PNGs in IE if those were made in Fireworks.

    I’ve quickly made 2 images, box8.png and borders8.png, that seem to work fine in IE, too. (Nothing fancy, just to see if it worked).

    I’ve put copies of them on www.lamiroy.com/download.

    Regards. Manuel

  52. A little late into the fray, and perhaps slightly OT.

    Optipng is the best tool I’ve found for compressing png’s, and it’s available as either a commandline tool or cocoa app (last I checked).

    Also just wanted to reiterate that IE does support 8-bit pngs, but not 24-bit ones. Generally I have found that 8-bit gifs get better results for files less than 4K — YMMY.

  53. May 28, 2005 by Roger Johansson (Author comment)

    Steve: It’s hard to tell without having an example to look at.

    David H: Floating elements within the box works fine here. Got an example we can look at?

    Manuel: Nope, haven’t tried Fireworks, but since IE only supports binary transparency in PNGs anyway there isn’t really any point in using PNGs for IE. Also see Terrence’s comment.

  54. May 30, 2005 by Steve

    Short of making individual js files for each instance, would there be an efficient method of mixing box types on a given page? I’m not talking about adding divs for the single as your script shows, but doing completely separate boxes with different png files (or maybe this accounts for that and I just don’t “get it”?)

    btw I fixed all my other problems :)

  55. I love this! I stuck it on my entries to see how it worked and now I don’t want to take it off, is that stealing?

  56. June 1, 2005 by Chris

    Great work!

    I noticed a small bug and can’t figure out how to fix it. When you’re viewing your final sample site in Firefox, at certain sizes the content of a box is separated from its bottom by 1px. If you shrink the text by one size, you’ll see what I mean.

    I have also noticed that sometimes the bottom overlaps the content by 1px (this doesn’t really have much of a visual effect, though).

  57. June 1, 2005 by Roger Johansson (Author comment)

    Conánn: Well, I wouldn’t call it stealing, but I would prefer if you came up with your own graphics.

    Chris: Both of the problems you mentioned are a result of a rounding bug i Mozilla based browsers. Will it ever be fixed? I don’t know.

  58. I will create my own I just tried yours out and love’m! Unfortunately your aesthetic is very similar to my own when it comes to this type of thing and it will be hard for me to replace yours. I have seen the same motif in some of your other work and like it a lot. After I have changed it I will have to find a suitable way of crediting yourself and the others I have plagiarized along the road, perhaps we can come to an arrangement. THX

  59. June 2, 2005 by Steve

    Roger - any ideas about my question at post 54?

  60. What about that IE5 bug from comment #17 ?

  61. June 2, 2005 by Mindaugas Pelionis

    If you try to make thinner borders, you may run into IE’s empty <div> height bug. Add following code to IE specific CSS to prevent this:

    .bb div,  
    .bt div {  
        line-height: 0;  
        font-size: 0;  
    }
    
  62. June 4, 2005 by Roger Johansson (Author comment)

    Steve, Paul: I’ll take a look at the issues mentioned in comments #17 and #54 when I get the time.

  63. Looks pretty good Roger. I do see a few places where the script can be tightened up a bit, though. Once I have a little free time, I’ll pass along my recommendations.

    Keep up the great work and thanks for not inserting any junk markup.

  64. June 6, 2005 by Roger Johansson (Author comment)

    Steve: Regarding comment #54. It’s pretty easy to have differently styled boxes on the same page. Add another class name and use that to override the default rules. I’ve added an example of that to the demo. Instructions are in the comments. All changes are made in the CSS so there is no need for extra .js files.

    Aaron: Looking forward to those suggestions. I’m not the king of JavaScript, so I expect the script can be made more efficient.

  65. June 6, 2005 by Roger Johansson (Author comment)

    Regarding comment #17: The bug in IE5 is fixed now. The margins of elements in the innermost div were sticking out of the div despite it having horizontal borders to prevent that. A little bit of “height:1px” in the IE-specific CSS took care of the problem.

  66. This looks really great, but I’m finding it very difficult to customize. Could you write a short explanation of how to modify the CSS to work with images of different dimensions?

  67. June 13, 2005 by Roger Johansson (Author comment)

    Jordan: Noted in my to-do list.

  68. Great bit of work… but I find that when I try to nest floated divs within the box it breaks (nested divs are displayed below the box). Anyone else have this problem? Any solutions?

  69. Comment-o-rama here today! :-)

    So you do know JavaScript? ;-)

    Anyway, being JavaScript boy here, I just have to make some small remarks:

    First, I agree with Matthew Pennel; use indexOf or a regular expression to check the classnames. Also, good practice from a performance point of view is to not declare a variable within a loop, but rather declare it before the loop.

    For instance:

    for (var i = 0; i < cbDivs.length; i++) {
        // Save the original outer div for later
        var thediv = cbDivs[i];
    

    should be

    var thediv;
    for (var i = 0; i < cbDivs.length; i++) {
        // Save the original outer div for later
        thediv = cbDivs[i];
    

    and so on… You get my drift.

    Otherwise: very nice! Keep on scripting!

  70. June 21, 2005 by Roger Johansson (Author comment)

    Jordan: Check out Customising custom corners and borders for customisation instructions.

    David: Would you happen to have an example I can take a look at?

    Robert: Thanks for the tips. I’ve updated the script now. How did I miss that the variable was declared inside the loop? No idea.

  71. June 23, 2005 by Colin

    I was doing some testing with your wonderful script and noticed that if the .cbb box extends beyond the bottom of the page, IE doesn’t display scrollbars… Perhaps IE doesn’t recognize the JS-generated content as content?

  72. June 24, 2005 by Colin

    The IEBlog posted this rounded corners ‘solution’ yesterday which I thought everyone here would find amusing… http://blogs.msdn.com/ie/archive/2005/06/23/431980.aspx

  73. June 25, 2005 by Roger Johansson (Author comment)

    Colin: Hmm. Could you post an example of that? I can’t reproduce the problem.

    And yeah, I noticed that article at the IE Blog. Somebody posted a link to this method in the comments. Ironic, isn’t it ;-)

  74. June 27, 2005 by John Keane

    Roger, David: I think the problem David is reporting with nested floated divs is that the containing div (i.e. the cbb div) doesn’t expand to the size of the nested div, so the nested div overflows out of the bottom of the box. I think there are a number of hacks for this, the only one I can remember at the moment is having a clearing element or div at the end of the containing div.

  75. This is a really good technique. Thanks for sharing. I hope to implement it for my site some time later.. (My site became a javascript beast, I have to optimize my code :) )

  76. July 17, 2005 by Thorsten

    hi,

    i can’t seem to find out how to change the width of a box (with css and js enabled) to, say 300px without the rounded corner effect breaking, can someone give me a hint?

  77. “I used a few code snippets from elsewhere instead of spending three weeks trying to come up with something that wouldn’t work anyway.”

    awesome.

  78. July 21, 2005 by Valério F. Carvalho

    My test page with rounded border is wrong.

    I used “float:left”, float:right and clear:both in CSS code to positioning the boxes.

    If you could see the page and to help to repair the error.

    The address is http://beta.uern.br

  79. July 27, 2005 by Valério F. Carvalho

    I had to gone on the project, but I put the page with round border error in other address:

    http://geocities.yahoo.com.br/valnetbr/default.htm

    In the page have a link to download the example.

    Who can help to solve this error.

    Thanks.

  80. Thanks for sharing this technique! I have it working great in Firefox, but since implementing this all I get in IE is a blank page. What could I have done wrong?

  81. Sorry, please ignore that last comment of mine.

    Turns out is was because I had used instead of .

  82. Code got stripped out of that last message. It should have read…

    Turns out is was because I had used <script /> instead of <script></script>.

  83. August 2, 2005 by Mihailo

    I have a problem. When I use class on a div that has child div’s in it it transfers the class on to all of the div’s inside altough they have their own class. Any solution?

  84. August 2, 2005 by patrick

    I’m trying to add a background image (background:url(images/robin.jpg); background-repeat: no-repeat; background-position: center center;) which serves as a logo. I tried inserting it both in the:

    1. .cbb { padding:0 10px; margin:1em 0; background:#fff; border:1px solid #666; } 2. .cbb h1 { margin:0 -10px; padding:0.3em 10px; background:#efece6; font:bold 1.2em/1 Arial, Helvetica, sans-serif; } Nothing is showing up. Any ideas?

  85. August 6, 2005 by Patrick

    OK … I’ve figured out the answer to the above question. All I did was add a hight attribute to the .cb h1 class in the .css. Now, I have a beautiful logo that sits at the top of the box where the thin grey line was before. I didn’t have to tamper w/the js at all. In fact, I think this solution will work w/or w/out the js enabled.

  86. August 8, 2005 by Justin

    anybody know a way to get this to work with some PNG hacks for IE? or do those only work for tables and such

  87. I have been using your older version of boxes for awhile now @ work. I am implementing this version onto our site revisions. This is absolutely awesome.

    Now I do have some questions.. I am making boxes which the body collapses (display:none) but the heading stays. I have been able to do that with the new code by wrapping a “span class=hide” around the paragraph tags. This still leaves the bottom visible.

    Would there be a way you could think off the top of yer head, to be able to hide all the box of the content (paragraph and below) ?

    Just curious.

    Again.. thanks soo much.

  88. This solution works great! It does what it says it’s supposed to do :)

    The only problem I’m having is making the height 100%. I want the bounded box, but I can’t seem to figure out where/how to set the box to be the full height of its container.

    Anyone have a solution for this?

    Thanks! -eli

  89. August 16, 2005 by Anonymous

    your demo flickers badly upon resize in Firefox 0.9 and 1.0.6

    JavaScript used for layout is probably a idea, whether it’s obtrusive or not. IMO this is the least effective CSS/round-corner method i’ve seen.

  90. August 16, 2005 by Roger Johansson (Author comment)

    I’ll try to set some time aside to take a look at the questions and problems noted here since my previous comment. Please be patient :-)

    Comment #89: No flickering here. In fact I haven’t seen this cause flicker in any browser, so your comment is a bit surprising. Using JavaScript for layout… well, if you want to avoid that all you need to do is move the divs to the markup instead.

  91. I ask with my real name because there’s no way an anonymous asker of a question so apparently stupid would get an answer, especially so far after the fact, but can you, Roger, explain something for me? The image borders.png has the right and left border smack up against each other. I don’t see widths for the i1 and i2 divs. How does each side display only its half of the .png?

  92. Ah, just found the followup post, so if comment #91 ever gets read, please ignore it. By the way, server offline for the last couple days?

  93. August 23, 2005 by Roger Johansson (Author comment)

    Chris: Yep, I read all comments. I make take a while to respond to them though ;-)

    Yeah, the server crashed last weekend and it took a couple of days for my host to get everything back to normal. Everything should be OK now.

  94. “No extra markup” isn’t entirely true here. Sure, the document that gets sent down the wire has less markup, but it’s still getting added after the fact, in the browser, and it still becomes part of the DOM after the script runs.

  95. September 7, 2005 by Techni

    You said you wanted to know how to get vertical borders? Well if you’re using a table, for the middle row, left and right columns, just stick an image in them with a width set to the width of the image, and height set to 100%

  96. September 7, 2005 by Roger Johansson (Author comment)

    Marty: Absolutely. The point is that there is no extra markup you need to wade through while working with the HTML.

    Techni: Well yes, but why use a table for that? And why put the images in the HTML?

  97. Great technique; I love it!

    One quick suggestion:

    Have you considered changing the style to the following to handle extra-wide resolutions?

    .cb {
         margin:0.5em 0;
        max-width: 1600px;
        width:expression(document.body.clientWidth > 1620? "1600px": "auto" );
    }
    
  98. September 9, 2005 by Gordon Tatler

    Is it possible to get all 4 corners rounded ?

    Not up to much in CSS so can’t see how.

    Please email if possible.

  99. September 9, 2005 by Roger Johansson (Author comment)

    6dust: Not really. The situations where that will be necessary are rare, so I’ll leave it as an exercise for the reader ;-).

    Gordon: Yes, by making an image with four rounded corners. Instructions for the CSS part are available in Customising custom corners and borders.

  100. incredibly well done and documented. We thank you.

  101. Wow really nice work. Just came across this site and was looking at all your examples and this one is just fantastic. No plans on where I might use this, but thanks for all the great information.

  102. I’m using this technique in a sit I’m buildign for a friend, and after sitting down to work out what the CSS is doing in detail, realised that a way of handling the extra-wide case is to put

    .bb div, .bt div {width: 50%;}

    rather than have them be just the corner-width; this gets you to almost twice the underlying image width before it looks ugly in the middle.

  103. Just wanted to chime in and say that I came across this technique the other day and it’s simply fabulous. Thanks for saving me a whole bunch of time and effort!

  104. Thanks a bunch for this ! I got it working on my page, but yet i have a one pixel break between the top border and the body of the . A screenshot is here

    http://img249.imageshack.us/img249/5839/test9fh.jpg

    i cant’ figure out how to get rid of the px horizontal line. The code includes a simple table inside the .

    I changed the class name “two” to “w35” just to indicate the percentage of the width. I guess that is not the reason for the horizontal line !

    And yeah, is there any way i could dynamically change the colour of the boxes, i mean now i have to edit the images for a specific colour, is there any work around for it?

  105. REf# 104 I changed the border-width of .i3 to 0 and that removed the horizontal line, does this have any adverse effect?

  106. Thanks so much for this! I am currently trying to implement it for dynamic drop shadows on a site I am building. I am having a few issues though that I hoped you guys could help me fix.

    First off, since I am applying drop shadows with the technique I want a small white space to sub in for an offset. I have been able to do this with everything except the top right corner. Any ideas?

    Second, of course IE is acting up on me. There are margins/padding on the bottom of the main container that I can’t seem to account for. Also, the other side of the border img is showing up in the content area. Things are disappearing on me and I can’t seem to fix it with holly hack.

    Thanks again!

    Take a look at the site here

  107. Hi Roger, I have what is probably a totally easy question, but I cannot solve it. I have set up everything according to the examples, but the graphics just will NOT show; I get the default (line style) no matter what I try.

    I am trying to implement this on a Wordpress site, so the header info is seperate from the body template pages; I put the JavaScript call in the head area as normal; added the CSS to my CSS file; added the CSS tag to my site, wrapped around content. I know it is (partially) working, because I can see the outline style, but no graphics.

    The only difference I see is that my graphics are in an /images directory; I updated the CSS accordingly.

    Any help you can offer would be great, I really want to see this happen!

    Thanks for any suggestions, Jess

  108. October 6, 2005 by Roger Johansson (Author comment)

    Veeru: The border is there to stop the margins of any elements in the box from pushing the top and bottom away.

    Dynamically changing the inside colour may be possible if the insides of your corners are right angled. You could then use a background colour in the CSS. I don’t have an example of it, but it should be possible.

    jace: Sorry, no solutions come to mind right now.

    Jess: I need to see your site to be able to figure out what is going wrong. From your description it sounds like either the JavaScript is not loading or the CSS can’t find the images.

  109. October 20, 2005 by Robert G.

    Hello Roger, I’m new at working with CSS and javascript but I want to use this code for a website I am developing. I am using your html as a test file and have downloaded the javascript file. I separated the CSS and included an @ import statement in the head section. In IE 6 the page displays with the rounded boxes. In Firefox 1.07 and Opera the page is broken up. The graphics are not displayed and the text is squished together. The firefox js console warning states that there is a redeclaration of var i. I would appreciate any help you can give me. Thanks for posting this code.

  110. October 20, 2005 by Roger Johansson (Author comment)

    Robert G.: If you can post a URL I can take a look and try to figure out what’s wrong.

  111. Thanks for getting back to me so quickly. This is the file that I am working on http://www.gandwphotography.com/box_test.html.The source file contains the separate elements. If I can get it to work I’ll try to modify it for use on a website that I am creating. One other question. Will using javascript be problematic as the web moves towards standards and newer browsers emerge?

  112. October 21, 2005 by Roger Johansson (Author comment)

    Robert: I see two problems.

    1. The css file “css/boxtst.css” contains a style end tag and the conditional comments that are used to give IE different images. That needs to be removed.
    2. After the closing html tag in your document, the CSS and JavaScript is repeated. You need to remove that.

    Start there and see if that fixes the problems.

    Regarding the use of JavaScript: no, it will not be problematic if it is used in an unobtrusive way with fallbacks for user agents that do not support it.

  113. October 21, 2005 by Robert G

    Hello Roger, I followed your suggestions and was able to get the boxes working in Firefox and Opera. I have a lot to learn about CSS and standards. Another question. I have placed one box inside another box. I scaled the inside box to 20%. Now when I scale down the browser window the inside box breaks up. This is the code (.two {width:20%; float: left; }). Again, many thanks for your help. Bob

  114. October 21, 2005 by Roger Johansson (Author comment)

    Glad I could help, Robert :-).

    I haven’t tried placing one box inside another, so I’m not sure what is going wrong. I’ll take a look at it when I have some time to spare and post a comment.

  115. October 25, 2005 by chappy

    tried to implement this into a 1 box centered design from the little boxes examples at thenoodleincident.com that uses an IE centering hack.. view source here

    if i try to insert your boxes inside the above div, they end up broken in IE6.

    as soon as i removed the “text-align:center;” from the containing div, your box showed up properly, but my containing div was then broke in IE6. ideas?

    thanks

  116. October 25, 2005 by chappy

    doh!! i didnt clear my cache..nevermind.. it works in IE6 now that i removed the “text-align:centered;” from the containing div.

    wondering if its broke in IE5 though?…..

    many thanks for such a cool solution.

  117. Hi. Great looking solution. Big thanks for making the code available.

    I’m using a liquid layout from positioniseverything.net - the Geckofix layout. The middle section is floated left and then right.

    When I use either the transparent or standard flexible solutions it stops working in IE6.

    It was working briefly but then stopped and I’m not sure what I did.

    It works fine in Firefox and Opera. http://www.ekstasis.net/blog/blog.php

  118. Am having issues with floats that should be contained within a curved corner box. I’ve floated the curved box, and want to float an un-bordered div to the left of it, with the rest of the text in the div flowing down. This works in IE, but not in anything else, despite the curved box being floated (hence in theory containing all subfloats). The non-curved parts seem to be working. Test case is at http://bleurgh.co.uk/temp/cbbtestcase/

    Any ideas?

  119. November 9, 2005 by Roger Johansson (Author comment)

    Matthew: When you use floated elements inside one of these boxes you need to use a clearing method for the innermost div (.i3). I recently ran into this myself. I suggest using Easy clearing of floats.

  120. November 22, 2005 by Mihailo

    I’ve implemented this solution to a website http://www.leginetcy.com/ but in Firefox one of the boxes has 1 pixel blank line that is only apearing to that one box. In IE, everything is ok. Any solution?

  121. I too am trying to implement this in a WordPress theme. I’ve managed to get the script to work, but my problem is the boxes are not wide enough for the content. Particularly in a side bar where there is dynamic lists being created. Any suggestions on forcing a wider box dynamically?

  122. December 3, 2005 by Pedram

    why aren’t you using..

    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=’box.png’, sizingMethod=’scale’);

    to make use of transparent png’s in IE

  123. December 3, 2005 by Roger Johansson (Author comment)

    Pedram: Because that hack doesn’t work very well with background images.

  124. December 3, 2005 by Pedram

    Yah I just looked into it … it doesn’t have any facility to do tiling.. I’m getting tired of hacking at it too… I can almost get it to work, but it’s soo damn frustrating…

    My job would be sooo much easier if the people in charge would just think a little more often.

    I don’t see why a patch for IE wasn’t made 2 years ago to simply add variable transparency for png’s.

    I think the original designers must be dead. I don’t see how a company could be so neglectful. Petition? I wish we could boycott

  125. Help! I’m new to this.. I added the js to my html page.

    1. Where do I store the images?
    2. How to I call the js?
    3. I don’t see a png reference in the code?

    Thanks for any help!

  126. March 6, 2006 by casey

    This is a really nice method of shadows and rounded corners, however if I have any internal div elements they seem to inherit the borders as a background image. I needed to remove the #fff as a background color because my inner divs have a bg image of their own. My question is; Is there any way to keep the borders out of the inside when using your box as a container div?

    Thanks again. casey

  127. This is a great script. Prefer it to nifty corners, etc…. BUT…

    There is a problem with elements that are styled both by reference to their class and their ID.

    You have forgotten to reapply the ID to the outer DIV.

    I’ve achieved this (imperfectly) like this:

    outer.id = thediv.id;
    thediv.id = '';
    

    I add these lines after:

    outer.className = thediv.className.replace('cbb', 'cb');
    

    Now, purists will note that for a moment we have two elements with the same ID, which is bad… but it’s only for a split second!

    This seems to fix things for me!

    Cheers,

    • Alister
  128. I’m trying to make a site overflow friendly, would this work on the boxes at http://www.junkboys.net/new (note: site is going live by mid next week, so if it gives you an error, got to http://www.junkboys.net)?

    I like the idea of what you’re doing here, but so far i haven’t seen any applications where it is a semi-transparent box with rounded corners in front of a background picture.

    Would using the php solution for ie png transparency in tandem with this work?

  129. I am trying to get the background for my boxes with content to work with IE. The background works perfect in Firefox, but IE makes the background solid. Any suggestions. (http://s153391734.onlinehome.us/)

  130. April 12, 2006 by Örjan

    Is it possible to use this one image method to create link “buttons” instead of sliding doors split images. See the markup below, there’s no problem to use an extra span if that make things easier

    [li][a href=”#”]Text[/a][/li]

  131. April 20, 2006 by Andrew Gribben

    Hi, has anyone been able to create a second box using a different image, but on the same page ?

  132. Aw heck! I’ve LITERALLY spent hours trying to debug an issue with this thing!!!

    I only need small corners on my boxes, so I set most of my corners and edges to 8px or there abouts.

    But NO MATTER WHAT I did, the BT and BB divs (or their inner divs) were double the height. And there was nothing I could do.

    In the end I had it down to the barest bones: one div nested inside another, and still the problem.

    Finally I came across this page over at the css-discuss archive… which was my issue precisely!

    It turns out an empty div in IE will default to a minimum height roughly equivalent to the line-height setting it inherits.

    In my case way over 8px.

    The solution I chose was to add one line (5th) to the insertBottom and insertTop function in the JS as follows, to add a non-breaking space as the content of the inner DIV created by this function:

    function insertBottom(obj) {
        var d=createElement("div");
        d.className="bb";
        var d2=createElement("div");
        d2.innerHTML="&nbsp;";
        d.appendChild(d2);
        obj.appendChild(d);
    };

    The line I added (in the same place in both functions) is in bold.

    I also made a change to the stylesheet, adding

        font-size: 1px;
        line-height: 0;

    to .bt div and .bb div css declarations.

    I can’t tell you how much pain this has caused me!!! I am just so sick of dodgy IE whitespace issues. They keep coming back to bite me in the butt :(

    Anyway, this is an important fix which I strongly suggest you add to the code, Roger. Along with my previous fix in comment 127.

    Cheers,

    • Alister
  133. April 22, 2006 by Roger Johansson (Author comment)

    Just a note to those of you who have questions or suggestions for improvement: it’s on my to-do list. Not sure when I’ll get around to it though - maybe in the next few days, maybe in a couple of weeks or a month. It will get done eventually though.

  134. April 23, 2006 by Anders

    Great! Tnx.

    Question: It is rendered different in IE compared to Firefox. The diff that disturbs me is that in IE the outer box will enclose the inner box completely. But in FF the inner box is “leaking” outside the outer box.

    Example:

    &lt;div class="cbb">
        &lt;div class="cbb two">
            aaa bbb ccc
            aaa bbb ccc
        &lt;/div>
            aaa bbb ccc
            aaa bbb ccc
    &lt;/div>
    
  135. Nice!

    Here’s an alternative to the JavaScript file. It’s shorter, but depends on Scriptaculous (so it’s appropriate for pages that include Scriptaculous already). The change from ‘cbb’ to /\bcbb\b/ should be copied to the non-Scriptaculous version too, so that it won’t replace class names such as “ccbbaa” with “ccbaa”.

    function wrapCbb(e) {
        function build(className, children) {
            return Builder.node('div', {className: className || ''},
                                children || []);
        }
        //  Create a new div, give it the original div's class attribute,
        //  and replace 'cbb' with 'cb'
        var i1;
        var outer = build(e.className.replace(/\bcbb\b/, 'cb'),
                       [build('bt', [build()]),
                        build('i1', [i2 = build('i2')]),
                        build('bb', [build()])]);
        // Change the original div's class name and replace it with the new div
        e.className = 'i3';
        e.parentNode.replaceChild(outer, e);
        i2.appendChild(e);
    }
    
    Event.observe(window, 'load', function () {
        $A(document.getElementsByClassName('cbb')).each(wrapCbb);
    });
    
  136. That’s terrific Thank you for the great job!

  137. Check out the RuzeeBorders that have support for corner-rounding, Mac OS X like shadows, and other neat effects. You don’t need to create images anymore while maintaining the same rendering quality.

  138. I love this way of making borders. Very elegant.

    However, there seems to be a bug in Internet Explorer 7 Beta 2 that makes the borders image hang down below everything else. Any ideas on how to work around it?

  139. I’ve figured out a fix for the IE7 problem I mentioned above. Add to the CSS for the i1 class (the left border) “height: 100%;”

  140. Ok, I’m stuck.

    This works great and I was able to style it with my own graphics. The problem is I need to position it absolutely.

    (for simplicity I am using the IE CSS only version as my base - no JS)

    If I set position: absolute on the div.cb and put just a small amount of content in it (like one word) Firefox collapses the box to surround just the content. IE, however, still renders the box at 100% width.

    Any ideas on how to defeat this behavior? My afternoon of hackery has produced nothing.

    Take a look at this link in both browsers to see what I mean.

  141. May 28, 2006 by Roger Johansson (Author comment)

    JZ: It seems that IE does not shrinkwrap absolutely positioned elements that either have layout or have children that have layout (in this case triggered by the various height declarations). The only solution I am aware of is to set the width of any absolutely positioned boxes. More info here: On having layout.

  142. May 28, 2006 by Roger Johansson (Author comment)

    Anders: I can’t see any problems or rendering differences when nesting boxes inside each other. Can you provide a more specific example?

  143. May 28, 2006 by Roger Johansson (Author comment)

    Steve (comment #102): Using 50% for .bt div and .bb div only works if the background images do not use alpha transparency. If they do the transparency will overlap.

  144. May 28, 2006 by Roger Johansson (Author comment)

    Robert G (comment #113): I can’t see a problem when floating a box inside another box. Could you post more details?

  145. May 28, 2006 by Roger Johansson (Author comment)

    casey (comment #126): If you are using a wrapper div inside a cb box you can remove the border from .i3 and make sure your wrapper has a border or padding to contain any vertical margins.

  146. May 28, 2006 by Roger Johansson (Author comment)

    Alister (comment #127): Thanks. There is indeed a problem if you have used the id of the styled box for anything. It will be fixed in an update to this technique.

  147. May 28, 2006 by Roger Johansson (Author comment)

    Örjan (comment #131): I’m working on an update that will let you apply this technique to any element, not just divs. So yes, it is possible.

Comments are disabled for this post (read why), but if you have spotted an error or have additional info that you think should be in this post, feel free to contact me.