[Ask SM] Transparent Background, Positioning Problem

Advertisement

This is our fourth installment of Ask SM, featuring reader questions about Web design, focusing on HTML, CSS and JavaScript. In this post we’ll cover how you can style only the text inputs, refreshing a content-block automatically, how to avoid some positioning problems and create and use transparent div-backgrounds; we also discuss further CSS-related problems and deliver answers to a couple of quickfire questions.

If you have a question about CSS or JavaScript, feel free to reach me (Chris Coyier) via one of these methods:

  1. Send an email to ask [at] smashingmagazine [dot] com with your question.
  2. Post your question in our forum.
  3. Or, if you have a quick question, just tweet us @smashingmag or @chriscoyier with the hashtag #asksmcss.

Please note: I will do what I can to answer questions, but I will certainly not be able to answer all of them. However, I hope you use the forums to post questions because that gives you the best opportunity to get help from the community.

You may be interested in the following related posts:

Styling Only Text Inputs

DonRonito writes:

Since I use a CMS for generating forms, I have encountered a problem with styling of forms that are auto-generated. I can use input[type=text], which only styles the text inputs, but it does not work in IE. I wonder if there is another good way to do this.

Hi Don, as you seem to know, that selector is what is known as an attribute selector in CSS. You can use it on any element if you intend to select only elements with particular values of inputs. For example, a[title="home"] is a valid attribute selector, which will target elements like this <a title="home" ... >. In the case of inputs, this is particularly useful because there are so many different types: text, submit, radio, image, etc., but they are all <input>’s. You may want to apply a width to text inputs but not radio buttons, for example.

As you also found out, IE 6 and below doesn’t like attribute selectors (it just ignores them). Huge bummer. One solution, which was pointed out right away in the forums, is to apply an ID or class to these inputs. You could then use the ID or class to target them in the CSS and apply your unique styling that way, without fear of affecting other types of inputs. But you say that these forms are being generated by a CMS, which seems to imply that you don’t have this type of fine-grained control.

A bit of a rough situation you have there. But there is hope, if you don’t mind a little JavaScript. If you use jQuery, it supports CSS selectors that accurately do the selecting for you, even in IE 6:

$("input[type=text]").css({
		// apply styling
});

Perhaps an even better solution is to use the Dean Edward’s ie7-js script, which automatically makes your CSS attribute selector just work, as well as fix a slew of other IE 6 bugs:

<!--[if lt IE 7]>
<script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE7.js" type="text/javascript"></script>
<![endif]-->

Auto-Refreshing RSS Content

Niki Brown writes:

I followed your SimplePie tutorial (Ask SM, 3rd ed.) and made Banana Tweets. But now I’m wondering how I would get the tweets to auto-refresh, say, every 20 seconds.

tweets

Hey Niki, great question! We can get this done fairly easily with the AJAX powers of jQuery. We can start where we left off last time. In that example, when the page has loaded, SimplePie works its magic by fetching the RSS (or Atom) feed data and displaying it.

Instead, we’ll pull out all that SimplePie PHP and put it into a separate file (which we’ll call feeder.php).

<?php
    require_once('inc/simplepie.inc');

    $feed = new SimplePie();

    $feed->set_feed_url(array(
    	'http://search.twitter.com/search.atom?q=twitter'
    ));

    $feed->enable_cache(true);
    $feed->set_cache_location('cache');
    $feed->set_cache_duration(10);

    $feed->init();

    $feed->handle_content_type();

    if ($feed->error): ?>

        <p><?php echo $feed->error; ?></p>

    <?php endif; ?>

    <?php foreach ($feed->get_items() as $item): ?>

    	<div class="chunk">

    		<h4 style="background:url(<?php $feed = $item->get_feed(); echo $feed->get_favicon(); ?>) no-repeat; text-indent: 25px; margin: 0 0 10px;"><a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?></a></h4>

    		<p class="footnote">Source: <a href="<?php $feed = $item->get_feed(); echo $feed->get_permalink(); ?>"><?php $feed = $item->get_feed(); echo $feed->get_title(); ?></a> | <?php echo $item->get_date('j M Y | g:i a T'); ?></p>

    	</div>

    <?php endforeach; 

