Best css questions in April 2011

CSS craziness and a new challenge :)

31 votes

I just came across a neat CSS trick. Check out the fiddle...

http://jsfiddle.net/duZAx/1/

This creates a little arrow/triangle-like effect, a "tooltip tail". This blows my mind! How does this work?!


CHALLENGE

Now, I pose a challenge to the Stack Overflow community! Is there a way to extend this CSS trick to create an effect as follows...

        enter image description here

I'm not worried about the shadow yet, but this is an interesting problem :) Can this be done using only CSS?


UPDATE TO THE CHALLENGE

I figured out the initial challenge. Here's the fiddle...

http://jsfiddle.net/duZAx/7/

Now, I pose a new challenge. How do I exactly mimic the little picture above using pure CSS, including the shadow and having it cross-browser compatible?


UPDATE TO THE NEW CHALLENGE

Here's my solution after a combination of the answers below. I haven't tested it across multiple browsers, but it looks great in Chrome.

http://jsfiddle.net/MZXCj/8/


Thanks,
Hristo

Here's an example with a box-shadow, all latest version browsers should support this

http://jsfiddle.net/MZXCj/1/

HTML:

<div id="toolTip">
    <p>i can haz css tooltip</p>
    <div id="tailShadow"></div>
    <div id="tail1"></div>
    <div id="tail2"></div>
</div>

CSS:

body {font-family:Helvetica,Arial,sans-serif;}

#toolTip {
    position:relative;
}

#toolTip p {
    padding:10px;
    background-color:#f9f9f9;
    border:solid 1px #a0c7ff;
    -moz-border-radius:5px;-ie-border-radius:5px;-webkit-border-radius:5px;-o-border-radius:5px;border-radius:5px;
}

#tailShadow {
    position:absolute;
    bottom:-8px;
    left:28px;
    width:0;height:0;
    border:solid 2px #fff;
    box-shadow:0 0 10px 1px #555;
}

#tail1 {
    position:absolute;
    bottom:-20px;
    left:20px;
    width:0;height:0;
    border-color:#a0c7ff transparent transparent transparent;
    border-width:10px;
    border-style:solid;
}

#tail2 {
    position:absolute;
    bottom:-18px;
    left:20px;
    width:0;height:0;
    border-color:#f9f9f9 transparent transparent transparent;
    border-width:10px;
    border-style:solid;
}

HTML5 Boilerplate vs. HTML5 Reset

27 votes

Hey everyone — HTML5 Boilerplate and HTML5 Reset are two HTML, CSS, and JavaScript templates with a lot of modern best practices built-in. Their goals are largely the same:

  • Fast, robust, modern Web development
  • HTML5 (duh!)
  • Cross-browser normalization (including support for IE6 and mobile browsers)
  • Progressive enhancement and graceful degradation
  • Performance optimizations
  • Not a framework, but the starting point for your next project

Obviously, they're very similar in function. In what ways are their implementations different (for example, perhaps IE-specific CSS fixes are achieved using different techniques)? Are they at all different in scope? It seems like HTML5 Boilerplate is a bit larger (build tools, server configuration, etc.), but it's hard to know where it goes beyond HTML5 Reset when it comes to the actual site that people will see.

In general, both projects set out to provide a solid starting point for developers working on web projects. They both get rid of a lot of the tedious, some-what error-prone boilerplate that many developers find themselves re-creating for each project. The details in how they go about it are slightly different, but for the most part, they achieve the same results.

HTML5Boilerplate has, as you noted, added in some build-script pieces to help developers follow best practices to speed up their pages in terms of server-side items, such as far-future expires headers, etc. where-as the HTML5Reset project is more focused on the semantics, content, and styling. For example, HTML5Reset has more example structure for the content of the page in HTML5 (to help show people how to use some of the new elements), whereas HTML5Boilerplate does not.

The response-time and page speed parts that HTML5Boilerplate includes get more and more important as more users find themselves on mobile platforms, and as Google increases the effect page response times have on page rank. There are lots of papers that show a small increase in the page response time has a measurable negative impact on how your site is used and perceived (especially in an eCommerce setting...often a 100ms slower page will get percentage less things sold).

