CSS hacks (tricks) - css

Sometimes when I see a website I like or sites from respected people, I see the source codes and try to understand them (as we all do).
On Jeremy Keiths site he uses the following code:
[role="navigation"] a {
font-weight: bold;
text-decoration: none; }
I have never seen this before, and a few other times I saw code (which can be considered a "trick") that I had never seen before.
Other than asking what the above code means, my question is - is there any documentation, book or blogs that go through to learn about the advanced/less known CSS "tricks"?

The above targets elements that have a role attribute, such as:
<div role="navigation">
...
</div>
A class would make sense here too, but it's just another way of doing it. Attribute selectors are a standard part of CSS2, but at the time IE6 didn't support them so it hasn't been used much until recently.
There are many other such selectors that have been around for a long time but couldn't be used due to limitations imposed by IE. See Quirksmode for more examples.

That is a CSS attribute selector. It's saying "All <a> tags that are descendents of an element that has an attribute of role with a value of navigation should be styled in the following way ..."
He's using it for accessibility principally, and for styling only secondarily.
If you are looking to learn some of the newest things about CSS, I'd recommend css3.info and css3please.com. The first is a great source of examples of new tricks, and the second one lets you play with the new stuff in the browser. Other than that ... I've found that the best way to learn is to answer questions here (looking things up when you are not sure) combined with reading -- Eric Myers, Paul Irish, Quirksmode -- all of these are good resources for learning things that are new to you.

In this example, the <nav> is wrapped in a <div> and then then assigned a navigation role. The same can be achieved with just
nav a {}
A lot of sites seem to mix a "little" HTML5 with XHTML. I really don't see a reason why they don't use HTML5 "completely". The whole point of HTML5 is to be more semantic and to write less code that's more meaningful.
Some useful links.
http://html5doctor.com/
http://htmldog.com/
http://desizntech.info/2009/03/discover-the-cool-of-css-25-advanced-css-techniques/
As of now, you'll need a bit of javascript to make HTML5 elements work in IE. These links should help
http://html5doctor.com/how-to-get-html5-working-in-ie-and-firefox-2/
http://remysharp.com/2009/01/07/html5-enabling-script/

Role is a new XHTML2 attribute.
http://www.wait-till-i.com/2009/05/16/pitching-a-hack-or-a-product-dos-and-donts/
http://www.w3.org/TR/2008/WD-xhtml-role-20080407/

Cool, which browser did it work in?
http://www.w3.org/TR/2001/CR-css3-selectors-20011113/#selectors
E[foo="bar"]
an E element whose "foo" attribute value is exactly equal to "bar"

Related

CSS Specificity Filter