?>

This “feeder” file could be loaded directly, but it would be completely unstyled. The point is to use some AJAX to load the content from that page and plug it into our real page. Then we can set up a JavaScript interval to call this file every 20 seconds and replace the current content:

<script type="text/javascript">

    function getFresh() {

        $("#loadArea").fadeOut(400, function() {
$("#loadArea").load("feeder.php", function() {
                $("#loadArea").fadeIn();
            });
        });

    };

	$(function(){
		getFresh();
		var int = setInterval("getFresh()", 10000);
	});

</script>

Note that the above code is dependent on jQuery.

VIEW DEMO   DOWNLOAD FILES

Positioning Blues

James Bull writes:

On my website, I was wondering how to avoid a scaling problem. If you drag the browser smaller than the width of the page, there are issues with my top-corner images. I’ve tried various min-width values on different containers and can’t seem to solve it. Know how to do this?

logo push

Hey James, first of all, your background looks like it is a combination of four different layered images. One on the html element, body element, image_left, and image_right. Because yours is just a centered fixed-width website, you could get this done with just two: one for the background texture, and the other for all the other frills.

But in looking at the problem at hand, the percentage positioning you are using for those “corner” images is the problem. Your image “image_left.png” is set to a right position of 50%. That means this image will be perfectly willing to hang off the left side of the browser window without limit and without causing scroll. The “image_right.png” container is set to a left position, which will cause horizontal scroll (weird, huh?).

The quick fix in your case is to make sure the viewport area cannot shrink any narrower than the width of image_left.png (876 pixels). So just set:

html {
	min-width: 876px;
}

In your particular design, you might wanna beef that up to about 912px to keep your full name visible at all times. Remember that IE 6 doesn’t support min-width, but it looks like you hide those images for IE 6 anyway.

Transparent Div Background

Louie Livon-Bemel writes:

Is there an easy way to give a div’s background a low opacity but have the content be normal. The only way I know of is to position a second div behind the content with z-index and give the background div a lower opacity. And if possible, I’d want this to work in all browsers.

png24

They way you describe works, but going to those lengths is probably unnecessary. If the background of the div is an image, you could lower its opacity in Photoshop and save it as an alpha-transparent PNG (PNG-24 in Photoshop). Then use that PNG as your background image. You’ll need PNG hack for IE 6. If you have a solid-color background, you could use a repeating 1×1 pixel alpha-transparent PNG of that color, or use RGBa.

rgba

backgrounds

To Use A CSS Framework?

Andrew Turner writes:

I was wondering whether you think it best to use available CSS Frameworks for projects (e.g. Blueprint CSS) or to build one yourself from the ground up? Are there any disadvantages or advantages to using frameworks?

blueprint

The common arguments against frameworks are 1) bloat — that is, a bunch of unnecessary CSS for alternate grids you may never use — and 2) semantics problems. Your markup will be using things like <div id=grid_13_b .. />, which isn’t very helpful or semantic.

My argument is that CSS is not (for the most part) a very complicated language. Writing it from scratch for each project isn’t all that time-consuming and results in exactly what you need and nothing else.

All that being said, I do believe that if you dedicate some time to learning all the ins and outs of a particular framework, it could potentially save you some time as well as lend a familiar feel to all of your projects. If Blueprint CSS is good enough for Jeff Croft and Blueflavor, it can work for you.

Image The Size Of A Table Cell

William Woolard writes:

I’ve created a calendar using PHP that generates the days within table cells. I’ve modified it to add a class="currentdate" to the current date. The single-digit day cells are one size (1) and the double-digit day cells are twice as large (24). Is there a way to apply a background image to the cell that adjusts according to the size of the cell? For instance, the background is a circle, as if the day has been circled (for single-digit days) and expands to look like an oval on the days that are double digits?