On the CSS front, the majority of the reset style section for both projects is very much the same, with some minor differences in what the baseline is set to. The IE specific fixes, however, are largely the same, with HTML5Boilerplate asserting a bit more control than HTML5Reset over how IE styles some things like form elements (ie. check box / radio buttons and valid / invalid states)

Two major CSS areas that HTML5Boilerplate covers that HTML5Reset does not are common helper classes to assist with making sites more accessible, such as .hidden and .visuallyhidden, as well as some substantial adjustments to the print styles that serve to both make printing more similar across browsers, as well as some cost-savings and accessibility things like making background images transparent (to not waste toner), and adding the actual URL to links and the title to abbreviations.

I would highly suggest reading through both projects' info and how they do things in a side-by-side comparison because the similarities, and also the differences (and the reasoning behind them) is quite informative and has helped me to better decide what parts of each I wanted to use.

Ultimately, just like any "library" sort of project, you as the developer need to understand what you are doing and probably should tweak your baseline to meet the particular needs of the project.

Is there a way of testing CSS?

16 votes

I know that this idea has come up before - notably here and here - but no solution seems to have been given. It was largely seen as either a 'nice-to-have-but-impossible' or 'stupid idea'.

My thoughts were using jQuery to calculate computed values and compare them to expected values. For example, I could have <h1>This is a header</h1> and in theory, I should know it's font-size, colour, font-weight, etc. I can use jQuery to check that it is actually that font-size, and if not, return an error.

The advantage of this is that I don't have to sit with a checklist going through each browser - 'Is this header bold? Are these links underlined? Is this column 110px wide?' - every time I make a CSS change.

My question - is that a feasible idea? What are the major problems in implementing something like that? Has anyone done something like that before?

EDIT: Any thoughts on how to actual render the errors are welcome too. I thought of using a JavaScript file in the header of the relevant page and then adding content to the page, kind of like Firebug's on-page version. However, I'm worried that could then affect the rendering of the page. Alternatively, I could log it to the console, but I don't think IE6 has a proper console, and opening every console of every browser for every page-under-test seems a bit annoying as well.

Even if there was a way to do this, I would still feel the need to check manually.

The examples you gave aren't the types of things to typically worry about, but mostly positioning and box-model stuff. If I say h1{color:red} I feel pretty confident that it's going to be red in IE.

Getting the computed values isn't really going to help with finding out how they are rendered, it actually sounds like more work overall than just firing up IEtester. With a bit of experience you quickly learn the types of things you need to check for cross browser compatibility, and with browsers getting better and better, it's becoming less and less of an issue.

One technique that can help: Design in IE. Yes it sucks for sure, but you'll usually find that when you get it working in IE7 and then test in FF, IE8 or IE6 - it's pretty close or the differences are an easy fix compared to testing in say Chrome, and then double checking in IE7. I know that "cross browser" encapsulates more than just IE, but let's not kid ourselves; IE is the problem browser and the most widely used.

In conclusion: If there were a tool for this, it would have to be REALLY AMAZING to keep me from checking in a real browser. I think that's why people are pointing to Selenium as the solution to this.

Formatting events according to start time

15 votes

Hi,

Still working on my planner/calendar application. I'm nearly done, I got some of the harder parts working but I'm stuck at one more difficult part. I want to show my events in a grid according to their start time.

It doesn't show in this picture, but pretend there's a column with hours (8am - 11pm or so) at the left of the 25th. If an event starts at.. say, 1pm, I would like it to show somewhere in the middle of the page. If an event starts at 8:30 am, it should show between 8am and 9am.

events

I guess I could do this with tables, but I was wondering if there's another way. Is this doable with plain html/css, perhaps some Javascript? Any suggestions on what the best way would be to achieve this? If I use a table, I'm still not sure what would be the best way to do this. A cell for every thirty minutes? I have access to the start and end time of each event from my view. An event array (in this example, the 25th) looks like this:

Array

[1] => Array
    (
        [title] => Ethiek
        [description] => Ethiek: Opdracht 1
        [time_start] => 11:30:00
        [time_end] => 12:00:00
    )