This is a long shot, but is there a tool available that optimizes CSS selectors by removing unneeded specificity?
I find that when I write CSS, I deliberately make my selectors more specific than necessary to avoid conflicts and for quasi-documentation.
It would be great if there were a tool that could analyze a given group of rules, determine their "uniqueness" in terms of overlap with other rules, and then strip away any unnecessary specificity.
I can't even begin to imagine how a tool developer would approach all of the scenarios this would require, but I've been blown away by others' ingenuities in this area before and figured it was worth asking.
Update:
I've added a bounty to this question, and the more I think about it, the more I realize how valuable a CSS Specificity Filter would be.
For example, when working with Nested Rules/Selectors in Sass and LESS, excessive nesting is a common and well-known antipattern that can easily lead to overly specific selectors.
There's a good illustration of this in the excellent TutsPlus course Maintainable CSS with Sass and Compass:
body {
div.container {
p {
a {
color: purple;
}
}
}
}
Sass will follow these nesting instructions and produce the following CSS output, raising no objection to any unneeded specificity:
body div.container p a {
color: purple;
}
If a Specificity Filter did/does exist, however, it would create potential benefits for CSS developers:
You could organize your stylesheets as a 1:1 mapping of the DOM, similar to what you see when you examine style rules in Firebug and Chrome Dev Tools. A smart editor/IDE could auto-populate styles for DOM elements with shared styles/classes. That redundancy would then, of course, be filtered out by the Specificity Filter/Optimizer.
Stylesheets could have their structure pre-populated by a tool that scans the DOM and translates it to CSS selectors/rules. This means a developer would only need to update the HTML; the CSS "tree" would be kept in sync to reflect the current state of the DOM. A smart editor would let you jump to the CSS definition for an element/class for styling -- or even make its style rules visible in a separate panel.
In a way, this almost seems like a step backward - like a feature you'd find in Dreamweaver or WebAssist to help newbs learn CSS. But the basic idea of a CSS selector optimization tool seems like a no brainer, and the type of workflow automation I've described would be the logical next step -- and the catalyst would be the Specificity Filter.
I looked into some of the better-known CSS editors and web IDEs, but haven't found anything offering this type of functionality beyond targeting a single element and generating a selector for it.
Update 2: CSS Selector Performance
In response to Spliff's comment, here are two great articles on CSS selector performance:
Performance Impact of CSS Selectors by Steve Souders
Efficiently Rendering CSS by Chris Coyier
Both agree that micro-optimizing CSS isn't worth the effort, but that over-qualified descendant selectors are "an efficiency disaster." I haven't benchmarked yet myself, but suspect that the kind of "DOM Mapping" approach I'm suggesting would cause a performance hit without an optimization step, either manual or automated.
Related Questions, Links, and Tools:
Points in CSS Specificity
Tool to See CSS Specificity
Tool for Cleaning Up CSS
Order by CSS Specificity
Top 5 Mistakes of Massive CSS
Google: Efficient CSS Selectors
Procssor
Clean CSS
CSS Tidy
You could attempt to take a different approach, try to write your selectors as small (low specificity) as possible. and only make them more specific when needed.
With that way of working you don't need a tool.
Just going to throw this out there-- it doesn't 'answer' your question,but it's a tool I like to spread the word about for people who do a lot of css programming: Firebug.
If you're not familiar with it, it's a tool for web browsers. You pull up your page once it's installed, right click and select 'Inspect Element.' It will show you all css affecting different elements on your page, and is useful for creating clean, precise css code. Also it makes it easier to see instant updates on what your page would look like with slight modifications. It will inform you of useless css code that's being overridden by other css code.
ALSO! Firebug now is available for almost all browsers. Not just Firefox. Personally, I'm partial to using it in Chrome.
We really can't do without specificity because it is the only thing that saves you when you have two or more rules colliding. Specificity brings sanity to the whole jumbled CSS rule, so it is more of a blessing than curse. Some of the stuff you talked about, like the CSS selector, can be done using Firefox/Firebug. I'm more disturbed by browser compatibility.
Actually there's a way you can do this using HTML5 and CSS3. The standard technique is to specify elements using the HTML 5 attribute "data-" and then do CSS selection for this attribute. This isn't the purpose of the attributes, but you can customly specify some elements that you can use to even switch the theme of a site.
So, for example, you can end up creating your specificity filters manually in CSS, by specifying
<b data-specificity=2>test</b>
where data-specificity only matches to parents above.
UPDATE:
Alright, so for example, let's say you have a paragraph class, but you want to specify which parent, or how many parents the paragraph can inherit properties from. You would use rules for each potential parent that can be inherited from:
p[data-specificity="1"]{
color:red;
font-family:verdana;
text-decoration:underline;
}
p[data-specificity="2"]{
color:black;
font-family:arial;
}
div.container > *[data-specificity="2"] {
font-family:impact;
color:blue;
text-decoration:underline;
}
So these rules mean that any p tag which is a direct child of the div container and has specificity 2, is allowed to inherit properties from the div container. The blue color of the div gets inherited by the p with data-specificity 2.
Here's a JSFiddle where you can see this!
The idea is that like this, using HTML5, you can control exactly which elements are allowed to inherit which properties. It's a lot of extra code to write (for both child and parent elements) but you can use this to get rid of some unnecessary specificity
I've never actually seen anyone use this method in practice, I pretty much just cooked it up for you, but I think it could be very useful, what do you think ?

Is there any practical benefit of using <header> over <div id="header">?