This is really a rock-and-a-hard-place scenario. CSS background images are not resizeable, so that’s out. The other way to include an image on the page is with an inline <img ... />. These are resizeable, so we may be on to something. The go-to method for stretching an image to the size of its parent is to use absolute positioning and set the top, bottom, left and right values to zero. Unfortunately, the parent needs to have relative positioning for this to work, and table cells do not accept relative positioning.

Divs, however, do accept relative positioning. So, a div inside will stretch it to the width of the parent table cell, but not necessarily the height, and we are unable to force it because of the no-relative-positioning-on-table-cells problem mentioned above.

With CSS alone, we can almost get it:

<td class="currentDay">
   <div>
      <img src="images/circle.png" class="circle" alt="" />
      19
   </div>
</td>
td                  { padding: 5px; vertical-align: middle; text-align: center; }
td div              { position: relative; }
.circle             { position: absolute; top: 0; left: 0; right: 0; bottom: 0; }

The height is still a problem though, and I don’t see a purely CSS solution. What we need to do is set the height and width of that image to be the exact height and width of the table cell that it’s in. We can lean on a bit of jQuery to do that math for us:

$(function() {

    var theImage = $(".circle");

    var theCell = theImage.parent().parent();

    var theWidth = parseInt(theCell.css("width")) + parseInt(theCell.css("padding-left")) + parseInt(theCell.css("padding-right"));

    var theHeight = parseInt(theCell.css("height")) + parseInt(theCell.css("padding-top")) + parseInt(theCell.css("padding-bottom"));

    $(".circle")
        .width(theWidth)

        .height(theHeight)
        .css({
            "top": -parseInt(theCell.css("padding-top")),
            "left": -parseInt(theCell.css("padding-left"))
        });

});

Kind of a lot of work for such a seemingly simple problem, but at least it works and is adaptable. If anyone can figure out a purely CSS solution, I’d love to see it!

cell

VIEW DEMO

Styling the HTML Element

Aaron Bazinet writes:

Can you style the HTML element directly, such as by applying a background image and color to it. I remember someone mentioning it once, but is it safe/valid to do, or bad mojo?

Hey Aaron, just to clarify for readers, all Web pages have an <html> element that wraps the entire page. The tag usually comes just after the DOCTYPE specification. So is something like this do-able in CSS?:

