Best css questions in March 2011

How can you flip website upside down in IE ? (for the April 1st)

27 votes

We are making April 1st prank in our office, and wanted to flip our corporate website upside down for several hours tomorrow :)

My patch works everywhere but not in IE... Can anyone help ?

<script type="text/javascript">
   document.body.style.MozTransform = 'rotate(180deg)';
   document.body.style['-webkit-transform'] = 'rotate(180deg)';
</script>

A slightly simpler version for IE (no matrix stuff):

body {
  filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2);
}

17 votes

I'm currently working on a site, and somewhere in my mass of stylesheets, something is killing performance in IE. Are there any good CSS profilers out there? I'd like a tool that can pinpoint rules that are killing performance.

Before you ask, I've disabled JavaScript, opacity, and box-shadow/text-shadow rules. The page is still jumpy. :/ If I disable all CSS, it runs great.

I need a tool that can profile the page and report where the CSS bottlenecks are.

So, I finally got around to writing a JavaScript function that indexed all of my CSS classes on the page and then individually toggled them, while scrolling the page. This immediately pin-pointed the errant class, and from there, I was able to determine errant property. Turns out that border-radius on an element that contains many children (e.g. a body level div) performs incredibly poorly on IE9.

I've started a github repo for my CSS stress test: https://github.com/andyedinborough/stress-css

From there, you can install a bookmarklet to easily run the test on any page.

How to disable resizable property of TextArea?

11 votes

I want to disable the resizable property of a TextArea.

Currently, I can resize a TextArea by clicking on the bottom right corner of the TextArea and dragging the mouse. Is it possible to disable this? Thanks in advance.

Use the following CSS rule to disable this behavior for all TextArea elements:

textarea {
    resize: none;
}

If you want to disable it for some (but not all) TextArea elements, you have a couple of options (thanks to this page).

To disable a specific TextArea with the name attribute set to foo (i.e., <TextArea name="foo"></TextArea>):

textarea[name=foo] {
    resize: none;
}

Or, using an ID (i.e., <TextArea id="foo"></TextArea>):

#foo {
    resize: none;
}

Note that this is only relevant for WebKit-based browsers (i.e., Safari and Chrome), which add the resize handle to TextArea controls.

Standard way to detect mobile mail client?

11 votes

This question is similar to "Standard way to detect mobile browsers in a web application based on the http request" except for mail clients. For instance, if an email message is opened on the built-in iPhone mail client it will display a version of the message specially formatted for the iPhone. If opened on an tablet or desktop it will display as the complete, full-size version of the email. This is similar in principle to web sites that have mobile-friendly versions of the site that load automatically by detecting the user-agent - but for email clients.

So - is it possible to detect the mail client being used to open an email and format the message accordingly? Perhaps a way to detect the screen resolution?

You can try to apply @media css queries that target specific browsers like mobile devices. There is a good introduction on the campaignmonitor help website but be aware, it probably is only supported in a hand full of browsers and devices, iOS being on of them luckily :)

Basically you are defining css styles that target specific screen widths so that you can optimize your email for limited screen space.

@media only screen and (max-device-width: 480px) { ... }

When talking really detection and displaying a totally different email, that's really impossible since you are talking about javascript there and that's not done in emails and probably won't even work in 99% of all email clients. But you can go a loooong way with @media queries.

jQuery .css() function not returning expected values

11 votes

Alright, I've search the jQuery docs (needs somebody devoted to maintaining), I've searched SO, and I've searched Google. I can't find the answer to this question.


In Words

In the past, I remember jQuery working like this:

$('#myObj').width() returns the computed width of #myObj.
$('#myObj').css('width') returns the width as it is entered into the CSS stylesheet.

Now, any jQuery package I use returns the exact same number no matter which method I use.

$('#myObj').width() returns the computed width of #myObj as an integer (float?).
$('#myObj').css('width') returns the computed width of #myObj as a string with px on the end.