Is there any practical benefit of using <header> over <div id="header">?
and writing css for header {} over #header {}
I know one downside is , I will have to punish IE users with a Javascript if use <header> otherwise it will not take style.
I know it's HTML5 but is there any advantage of using it until non HTML5 supported browsers are still in use.
IE6, IE7, IE8 and some old mobile browsers do not understand these new tags.
Edit:
It's OK to use a JS Canvas library to do something awesome in all browsers but to use a Javascript just to use some tags in IE wil decrease performance without a big reason.
Besides the fact that it gives more meaning to the markup , when working with css you can more easily select the required items without resorting to id's or class.That reduces the amount of markup you are required to write , it makes mantaining the site alot easier and help other developers understand your code better if needed.
I don't know for a fact, but I think it almost certain that using semantically better markup (e.g. <header>) will help search engine crawlers construct a better image of your website.
There is probably no other practical benefit of going HTML5, and even the above is not exactly tangible. So in practice I don't really believe you can argue that going HTML 5 (and doing the extra work needed to make your page compatible with earlier IE versions) is going to be a good investment.
On the other hand, if you don't care about obsolete browsers then there's really no drawback.
Well, from my point of view, it gives further meaning to the markup. At least in a more structured way. Say, for instance that you have to parse automatically your page (if it wasn't yours), you would know that the header will always be a and it doesn't depend on the CSS class used.
Gives better structure to your page as Carles points out - this is especially helpful when it comes to search engines - they'll be able to crawl all your website a lot more effectively. You can use javascript to get IE to recognise HTML5 elements (simply put it inside an if statement).

Style half of a word, sentence, etc

I'd like to show a title with the first three characters in different color.
I know this can be done with <h2><span>The</span> awsome title</h2> but I was wondering if there is some kind of "nth-child" property that can be applied to characters inside an element.
I'd like to avoid breaking the text by inserting other elements ( etc.)
A (relatively) crossbrowser solution would be welcome.
There is no cleaner way than what you already have.
<h2><span>The</span> awesome title</h2>
With CSS:
h2 {
color: red
}
h2 span {
color: blue
}
There's :first-letter and :first-line, but no :first-word.
I imagine the reason for this is that it's hard to define exactly what a "word" should be.
The only way to do it without changing your markup is to use JavaScript to enclose the first word with a <span> (and style it the same way), but I would only recommend that if the rest of your site already heavily relies on JavaScript to function.
Yep, JavaScript is the only way I can think of (as everyone else has already said!). Demo here.
$(function() {
$('h2').each(function(){
$(this).html( $(this).text().replace(/(^\w{3})/,'<span>$1</span>'));
});
});
This isn't possible with the current CSS operators you are talking about nth-whatever,
This could however be done with JavaScript... if of course you want to go down that route, the best way to do it would be with <span> tags as then you will have no problems with people who have disabled JS.
It is entirely up to you, but if I were in your position I would just man up and use JS, it is called progressive enhancement and unobtrusive JS, as long as the content is not wrecked if the user disables JS it is acceptable, see here:
http://dowebsitesneedtobeexperiencedexactlythesameineverybrowser.com/
Sadly, there isn't a way to do this with stylesheets. CSS3 provides us with first-letter and first-line, but not first-word, and certainly not first-n-letters.
See also the answers to this question for more: CSS to increase size of first word
JQuery does implement a first-word selector, so if you're prepared to go with the Javascript option, you may be able to do it.
Heh. It seems that JQuery doesn't actually implement it after all. I must have been using a plugin when I saw it.
But here's a link to a Javascript solution that might help: http://www.dynamicsitesolutions.com/javascript/first-word-selector/

Adding strong emphasis to an img tag. Semantics

I'm actually coding a website and a doubt came to me. I have a list of images (it's an artist portfolio, so it should be images), some of which have a "Featured" badge. Is it semantically correct to wrap the img into a strong tag instead of using a class="featured"? Will it add strong emphasis to the image?
Reading the W3C spec., it refers strong and em as text-level semantics, but I'm not sure what happens with media like img.
Thank you so much.
I think that's fine. You may already be doing this, but you need to make sure that the ALT text describes why the images has been emphasized. Eg alt="man with dog - featured"
I think that it would be perfectly acceptable to do this and preferable.
First of all, I think the HTML 4 spec allows it. Question is, can you rely on what browser will do with it. I would not take my chances with that.
But at least, in many browsers you can attach formatting to
strong img {
/* mark up for the featured image */
}
And this should then work for all browser that support it.
I wouldn't use the strong tag on images, I am not sure why it would be preferable since it refers to 'emphasized' text only: an aural user agent may use different voices for emphasis, it would be pointless for images.
Why don't you just use a class?

Is there any way to find unused CSS in a website?

Is there any way to find unused CSS in a website?
I'm trying to clean up a project I just inherited.
Dust-me Selectors is a Firefox plugin that finds unused selectors.
I just ran into this and remembered your question: http://github.com/geuis/helium-css
Chrome 59 has built-in coverage display for CSS and JavaScript since 2017-04: https://developers.google.com/web/updates/2017/04/devtools-release-notes#coverage
You can enable it by opening the dev tools, then the command menu (Cmd+Shift+P on Mac or Ctrl+Shift+P on Windows and Linux), and then type "show coverage".
There is so much that can be said about best-practice methods for CSS. I'll try to stick to the main points.
Use a CSS reset.
Try to remove really general CSS statements like h1 {} and #container em {}. You're much better off using h1.section-title and #container em.important {}, because that way if you choose to use h1 or em a different way somewhere in your document, you don't have to worry about overriding any existing code.
Don't be too specific in your CSS selectors if you don't have to. You really only need to have high degrees of specificity if being in a specific section changes how the element is going to be displayed. Otherwise, to make your code for your block class reusable, #container .content .block ... could be reduced to .block ... in many cases.
Look for commonalities in your CSS and see if you can create reusable classes. If you have similar blocks class="favorites" and class="popular", turn it into class="block block-favorites" and class="block block-popular", and put the commonalities into .block.
Get in the habit of making areas in your CSS have an auto-width (can be done implicitly) so that they grow to the width of your containers. This makes it incredibly easier to move sections from a narrow portion of your website to a wide portion of your website without having to change any code.
Commenting your code and breaking it down into sections usually helps make code more readable.
You'd be surprised how much cleaner your code looks when you implement more powerful CSS selectors. Most of them are cross-browser compatible (Internet Explorer 7 and later).
Some valuable resources: When can I use... - Quirks Mode on CSS Selectors - w3 on CSS Selectors
Answer moved from:
Best Practices for Cleaning up Existing CSS/unused styles
To add to #cweiske suggestion, Google Chrome has a no nonsense way of uncovering where your "unused" and "never will be used" selectors are.
I have posted a screen capture of how to launch the CSS Coverage tool with step by step markers.
It is a reliable way to figure out where you really are not using stuff.

Resources