name="code">html { background-color: #ccc; }

Yep, it is, should be fine. And in fact, it can fix some otherwise weird issues. I believe you need to go all the way back to IE 5 to see problems with it, which isn’t a concern anymore. Sitepoint has a little more info on this and reminds us to avoid positioning this element.

Quickfire Questions

Have you ever used or heard of Sweetcron? We need a tutorial on theming it! Please help!

I have heard of Sweetcron. I think it is incredibly well-done self-hosted life-streaming software. It was produced by Tokyo-based Web developer Yongfook, who uses Sweetcron on his personal website. I did a tutorial on building a custom life-stream website with it on NETTUTS.

Should I enroll in a Web design program that is geared more to the “design” end (artsy) or the “development” end (coding)? Which one will benefit me more in making Web design a full-time career?

If you are lucky enough to be looking at colleges and programs that give you that kind of choice, I think you will do well either way. I got a multimedia/graphic design degree, and we didn’t even once look at HTML (not kidding). Because you said at the end, though, that you want to make “Web design” your full-time career, the “design” path would seem to make more sense than the “development” path.

All of my images have a few pixels of extra background space along the bottom length.

In this particular scenario, a div is wrapping the image, creating the double-border effect. The image inside is an inline element, so the space following the <img ... /> tag and the closing div tag is apparently creating a line break and causing the gap. A quick fix is to make the image a block-level element, which eliminates the gap.

.image img { display: block; }

space

That wraps up another installment of Ask Smashing Magazine! If you have questions to ask, refer to the top of this article for ways to submit your questions.

Related posts

You may be interested in the following related posts:

(al)

CSS,

↑ Back to top

I create websites and help others create better websites through writing and speaking. I consider myself a lucky man for getting to work in such a fun and rewarding field.

  1. 1

    Comment no.1 (!) Interresting article :)

    0
  2. 2

    You can also set a width on your HTML element to kill the need for a #page-wrap.

    0
  3. 3

    As a reminder, here is the CSS3-color working draft :
    http://www.w3.org/TR/css3-color/#rgba-color
    « Note. If RGBA values are not supported by a user agent, they should be treated like unrecognized values per the CSS forward compatibility parsing rules. RGBA values must not be treated as simply an RGB value with the opacity ignored. »

    On this point, Netscape 4.8 and IE 5.5 are more standard compliant than IE8 :/

    0
  4. 4

    Nic3 w0rk guys…. n00bs r3ally g0nna lik3 this 0n3 !!

    DKumar M.
    @instantShift

    0
  5. 5

    I like the solution to styling text-only inputs – will definitely be using that one!
    Just a little note on using transparent png’s as background images – IE7 doesn’t like tiling really small transparent images (i.e. 1px by 1px) and will massively slow down page rendering time. Solution is to create bigger images that don’t tile as much – there won’t be much impact on file size either.

    Ryan :)

    0
  6. 6

    Awesome edition of AskSM, Chris!

    Could you accomplish the calendar situation by using CSS sprites? It would necessitate having an image that has both circles, of course.

    0
  7. 7

    thx,

    found exactly what i needed in this article.

    0
  8. 8

    On the transparent div background:
    I just ran into this a couple of days ago. While creating a PNG with diminished opacity is by far the easiest, like so many websites today, I needed rounded corners and the background needed to expand to the amount of text in the div on top of it.

    What worked best, but I admit was more work, was to use the z-index trick and position the transparent background absolutely. Then a one line jQuery automatically adjusts the height/width based on the above layer’s text. No images, no sliding windows, works in ie7 (with no hacks) and I can very easily adjust the color of the background as needed (something clients love to do).

    0
  9. 9

    always a pleasure to read your article, great job Chris!

    0
  10. 10

    All incorrect, here’s how you do it:

    Some Text Input

    That’s the best way to do it no matter what. If you use JQuery for CSS then you’re mixing presentation with behavior. JQuery styles should only be used for active styles (Things that change because of events on in the DOM). If your CMS doesn’t support what I’m talking about than you should do this with JQuery instead:


    $('input[type=text]').attr('class', 'text')

    Those two versions are hands down The way to do it.

    0
  11. 11

    well, really nice. Apparently Smashing magazine is too NOOB to know how to encode HTML properly so my first example is wiped off the face of the Earth.

    0
  12. 12

    Love the auto-refresh RSS tute- really cool simple stuff. This would be super cool combined with Remy Sharps’ ‘spy’ effect- I’ll put it on the to-do list. Thanks!

    0
  13. 13

    Ahhh. I have so much to learn!

    0
  14. 14

    Great info — thanks!

    0
  15. 15

    So use blueprint or not? has anyone paid attention to the development of css3? css will no longer be a simple language : (

    0
  16. 16

    Tiago Pastorello

    April 17, 2009 10:04 am

    IE sux!

    0
  17. 17

    Awesome tutorial… i’ve seen a lot of these transparent png effects on a lot of sites these days… check this one in IE6 and IE7 and see the difference: LINK

    0
  18. 18

    Nice article. The .png hack for IE6 is not a good way to fix transparency in my opinion… if there are a lot of png files to fix, the browser will get pretty slow and will even crash sometimes. The method I normally use is to save the transparent png as normal in Photoshop, then load it into Fireworks. Fireworks allows you to resave the image as an 8bit png WITH alpha transparency. IE6 loads anything above 50% opacity as normal, and below 50% is completely transparent (instead of that blueish haze).
    This makes files load in IE6 to keep the function of the site. It also hopefully looks just bad enough that users might think “hmm maybe I should upgrade my browser”.
    For really picky sites, I just use alternate images for IE6.

    0
  19. 19

    Great tips, thanks!

    To the person asking about a web design/development track, I would say that if you are interested at all in designing the front-end (navigation, interfaces, graphics, layout–what people generally mean by web design) then you should focus on *design*; that is, visual communication fundamentals you’d learn in a graphic design program like typography, contrast, and color theory. Nuts and bolts are relatively easy to learn and easier to get feedback on. Design essentials are harder to self-teach and you will benefit greatly from feedback and critique in an academic/group environment.

    0
  20. 20

    Another way to get rid of the image space at the bottom is to use:

    img {
    vertical-align: top;
    }

    0
  21. 21

    Great Article, Chris Coyier you rock.

    @JoshTummel: hey thats a good idea. I didn’t know that. I will try that definitely.

    Thanks

    0
  22. 22

    For “Image The Size Of A Table Cell”, you could just use the “sliding doors” method in CSS since the only thing expanding is the width.

    0
  23. 23

    To whoever asked if they should develop or design websites… identify what you like and who you are; do you like to buy nice things because they are nice even if they don’t work very good or because they work good even though they are ugly? the truth is, you should try to learn as much as possible of both, it will help you communicate better and understand what the extent of the possibilities are. I myself am a very visual person, I am attracted by colors, and shapes and styles so I like design; you might be very analytical and care more about how something works, art galleries don’t attract you as much as a machine shop, what makes things spark, experimenting with numbers and interacting letters no matter what their shape. Identify who you are and what you like; the choice will be clear.

    0
  24. 24

    ie6 png fix… working perfectly!!! FINALLY!!! great/very interesting article!!! keep it up!
    cheers

    0
  25. 25

    The link to the [Ask SM] Transparent Background, Positioning Problem is broken, it has some gobbledygook at the end.

    0
  26. 26

    Sorry, I meant “Other Weird Issues.” The gobbledygook at the end is the proper link, it just has another link to this very article at the beginning. Here’s the proper link.

    0
  27. 27

    that is quite interactive ..lovely post

    0
  28. 28

    [Ask SM] are extremely useful, probably my fav articles!
    I hope the fix for transparent PNG works, ’cause everything I’ve tried did not.

    0
  29. 29

    For the Image The Size Of A Table Cell:

    I know CSS3 is still not out yet, but there will be a new property “background-size”. With this, you could simply define the current day class as using the circle image as the background-image and then set the background-size to 100%. That’s not really helpful right now, I know, but it’s something to keep in mind.

    0
  30. 30

    These are some really nice tips! Thank you!

    0
  31. 31

    Wow,Thanks
    Link

    0
  32. 32

    Great post…

    Thanks

    0
  33. 33

    These are some pretty novice questions. That’s surprising …

    0
  34. 34

    Styling Only Text Inputs [IE6]

    By using css expressions, the IE6 problem can be solved with an extra line of css. I put this in my ie6 css stylesheet, and have never had to worry since:


    input {
    ie-fake-class: expression( this.doneFakeClass ? "0" : (function(el) { var cls=el.className.split(/s+/); cls.push(el.type); el.className = cls.join(' '); el.doneFakeClass=true; return 1;})(this) );
    }

    Note that unlike normal css expressions, this only executes once, so there is no performance problem.

    0
  35. 35

    Teddy Zetterlund

    April 20, 2009 5:29 am

    For “Image The Size Of A Table Cell”. I’m not offering a solution to the question itself, but a alternative solution to the example. Here’s an example of how to mark the current day with a red circle by only using CSS: http://gist.github.com/98530

    What might be an issue here is that it’s only a circle in browsers supporting browser-radius (safari, chrome and firefox), but in the others you get a square instead which might be fine on some sites).

    0
  36. 36

    I’ve been enjoying the Ask SM series very much; keep it up! Thx

    0
  37. 37

    I’ve been dealing with transparent overlays with non-transparent text on a lot of recent projects (darn those designers and their really good ideas!) and came up with this: http://kiveo.net/transparent-backgrounds/

    0

Leave a Comment

Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that comments are moderated and rel="nofollow" is in use. So, please do not use a spammy keyword or a domain as your name, or else it will be deleted. Let's have a personal and meaningful conversation instead. Thanks for dropping by!

↑ Back to top