[2] => Array
    (
        [title] => Project Management
        [description] => Test: Project Management
        [time_start] => 15:00:00
        [time_end] => 16:00:00
    )

[event_count] => 2

I appreciate any advice you can give me. Thanks a lot!

EDIT: Started a bounty on this because I'm still stuck and I would appreciate some feedback.

UPDATE:

I've been breaking my head over this and I honestly can't figure out the best way to do this. First of all, I think the reason I'm stuck is the way I read out my events from the db/array. This is the code I have to display the events as seen in my screenshot, don't mind my complex arrays:

        foreach($details[0] as $key => $detail)
    {
        echo "<div class='grid'>";
        $header = "<p class='detail_header'>";
        $header .= ucfirst($dates[0][$key]['name']) . ", " . $key . " " . $init['curr_month_name'];
        $header .= "<img src='" . base_url() . "assets/images/create_event.png' alt='Plan iets'></p>";

        echo $header;

        for($i = 1; $i <= $details[0][$key]['event_count']; $i++)
        {
            echo "<div class='event " . $details[0][$key][$i]['type'] . "'>";
                echo "<p class='event_title'>" . $details[0][$key][$i]['title'] . "</p>";
                echo $details[0][$key][$i]['description'];
            echo "</div>";
        }
        echo "</div>";  

    }

It's a bit of a mess, not to mention that I have the same code another time to fix some exceptions. But more importantly.. I feel like those loops don't allow me to make a lot of modifications to it. I tried adding two divs for AM and PM so I could split up the events in before-noon and afternoon blocks, and then just display the time on the event (to avoid having to work with a thousand blocks of 15 minutes). But yeah.. That didn't work out since it would put a couple of 'PM' divs if there is more than one event in the afternoon.

I'm tempted to just leave it like it is for now and just display the start/end time in the event divs.. until I figure out a better way to read them from the array and display them.

Any help/suggestions appreciated. Thanks.

I'm actually also doing this right now. My solution was to go with 960.gs-like divs.

First, I define a series of constants: Start time to display, end time to display, columns per hour, total columns. In my app's case, these variables are configurable by the user.

Second, I query an array of events that I need to deal with. These include a start time and end time, plus the details I want to display. I'll be using jQuery QTip to popup details that hover, so data to populate those is also included in this query.

Now, the 960.gs concept. The basis for a grid is knowing that you have X amount of space to display your content...with 960, it's 960 pixels. Mine is more custom, but this provides the concept. You can divide this by quite a few numbers, which becomes the basis for how to split the grid. Using this approach, I can easily define a column from grid_1 to grid_4, and it will take a width that is a commensurate percentage of the overall width (i.e. on a 16 column layout doing a 4 column div would cover 25%) It's cross-browser compatible, and doesn't require an overt amount of clear divs. You just need to make the numbers add up to match the amount of columns you want to work with.

Now, I begin by doing the math to figure out how much time each column represents. I assemble each day using a foreach loop: I start with the hour of the display start time and increment up. If the start_time of an event equals the incrementer, I start a div that's styled appropriately based on my coloring criteria. Likewise, if my end time <= the incrementer, I stop the div and define the column's width in the id. Obviously, at the end of the loop, I do an incrementer++. Repeat per day that you display.

My concept is doing this on an time basis for a weekly type calendar. But the overall idea could easily be modified for a month-style calendar or even for a day calendar.

Tables definitely make this easier (version 1 was tables) but it can be done either way if you have the patience.

Is there any single tool that runs JSLint, W3C validator (both CSS3 and HTML5) on files in a given directory?

14 votes

I want a single program that recursively finds all *.js, *.html and *.css files in a given directory and JSLints, and W3C validates them respectively and prints out all errors found. Also it separately JSLints and CSS validates anything found inside script and style tags embedded in the html files. I also want this to validate other less common web contents too if possible using the W3C tools. The tools should also have option for passing in common JavaScript frameworks for JSLint (e.g. it should work fine with latest JQuery). Where I can buy such a tool?