In Pseudocode

#myobject{
    width: 14em;
    height: 14em;
}

<div id="myobject">Has Text</div>

<script type="text/javascript">
    $( '#myobject' ).click(function(){
        alert($(this).css('width') + "\n" + $(this).width());
    });
</script>

//Always alerts "224px [newline] 224"
//Expected to alert "14em [newline] 224"

These pixel-based return values are almost completely useless, as I need to do calculations based on what's actually in the CSS. For example, I want to do math on the left position of an element, but I can't because it keeps returning pixel values, which are worthless in an em-based design.

Is there any way to get the actual values out of the CSS in jQuery?
Is this a jQuery bug, or am I missing something?

Here's a jsfiddle: http://jsfiddle.net/yAnFL/1/.


Resolution

Apparently, this is the intended result.
I have decided to use this plugin to do conversions for me.
Taking away control of CSS seems like a poor choice in the jQuery design.

This is not a complete answer to your question but it may be a working solution to caclulate the em values. I adapted this function from here. And here is the updated fiddle.

$.fn.emWidth = function(){
    var wpx = this.width();
    var temp = $('<div />').css({
        width:'1em', 
        position: 'absolute'
    });
    this.append(temp);
    var oneEm = temp.width();
    temp.remove();
    var value = wpx/oneEm;
    return Math.round(value*100)/100;
};

Background of body element

10 votes

When you style the background of the body element, why does the styling affect the entire screen and not just the body element itself? Let's say i create the following rule:

body {width: 700px; border: 1px dotted red; background-color: blue;}

I find that the border shows up as 700px wide as i would expect, but the background color occupies the entire browser viewport. Why?

Quote from http://www.w3.org/TR/CSS21/colors.html

The background of the root element becomes the background of the canvas and covers the entire canvas, anchored (for 'background-position') at the same point as it would be if it was painted only for the root element itself. The root element does not paint this background again.

The body element is the root-element, and thus, as required by the CSS rules it loses its background style and the background style is applied to the containing canvas (the webpage area in the browser), therefor the entire screen is blue. The other properties stay with the element (e.g. the border).

my lovely dream : slanted text areas in div

10 votes

I was wondering if any of you knew if it was possible to make anything looking like this? I know about http://www.infimum.dk/HTML/slantinfo.html but I can't put any text in the slanted areas.

Here's an image of what I'm trying to do:

enter image description here

Did it with a bit of javascript: http://jsfiddle.net/billymoon/AvmE8/

But that is just for convenience, you can do the same with HTML.

Will not apply to all circumstances, and will need a little tweaking, but can be made to work for things you know the approximate length of - or know the upper bound of.

html:

<div id='left'>whatever text</div><div id='right'>random text</div>

css:

#left, #right{
    text-align: justify;
    position: absolute;
    width:60%;
    right:0;
}
#right{
    right:auto;
    left:0;
}

js:

for (i = 1; i < 40; i++) {
    $('<div />').css({
        border: '1px solid silver',
        height: 10,
        width: (5 * i),
        float: 'left',
        clear: 'left'
    }).prependTo($('#left'))
    $('<div />').css({
        border: '1px solid gold',
        height: 10,
        width: (200 - (5 * i)),
        float: 'right',
        clear: 'right'
    }).prependTo($('#right'))
}

jQuery Masonry from bottom up

9 votes

Does anyone know how to make jQuery masonry stack from the bottom up? I wrote some rudimentary JS to stack things from bottom up but it couldn't do masonryish stuff like stacking the next brick on the shortest column and bricks that span multiple columns. Since I'm not good with Math, looking at the source code just makes me dizzy.

Stacking from bottom up

Anyone want to try?

You're going to laugh at how easy this is to do, but you will need to modify the plugin (demo).

Basically, I changed line 82 - 85 from this (all that needed changing was top to bottom but I added both so you can switch back and forth):

    var position = {
      left: props.colW * shortCol + props.posLeft,
      top: minimumY
    };