CSE Validator - http://www.htmlvalidator.com/

Should I use <ul>s and <li>s inside my <nav>s?

13 votes

The title pretty much explains it.

Now that we have a dedicated <nav> tag,

Is this:

<nav>
  <ul>
    <li><a href="#foo">foo</a></li>
    <li><a href="#bar">bar</a></li>
    <li><a href="#baz">baz</a></li>
  </ul>
</nav>

any better than the following?

<nav>
  <a href="#foo">foo</a>
  <a href="#bar">bar</a>
  <a href="#baz">baz</a>
</nav>

I mean, assuming that I don't need an extra DOM level for some CSS positioning/padding, what is the preferred way, and why?

the nav element and the list provide different semantical information:

  • The nav element communicates that we're dealing with a major navigation block

  • The list communicates that the links inside this navigation block form a list of items

At http://dev.w3.org/html5/spec/Overview.html#the-nav-element you can see that a nav element could also contain prose.

So yes, having a list inside a nav element does add meaning.

IE9: Why setting "-ms-transform" works from css, but not with jquery.css()

13 votes

This works

div{
    -ms-transform: rotate(30deg);
}

And following does not

$("div").css("-ms-transform","rotate(30deg)");

Any ideas why, and how to fix it?
Same thing works good on all other browsers, but not on IE. Ofcourse, only IE9 supports it. Older versions dont.

Not sure why As KooiInc says, dashes in style property names are invalid in DOM scripting.

You can fix it by using object notation and passing in the name in camel case instead of hyphenated, like this:

$('div').css({ msTransform: 'rotate(30deg)' });

jsFiddle preview

Can I disable the . in an <ol>?

13 votes

I was delighted to learn that CSS lets me say list-style-type: cjk-ideographic and get my ordered lists numbered 一, 二, 三, 四. Unfortunately, it displays like "一." (2 characters: kanji/hanzi 1, then ASCII period).

I looked around and found that the CSS spec actually says to do this:

The suffix for the cjk-ideographic numbering systems is a dot . U+002E.

(This seems bizarre, since Japanese doesn't even use U+002E for ending sentences. All of the text I have here uses U+3001 after the number.)

Is there a way to get the automatic "cjk-ideographic" numbering, but have it omit this suffix character, or (better yet) tell it to use U+3001 as the suffix character?

I'm assuming you only want the numbering but not the dot. If that's the case, you can do

ol {
    margin: 0 0 1em 0;  
    counter-reset: item;
}
li:before {
    content: counter(item, cjk-ideographic) " ";
    counter-increment: item;    
}

Check working example at http://jsfiddle.net/davidThomas/82SSG/1/

Where do the lost pixels go in a percent CSS layout?

12 votes

Possible Duplicate:
Evenly distributed height of child elements with CSS

Lets say i have a design with 6 DIVs that are float left with a width of 16.666%. So the document size is splited in 6 parts.

Now if i have a document size of lets say 620px wide this would make each part 103.333px. Since i don't know screens that can show partial pixels :) I wonder how the browser handles the partial pixels.

Here is my testcase: http://jsfiddle.net/dhQh2/ (Just resize the window to get a result)

When resizing it seams that the 6 DIVs keep the same size. But it some cases it can't be. How does the browser handle those partial PX values?

As you asked for me to write it up:

The problem is that elements must have an integral width (or height) - the only way browser vendors could fix this (render non-integer widths) would be to implement anti-aliasing - but that would bring a new problem: elements would suddenly appear to gain a "fuzzy edge" if they were being resized and their width ended up as a non-integer value. So anti-aliasing is a no-go.

If, for example, you're using % based width, and the precise width should be 103.333px, then the browser must make a decision on how to turn that number into an integer.

Different browsers make different decisions, read these links for more information:

I particularly like this explanation from John Resig/David Baron of why this is even a problem:

I was talking this over with some Mozilla developers and David Baron explained the situation quite well:

We’re trying to meet a bunch of constraints that can’t all be satisfied at the same time (the proof is left as an exercise to the reader, though I may have actually written it out once in a Bugzilla comment):

  1. 4 adjacent objects of width/height 25% (for example) starting at one edge of a container should end exactly at the other edge; there should never be an extra pixel in the container and they should never be wrapped due to being a pixel to wide

  2. objects that are logically adjacent should always touch visually; there should never be a pixel gap or a pixel of overlap due to rounding error

  3. objects given the same width should occupy the same number of pixels

  4. object boundaries should always (visually) be aliased to a specific pixel boundary in the display (they should never be blurred)

The one [Mozilla] sacrifices is typically (3), except for borders where we sacrifice (1) by rounding the widths to pixel boundaries much earlier.

See this question for a JavaScript fix that forces consistency:

Evenly distributed height of child elements with CSS

Another relevant question:

Are the decimal places in a CSS width respected?

In 2011, is there any need for clearfix?

11 votes

You are aware of the age-old problem: Containers containing floated elements don't automatically expand their height to enclose their children.

One approach to fix this is the "clearfix" which adds a number of CSS rules to ensure a container stretches properly.

However, just giving the container overflow: hidden seems to work just as well, and with the same amount of browser compatibility.

According to this guide, both methods are compatible across all browsers that are important today.

Does this mean that "clearfix" is deprecated? Is there any advantage left in using it over overflow: hidden?

There is a very similar question here: What is the different between clearfix hack and overflow:hidden vs overflow:auto ? but it doesn't really answer the question.

You can pretty much use overflow: hidden all the time.

But, there are exceptions. Here's an example of one:

Overflowing a container div horizontally but not vertically

The question there was:

In a framework using rewrite rules, how best to integrate CSS and JS?

11 votes

I've got a framework that routes all incoming URIs through a base file, and to deal with static files I've got a sub-directory /static in which I put all CSS, JS and images (ie. /static/css/main.css) in order to keep things clear.

My own code and plugins deal with this fine, but some times other code needs to be implemented, and often CSS files will try to style up with calls to URIs in those files. How can I deal with this in the best way?

An example ;

/about/company routes to /script?q=about/company and locks in the main structure of the site. However; /static/css/main.css uses a background image from; /static/images/widget/bg-color.png

Since this is a framework I'm not happy to hard-code the /static paths in the CSS files. For one, I don't want to restrict websites to only being served from some root directory. :) For all JS there's objects that deal with this (ie. var x = $xs_dir.js + '/script.js' ;) but nothing exists for CSS. I have five options, I think ;

  1. (worst) Have an option in my admin tool that scans all CSS files for URI references, and prepends them with the right static directory, and writing all CSS as if they're static to a root directory.

  2. (poor) Rely on the webserver's ability to alias any static directory to one root static directory, and let the admins deal with it.

  3. (meh, slow) Serve the CSS files through the framework, filtering URIs with the right static paths.

  4. (simplest, but not very easy) Hand-code the static portions of my CSS files for whatever server setup there might be, and just make sure they're easy to find and change.

  5. (probably best, but complex?) Have a rewrite rule that detects images in current directory, forwarding them to the static directory, and write all CSS with some recognized dynamic path. (ie. instead of /static/images/img.png do images/img.png and rely on rewrite rules to push it where it needs to go, also restricting the website structure to never have a sub-directory called 'images')

Any additional options? Ideas? I know Joomla and similar has some rewriting of files, and probably do no. 5?

Not sure whether you have an .htaccess file or not, but one option would be to put in a rewrite rule for request under a folder "images" to be redirected to your static (or whatever) folder:

RewriteRule ^[^\?]*(images/)(.*)$ /static/$1$2 [NC,L]

That way you can reference all your images as just /images/whatever.png in your CSS.

If you require a different setup for different servers, you could always have a separate .htaccess file for each environment or server, and version control these.

Help me convince a teacher that he needs to stop teaching IE filters!

11 votes

The Issue