to this:

    var position = (opts.fromBottom) ? {
      left: props.colW * shortCol + props.posLeft,
      bottom: minimumY
    } : {
      left: props.colW * shortCol + props.posLeft,
      top: minimumY
    };

Then added the option in the defaults:

  // Default plugin options
  $.fn.masonry.defaults = {
    singleMode: false,
    columnWidth: undefined,
    itemSelector: undefined,
    appendedContent: undefined,
    fromBottom: false, // new option
    saveOptions: true,
    resizeable: true,
    animate: false,
    animationOptions: {}
  };

Now you can just use the plugin like this:

$('#masonry').masonry({ fromBottom: true });

Update: I also forked the repository on github, so you can just download the changes if you don't want to do them yourself.

What are the pros and cons of adding <script> and <link> elements using JavaScript?

9 votes

Recently I saw some HTML with only a single <script> element in its <head>...

<head>
    <title>Example</title>
    <script src="script.js" type="text/javascript"></script>
    <link href="plain.css" type="text/css" rel="stylesheet" />
</head>

This script.js then adds any other necessary <script> elements and <link> elements to the document using document.write(...): (or it could use document.createElement(...) etc)

document.write("<link href=\"javascript-enabled.css\" type=\"text/css\" rel=\"styleshet\" />");
document.write("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js\" type=\"text/javascript\"></script>");
document.write("<script src=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js\" type=\"text/javascript\"></script>");
document.write("<link href=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.0/themes/trontastic/jquery-ui.css\" type=\"text/css\" rel=\"stylesheet\" />")
document.write("<script src=\"validation.js\" type=\"text/css\"></script>")

Note that there is a plain.css CSS file in the document <head> and script.js just adds any and all CSS and JavaScript which would be used by a JS-enabled user agent.

What are some of the pros and cons of this technique?

The blocking nature of document.write

document.write will pause everything that the browser is working on the page (including parsing). It is highly recommended to avoid because of this blocking behavior. The browser has no way of knowing what you're going to shuff into the HTML text stream at that point, or whether the write will totally trash everything on the DOM tree, so it has to stop until you're finished.

Essentially, loading scrips this way will force the browser to stop parsing HTML. If your script is in-line, then the browser will also execute those scripts before it goes on. Therefore, as a side-note, it is always recommended that you defer loading scripts until after your page is parsed and you've shown a reasonable UI to the user.

If your scripts are loaded from separate files in the "src" attribute, then the scripts may not be consistently executed across all browsers.

Losing browser speed optimizations and predictability

This way, you lose a lot of the performance optimizations made by modern browsers. Also, when your scripts execute may be unpredictable.