Just to give you some background, I'm currently enrolled as a student at the University of Mary Hardin-Baylor. Currently the web design classes there are somewhat... sub-par. My DHTML teacher worked on websites in the Netscape/IE clash and most of the stuff he teaches is deprecated, non-semantic HTML, or inline code. He is still a huge supporter of IE and is still avid about students learning IE filters. From what I've seen he seems to see no need to support multiple browsers. I'd really like to see the web design section of the school grow and as long as the teachers are still teaching deprecated code, it probably won't. I'm planning on sending him an e-mail trying to convince him to drop the IE filters section of the course next semester and replace it with something that students will actually be able to use cross-browser.

The Request

I need help building my argument.

  • I need to build a list of reasons on why filters are deprecated and shouldn't be used(I believe they aren't even supported in IE9 anymore).
  • It might also be advantageous to give reasons why cross-browser support should be achieved.
  • I need some reputable sources that I can quote. This excludes sites like wikipedia.

Also, on a side note, one of the reasons I'm asking this here is because I don't have any type of real world coding experience. If I had support from someone else who worked in the same era of the web, it could do wonders for the legitimacy of my argument. I don't want this to sound like I'm just bashing his methods, or even worse... just trying to get out of work.

Thank you in advance for any help you post! I know this is a huge request. I appreciate any time your willing to give.

Edit

I just wanted to point out that I agree with some of the comments made. The filters section of the course is a very minor problem. There is a numerous amount of other issues that would be far more important if the students were going into a web design career. Unfortunately most of the students are forced into this class specifically for degree requirements of the CGD Major. There currently is no major dedicated to web design and there are probably only 4 people on campus that actually are pursuing web design as a career. The average Joe of this class will probably never produce more than a personal website. This being said, version compatibility and other issues solved by filters will probably never be used.

The main issue isn't that the teacher is teaching IE filters, though, it's that he's teaching a three week section on filters. Through the entire semester, the class has only been able to go over very simple Javascript such as variables, functions, arrays, loops, and attaching events via event attributes. We haven't even touched the DOM yet and the stuff we have gone over we only touched on very lightly. I would just like to see the last section of the class dedicated to the more universally useful information such as the DOM, Objects, Object methods, and Regular Expressions.

Despite all of this though will be making a large section of the document over browser compatibility and I appreciate the information y'all have supplied for that. I wish I could tell him everything that he's doing wrong, but that would be way more than one e-mail. I would like to take it one step at a time though and at least point him in the right direction.

Sorry for the long post! Thanks