For example, some browsers will execute the scripts right after you "write" them. In such cases, you lose parallel downloads of scripts (because the browser doesn't see the second script tag until it has downloaded and executed the first). You lose parallel downloads of scripts and stylesheets and other resources (many browsers can download resources, stylesheets and scripts all at the same time).

Some browsers defer the scripts until after the end to execute them.

The browser cannot continue to parse the HTML while document.write is going on and, in certain cases, when the scripts written are being executed due to the blocking behavior of document.write, so your page shows up much slower.

In other words, your site has just become as slow as it was loading on a decades-old browser with no optimizations.

Why would somebody do it like this?

The reason you may want to use something like this is usually for maintainability. For instance, you may have a huge site with thousands of pages, each loading the same set of scripts and stylesheets. However, when you add a script file, you don't want to edit thousands of HTML files to add the script tags. This is particularly troublesome when loading JavaScript libraries (e.g. Dojo or jQuery) -- you have to change each HTML page when you upgrade to the next version.

The problem is that JavaScript doesn't have an @include or @import statement for you to include other files.

Some solutions

The solution to this is probably not by injecting scripts via document.write, but by:

  1. Using @import directives in stylesheets
  2. Using a server scripting language (e.g. PHP) to manage your "master page" and to generate all other pages (however, if you can't use this and must maintain many HTML pages individually, this is not a solution)
  3. Avoid document.write, but load the JavaScript files via XHR, then eval() them -- this may have security concerns though
  4. Use a JavaScript Library (e.g. Dojo) that has module-loading features so that you can keep a master JS file which loads other files. You won't be able to avoid having to update the version numbers of the library file though...

Images in CSS or HTML as data/base64

8 votes

To reduce the number requests on the server i have embended some images as BASE64 directly into the css. (Its automated in the build process)

like this:

background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAFWHRTb2Z0d2FyZQBBZG etc...);

Is this a good practice? Are there some reasons to avoid this? Are there some major browser that dont have data url support?

Bonus question: Does it make sense to do this for the CSS & JS also?

Is this a good practice? Are there some reasons to avoid this?

It's a good practice usually only for very small CSS images that are going to be used together (like CSS sprites) when IE compatibility doesn't matter, and saving the request is more important than cacheability.

It has a number of notable downsides:

  • Doesn't work at all in IE6 and 7.

  • Works for resources only up to 32k in size in IE8.

  • It saves a request, but bloats the HTML page instead! And makes images uncacheable. They get loaded every time the containing page or style sheet get loaded.

  • Base64 encoding bloats image sizes by 33%.

  • If served in a gzipped resource, data: images are almost certainly going to be a terrible strain on the server's resources! Images are traditionally very CPU intensive to compress, with very little reduction in size.

GUI alternative to <select> when you have a lot of options

7 votes

A <select> might be good for choosing between 3-15 simple items, but how do you deal with 15-100+?

The simplest option would be to just have a plain <select> with a lot of <option>s, but it's not very user friendly. There's a lot of scrolling and it might be hard to find the option you are looking for. The benefit is that you can (maybe with scrolling) see all the options you have.

A more advanced option would be to have a text field with autocomplete. A user types in a letter or two, and search results come back which you choose from. It makes it easier to find the option you are looking for - if you know what you are looking for. The drawback is that the user can't see all the options.

An even more advanced option would be to build a "search, list and choose" widget which defaults to show X items, but allows you to search. An advantage of this approach is that I can allow search on multiple attributes and not just the name of the item which is to be selected.

  1. What solutions have you deployed in these situations?
  2. Is there a jQuery plugin I should know about?

  1. The solution that I like to use is provide the user a select list with all the options (should they want to look through it), but provide an autocomplete feature which searches through the list as they type into it. Sort of a hybrid of your first and second options.
  2. As for plug-ins, there are a number out there (as well as documentation which will lead you to more) that can help you here:

How do I inspect CSS pseudo classes with firebug?

7 votes

I am struggling with a reluctant a:hover css style which I cannot override.

I tried to inspect the element in firebug, but I cannot see why it won't work. I don't even see how to properly inspect a :hover css event in firebug.

I have seen:
Hover Inspection in Firebug http://blog.borngeek.com/2010/04/16/hover-inspection-in-firebug/
but I have not figured out how to reproduce the steps mentioned there.

Also: Pseudo-Phantoms http://meyerweb.com/eric/thoughts/2009/11/03/pseudo-phantoms/

How do I inspect/debug CSS pseudo classes like :hover with firebug?

It's pretty easy. Just select the element you want to inspect. And then, from the panel on the right side, click on the Style menu item. There you can select the pseudo class :hover

EDIT

Here's an image : enter image description here

List of css vendor prefixes?

7 votes

Besides the following list, are there other css vendor prefixes that are important for web development? Are my definitions correct? Should I be more specific about mobile browsers (mobile Webkit, e.g.)

  • -khtml- (Konqueror, really old Safari)
  • -moz- (Firefox)
  • -o- (Opera)
  • -ms- (Internet Explorer)
  • -webkit- (Safari, Chrome)

Does this list (which also contains mso-, -wap-, and -atsc-) add anything of value?

These are the ones I'm aware of:

  • -ms- Microsoft
  • mso- Microsoft Office
  • -moz- Mozilla Foundation (Gecko-based browsers)
  • -o-, -xv- Opera Software
  • -atsc- Advanced Television Standards Committee
  • -wap- The WAP Forum
  • -webkit- Safari, Chrome (and other WebKit-based browsers)
  • -khtml- Konqueror browser
  • -apple- Webkit supports properties using the -apple- prefixes as well
  • prince- YesLogic
  • -ah- Antenna House
  • -hp- Hewlett Packard
  • -ro- Real Objects
  • -rim- Research In Motion
  • -tc- Tall Components

How can I stay organized when writing CSS?

7 votes

Possible Duplicate:
How to Manage CSS Explosion

One of the most difficult things I find is keeping my stylesheets organized. I usually start out with writing a small reset section. I then write the layout blocks, and continue progressively adding styles as I write my HTML blocks.

After the first two steps, though, everything turns into a mess. Styles get add, removed, forgotten, based on my whimsical HTML coding, which is changed often. I can't find a logical way to separate and classify my CSS.

I found myself creating separate sheets for the default style, the navigation, and the layout.

After I wrote my footer's CSS, I couldn't figure out if it should go into the default stylesheet, the navigation one, or the layout file. Its container was certainly part of the layout, its navigation menus were part navigation, but it had styles that should go into the basic stylesheet. I found myself thinking about seperating the CSS accordingly but that can't be right.

I can't find a logical way to organized my ideas into orderly classifications.

Can someone offer me any insight?

Let's approach this from the angle of a new programmer who wants to make some changes to the layout of your website.

I'm not sure whether using a framework will make things better, more abstraction, more learning curve.

I think you are on the right track with your organization.

I usually create a default.css file which contains the markup for the default fonts, colors, link styles, etc. In this file, I treat the website if it were one big chunk of pretty formatted text with embedded pictures. No <div> tag styling here. Usually this means that a lot of the formatting for the content is in there. But not that special button on the news page, that one gets a news.css on it's own.

Usually websites can be divided into parts. Header, footer, sidebar, frontpage, newspage, agenda, etc. If for instance the footer needs to be red, it's nice to see a file footer.css which indeed contains the background color.

If the link style in the footer is the same as in the sidebar, put the style declarations in both files. If the link style in the footer is the same as the main body text, it gets placed in default.css. Try to make sure it is in the first place you'd look as a new developer.

Is there an advantage to dynamically loading/unloading javascript and css stylesheets?

6 votes

Background:

I'm putting together a site that will use ajax as a primary method of changing the content. That way the main frame and images will not have to be constantly reloaded with every page change. The main frame has its own site.css stylesheet.

Question 1:

Is it worthwhile to put all the stylesheet information into a single stylesheet? I think that this would make the website less modular. Everytime a new page or content is added/removed the css would have to be updated (given the content requires different style information).

Question 1.1:

Same question but with javascript.

Question 2:

If it is worthwhile (as I think it is) to have multiple stylesheets, is it beneficial to unload a stylesheet when its not in use. For example, I load the profile.php page so I dynamically load the profile.css. The user then changes to the settings.php page, I unload the profile.css and load the settings.css. Is this constant loading/unloading going to tank performance or even save on website size?

Question 2.1

Same question as above but applied to javascript functions.

Once your javascript or css file is downloaded to the machine, it is cached by their browser. So, you don't incur the additional cost of another HTTP request. Lazy loading the scripts and stylesheets could make sense, but there is no sense in unloading these web assets once they have already been sent to the client.

It is good to use some sort of mechanism to compile your scripts and stylesheets to minimize the initial http requests to one per asset type. Having only one stylesheet and one javascript file would be an architectural nightmare in many cases, but that doesn't mean that you can't still present it to the browser that way. I use .NET, so I'm not sure how you handle this in PHP, but I'm sure the functionality is out there.