Cross-browser support:

  • If it's a project for a client: What do you tell your client if the site you created does not work on non-ie browsers? Actually usually clients require cross-browser compatibility.
  • Only supporting IE means losing customers which means losing money
  • Why use proprietary filters if cross-browser alternatives exist? IE9 supports CSS3, opacity etc
  • Modern developer tools facilitate and support modern technologies - and all developers want to use shiny new tools (they're more fun :-))
  • Forward compatibility: You may create an ie-only site with table-layouts and proprietary filters, but you will need to start from scratch once you'll realize what you've done, whereas building a site based on today's standards will be maintainable longer before a complete remake is due.
  • Maintenance: A web site needs to be maintained, probably by different people - choosing current and well-known technologies will make this easier.
  • It's not that hard (once you exclude IE6 - see compatibility table linked below)

Some sources:

  • Browser compatibility by PKK, for example CSS: http://www.quirksmode.org/css/contents.html Excellent resource for implementing cross-browser compatible web sites. PPK is one of many professionals promoting cross-browser compatible web sites, you won't find the contrary (professionals promoting IE only sites).
  • Even Microsoft promotes moving on from IE6 towards modern browsers and technologies, and is proud of ie9's CSS3 support: http://www.theie6countdown.com/default.aspx

display:none; displays 'none' in browser.

10 votes

This jsFiddle example works in Google Chrome, but in Internet Explorer then when the close icon is clicked the browser removes the pop-up element but results in the text 'none' being displayed in the browser window. Please explain how I can resolve this issue.

Use onclick for the event handler instead of href http://jsfiddle.net/AE2X3/4/

<div id="popup">
        <a href="#" onclick="document.getElementById('popup').style.display='none';return false;" id="close_popup"></a>
        <p>This is a pop-up.</p>
</div>

Why font looks much better in IE9?

9 votes

I use font-family: Myriad; font-size: 40px for some text. And, I can't believe what I see, IE shows the most quality font! Much better than opera, mozilla and chrome.

How can it be? How can I make text so nice as in IE in other browsers? If you don't believe, just try it!

Here is an edit:

http://jsfiddle.net/55Ruh/3/

Try this link in all browsers. IE (the newest version, 9) shows the best and most quality text, isn't it?

This is because IE9 introduces a new font rendering engine that is based largely on that seen in WPF's ClearType implementation. Its enhanced engine does a better job at reducing jagged edges, making fonts look smoother and better, especially at large sizes.

This breed of ClearType is different from the one seen in the rest of Windows, also known as GDI ClearType (for Windows' GDI graphics library). The old GDI ClearType is the one that Windows versions of most other browsers base their font rendering engines off, which is also the one that makes fonts look really jaggy in large sizes.

The following paragraph from the second link summarizes most of the rest of its content, that explains quite nicely why fonts look smoother in IE9's new engine:

A significant improvement over the previous version of ClearType is the use of sub-pixel positioning. Unlike the ClearType implementation found in GDI, the ClearType found in Windows Presentation Foundation (WPF) allows glyphs to start within the pixel and not just the beginning boundary of the pixel. Because of this extra resolution in positioning glyphs, the spacing and proportions of the glyphs is more precise and consistent.

See, especially, the section on Y-direction anti-aliasing with screenshots for comparison. Another quote:

ClearType in Windows Presentation Foundation (WPF) provides antialiasing on the y-direction level to smooth out any jagged edges.

Make Adobe fonts work with CSS3 @font-face in IE9

8 votes

Hi,

I'm in the process of building a small intranet application and try, with no luck, to use Adobe font I purchased lately. As I was informed, in our case it's not a license violation.

I converted the .ttf/.otf versions of font to .woff, .eot and .svg, so to target all major browsers. The @font-face syntax I used is basically the bulletproof one from Font Spring:

@font-face {
    font-family: 'MyFontFamily';
    src: url('myfont-webfont.eot');
    src: url('myfont-webfont.eot?#iehack') format('eot'), 
         url('myfont-webfont.woff') format('woff'), 
         url('myfont-webfont.ttf')  format('truetype'),
         url('myfont-webfont.svg#svgFontName') format('svg');
    }

I modified the HTTP headers (added Access-Control-Allow-Origin = "*") to allow cross-domain references. In FF and Chrome it works perfectly, but in IE9 I get:

CSS3111: @font-face encountered unknown error.  
myfont-webfont.woff
CSS3114: @font-face failed OpenType embedding permission check. Permission must be Installable. 
myfont-webfont.ttf

I noticed that when converting font from .ttf/.otf to .woff I also get an .afm file, but I don't have a clue whether it's important or not...

Any ideas how to work it out?

[Edit] - I host my websites (fonts too, but under separate directory and subdomain for static content) under IIS 7.5

I can only explain you how to fix the "CSS3114" error.
You have to change the embedding level of your TTF file.
I guess you have converted that locked .ttf to obtain your .woff hence the "CSS3111" error.

Using the appropriate tool you can set it to installable embedding allowed.

Will jQuery ever return a CSS measurement in something other than px?

7 votes

I'm rewritting my Textarea Line Count plugin (<-- shameless plug), and have this question:

When I call $("#someElement").css("letter-spacing"), will I ever get a value in ems, or anything other than px? Based on this example: http://jsfiddle.net/xhhr2/, in Google Chrome at least, it appears that either jQuery or the browser is converting the measurement to px for me. Can I always expect this behavior?

According to Crescent Fresh's answer that links to a hack by Dean Edwards, jQuery goes through great lengths to return the actual, computed pixel value across all browsers and not what was defined originally in the style sheet, so it seems that yes, you can rely on it.

Facebook Like Widget on Fan page, Comment area out of visible area

7 votes

Hi,

When using the like or send widget on a Fan Page (no mater if you use iframe tag or fbml for it) the overlay for commenting is positioned always to the right. see http://twitpic.com/4q7ggi for example.

I cant find a way to get the widget to respect the 520px boundary of the facebook tab. see http://www.facebook.com/pages/Ludwig-Test/127771653944246?sk=app_101150316644842 for an example. Anyone an idea how to solve this ?

TIA Rufinus

Try adding this to your css:

.fb_edge_comment_widget {
    margin-left: -350px;
}

This will move comment box to the left, but the little arrow pointing to the button will move too (which you could try to cover with another element). It will only work if you're using XFBML, not an iframe.

Here's an example.

Is it ok to store presentation data in the database?

4 votes

I am to displaying rows from a database (SQL SERVER 2005) table in a webpage. These rows contain a statusID (foreign key) that is further defined by Status table (eg. id, name, modifiedDate).

The various statuses should display differently (lets say they simply have a different background color).

I am using php to query the database, and build the web page table. As I build the table I am going to apply a css class to an element based on the status of that row.

I have at least 2 options to do this:

  1. Define code logic in the php to handle it, and if the statuses are changed in the database, I will have to change the code.

  2. Store the "class" in the database and simply apply the class that has been stored.

The latter option seems better to me, but I am unsure if embedding presentational data into the database is a bad design choice. This will be the foundation on which I create several intranet utilities, and I'd like to start off on the right foot.

There's nothing wrong with storing any data in the database, including presentation data. If it helps you produce effective results, while writing less code, then it is a good practice. The thing you need to make sure of is that you don't mix your presentation logic with your database logic.

You can ensure that these concerns are separated by encapsulating the data for your presentation layer in the properties of an elementInfo object (for example).

Since it is a CSS class that you are talking about, this presentation data should be kept separate from the business data. So, while it is okay to store both presentation data and business data in the database, it is not acceptable to store them in the same table.

Update re: comment No, you should not add a PresentationClassRecord's Id as an FK on the business object. I made a sample of an approach to the db below. I called the DummyTable your business objects, and the rest follows specification. The most relevant part is the StatusPresentationAssignmentTable

 -----------------------------------------------
 DummyTable
 -----------------------------------------------
 Id      Name     SomeOtherDataField    StatusId
 PK int  varchar  int                   FK int

 -----------------------------------------------
 StatusTable
 -----------------------------------------------
 Id      Name     ModifiedDate
 PK int  varchar  datetime

 -----------------------------------------------
 PresentationTable
 -----------------------------------------------
 Id      PresentationType    Value 
 PK int  varchar            
 sample data:
 43      CssClass            prettyBackground

 -----------------------------------------------
 StatusPresentationAssignmentTable
 -----------------------------------------------
 StatusId    PresentationId 
 FK int      FK int

Now with two simple join clauses you can get the presentation data and it is completely decoupled from your business data. Your script could do something like check if the Status of the Dummy has any presentation assignments. If it does then it looks at the PresentationType, gets the appropriate function to apply the presentation-data to the presentation, and executes it. (You would need to have a function for each PresentationType that knows how to handle the value - something that could be encapsulated by something like function applyPresentationValue(presentationElement, presentationType, presentationValue) that calls a different function applyCssClass(presentationElement, value) if the presentationType == "CssClass" ).

CSS styling in Django forms

4 votes

How do I style the following:

in forms.py --

from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    email = forms.EmailField(required=False)
    message = forms.CharField(widget=forms.Textarea)

in contact_form.html --

    <form action="" method="post">
        <table>
            {{ form.as_table }}
        </table>
        <input type="submit" value="Submit">
    </form>

For example, how do I set a class or ID for the subject, email, message to provide an external style sheet to? Thank you

Taken from my answer to: How to markup form fields with <div class='field_type'> in Django

class MyForm(forms.Form):
    myfield = forms.CharField(widget=forms.TextInput(attrs={'class' : 'myfieldclass'}))

or

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].widget.attrs.update({'class' : 'myfieldclass'})

--- EDIT ---
The above is the easiest change to make to original question's code that accomplishes what was asked. It also keeps you from repeating yourself if you reuse the form in other places; your classes or other attributes just work if you use the Django's as_table/as_ul/as_p form methods. If you need full control for a completely custom rendering, this is clearly documented