What are good uses of the css `content` property? - css

Does the css content property break the rule of content and separation because css is for presentation not to generate content?
What are other good uses of the css content property? I've seen it only in clearfix hacks.

Does css "content" property break the rule of content and separation because css is for presentation not to generation content?
Good point. I'd say it does if it's used for actual data.
The quirksmode page on content shows the limitations pretty well. You can't add any kind of styled content at the moment - it will work with too few browsers. You can add only character data.
The author of the quirksmode airs an interesting opinion:
I feel that we shouldn't use the content declaration at all. It adds content to the page, and CSS is meant for adding presentation to the page, and not content. Therefore I feel that you should use JavaScript if you want to dynamically generate content. CSS is the wrong tool for this job.
I agree with this in general, but sometimes there may be cases where you don't want to rely on JavaScript to do the job. The comma example shown by Martin is a case where I find using content justified (although I personally would be feeling better if the commas would already be served coming from server side - it's what I personally would stick to.)
Also, keep in mind that adding commas and quotes through the content property may look bad when your content is viewed from elsewhere - for example in a search results page.
I'd say use it only sparingly, if you really need it.

One popular place that this shows up is in WordPress' default theme
.entry ul li:before, #sidebar ul ul li:before {
content:"» ";
}

It could be used in print style sheets to show urls for links for example:
p a:after {
content: " (" attr(href) ")";
}
Some link (http://www.somesite.com)

It's good for structured content. I wrote a number of test cases for the W3C's next print CSS rules and the one that seemed cool to me was being able to put "Chapter " and things like that into certain elements, especially when paired with counters. A simplistic example would be something like:
li.chapter:before {content: "Chapter" counter(chapter) ": ";}
None of that's print-specific and it's all presentation information. If you don't want your chapters to be preceded with the word "Chapter", take it out of the CSS. Controlling that in a stylesheet means your print version could have different chapter headings from your screen version your mobile could be different again, without having to have any knowledge of the viewer's device inside your application logic.

I'm using it to display accesskey in admin panel menu
.menu a[accesskey]:after { content:' [' attr(accesskey) ']'; }

CSS is presentational data. Any content that's only presentation-related is fine in a CSS file. For instance, suppose I want to put « and » around my <h1> tags; that's purely presentational. You could do it with the :before and :after selectors.
It should also be noted that content can also display images:
content: url('my/image.png');
I'd like to add, on a side note, that I'd consider the use of the content property to override already existing content an extremely bad practice.

A common use I see for it is with :before and :after tags to format quotations with some sort of stylized quote box. It can be a quick and easy way to get in stylized elements that you would otherwise have build images out of.
blockquote:before, blockquote:after {
content: '"';
}
I think this is an okay use for it, because it doesn't really break rules of content and style separation. My feeling is that if it is part of the design of the page, rather than the content, it's probably okay for content:

One interesting use case, although maybe not recommended, is for placeholder text on contenteditables.
[contenteditable]:empty:after
{
color: #aaa;
content: 'Enter some text';
}

Like zneak said, it is also possible to replace images. I find it practical to replace "content images" (not "asset images", which should be done via css background images) with higher resolution variants on iPhone 4 and other devices that have more than one real pixel per virtual pixel.
E. g.:
<img id="people9" src="//lorempixum.com/200/150/people/9/" width="200" height="150" alt="People"/>
#media all and (-webkit-min-device-pixel-ratio: 2) {
/* e. g. iphone 4 */
#people9 { content: url(//lorempixum.com/400/300/people/9/); }
}
It works, at least, on iPhone 4 and Android Nexus S, but I consider it experimental and haven't tested it on other devices. Here is a complete example:
https://gist.github.com/1206008

I just want to add to what has already been said.
With Cascading Style Sheets you can apply styles to a lot of types of documents.
The common use case is to apply CSS to HTML pages. In this case, the general idea is to use the content property only for aesthetic purposes.
Another use case is instead to apply CSS to XML documents. In this case the document usually does not contain elements for page structure (div, h1, etc...). So, in this scenario, by using the content CSS property more frequently, you can better define the page and the relations between elements and data.
For example you could prepend a description paragraph before a table, or appending the email address after the name of a person. Note that in HTML pages these page-structure elements should be part of the HTML document itself while they are usually omitted in a XML document and so they can be added using the content CSS property.

One of interesting use cases would be localization of a User Interface.

Related

How to do CSS text replacement using generated :before or :after without absolute positioning?

I'm attempting to allow our CMS editors the ability to swap out the text used for a page title using only a css override.
<header data-alternate="An Alternate Title">
This Page's Default Title
</header>
Using the :before or :after tag, one could use one of many available alternate titles.
header:before {
content: attr(data-alternate);
display: inline-block;
}
If only we could also say,
header:text {
display: none;
}
Unfortunately, as far as I can tell, there is no good way to hide "This Page's Default Title" in order to replace it with "An Alternate Title". If this were a Sprite, we could use one of the well-worn image replacement techniques like Phark or otherwise. Not so much with text replacement generated by :before, because the :before is also affected by the CSS devices used to hide the default text so that, with Phark, for example, the :before content is also at -9999px.
There are solutions I'm trying to avoid.
Using the Phark method or somesuch to hide the default text and then using absolute positioning on the :before content to put it back at left: 0, top: 0. I want/need to preserve flow if possible.
Wrapping the "Page's Default Title" in a span and just setting it to display: none in the CSS when an alternate title is being used.
i.e.
<header data-alternate="An Alternate Title">
<span class="default">This Page's Default Title</span>
</header>
This works, but a span nested in a header is displeasing.
Is there a way to target a tag's text without also targeting its generated :before/:after content? Is there another way to do this?
I'm not sure if this is exactly what you want, but you could try something like this:
p {
visibility: hidden;
}
p:before {
content: attr(data-alternate);
display: inline-block;
visibility: visible;
}
http://jsfiddle.net/yJKEZ/
You can set the visibility of the p element to be hidden, and then set the visibility of the :before pseudo-element to be visible within it's parent (the p) despite it's setting.
If that doesn't quite work as expected, there isn't really anything tremendously wrong with adding an extra span in, to help the process. It might not be as clean, but it could work better.
I do, however, want to raise the question of why you might need to do this, and point out some concerns with an approach like this...
For starters, pseudo elements are not part of the DOM, so that alternate text can't be selected, and isn't as accessible to the browser (or the user). Screen readers or search engines will see the default text, and not pay any attention to the alternate text, but that's what your user will see... This could lead to some confusion.
While your question specifies that you want to be able to do this with CSS, and while it may be possible, it really isn't the best solution for doing something like this. Especially if your website is being viewed in an older browser which does not support pseudo elements (Now the user sees nothing at all!).
I would more recommend something like this for swapping an image out for alt text in a print stylesheet, or swapping a hyperlink's text for the full address that it links too (again, mainly for a print stylesheet). Changing important content like a heading in this fashion can cause a lot of other issues, especially in terms of accessibility.
Just something for you to consider along with my answer... I hope I've helped you with your problem!

Applying CSS to <a that has no <img child

I am using a special link effect on <a> tags with the background-image: CSS. The links look nice but the website also contains a lot of <img> that are links, which also get the CSS.
I am currently solving the issue with jQuery: $("img").parent().css("background", "none");
Is there any correct way of doing this with CSS, getting this CSS not to affect tags.
Code:
a:link ,a:visited {
text-decoration: none;
background-image: url(/underline.png);
background-repeat: repeat-x;
background-position: bottom;
}
CSS4 defines the following syntax:
!a>img {background-image:none}
However, as far as I'm aware no browser supports it yet. It's also not final on where the ! goes, as a!>img and !a!>img all have been suggested.
So, basically, there is no CSS solution for this. However, there is a "hack" solution.
Assuming body {background:white}, you can do this:
a>img {background:white}
This will cover up the link's background with a white one, which essentially hides it. Adjust the colour as needed. Note that this won't work if your content area has a background image...
When I saw this: background-image: url(/underline.png); I got very nervous. Is there some special effect you need to employ here? What's wrong with the underline property in CSS?
To solve this in CSS2 you'll need to redesign your code. Therefore, this might be a bit impractical.
Keep your css code for links.
Then wherever you have a link with an image in there, you should add a class. Use this class to link CSS that overrides the typical behavior.
There is no way to do what you want in current CSS capabilities. Jquery works but it is afterall a hack.
a {
code here that you want
}
a.img {
override properties
}
<!-- Html -->
Normal Text
<a class="img" href="#"><img src="image.png" width="x" height="y" alt="" /></a>
Some food for thought -> The reason CSS does not support what you seek is because a child should not define a parent's style! AFterall, we (as people) do not define our parents' traits but we surely override what we inherited.
What would be the difference in your links ?
Domain, peticular folders, extension name , etc...
I asked cause you could filter them by url.
[href~=picto] will mathch if url contains picto or something similar
[href^="image/] will match any url begining with image/whatever_is_behind_or_not
[href*="image/] will match any url containing image/
[href$=".jpg"] will match any url ending with this .jpg extension
As you can see , there's nowdays lots of option , level4 will make it much easier though :)
Well, unless I am missing something, the solution to this is rather simple.
On a website I worked on I used the following two CSS rules to differentiate between linked text effects and linked image effects:
a:link {
/* rules for linked text effects */
}
a img {
/* rules for linked img effects */
}

Have you ever set a class for your css that uses it multiple times?

I always was told to take out multiple properties in your css that you use more then once, and add them all in one rule. Like below. (please excuse the poor example)
I always seen this:
.button, .list, .items { color: #444; }
With multiple rules, can't that leave a lot of clutter?
Only in css tutorials and examples Ive seen this:
.someColor { color: #444; }
And in the css, just add another class of '.sameColor'. (div class="button someColor")
I've never seen this and feels like it would leave less clutter in your CSS. Would this be okay? Or do you think it could leave with more clutter in your HTML ?
Try to name your classes independently of their visual effect. It is a nature of CSS to play with the design and layout without having to change the HTML. Class names such as .someColor or .left-sidebar are a bad practice. Colors and position can change.
And also apply rules to semantic HTML elements rather than adding classes on all different divs and spans. It should be obvious, although many people get this wrong.
CSS is a limited set of rules and that makes it a perfect creativity stimulator.
It's all based on personal preference. I've tried both methods and prefer the second method you listed, except with more generic class names such as middleParagraph or headerGraphic so it applies to an area rather than a specific color because colors can change.
Good classnames and IDs are the first place you should optimize. THEN move onto multiple class names.
Multiple classnames can help out quite a bit though, consider:
<div class="leftColumn">Left</div>
<div class="rightColumn">Right</div>
<div class="middleColumn hasLeft hasRight">I have padding-left of 210px and padding-right of 210px</div>
<!-- alternatively, you could have -->
<div class="rightColumn">Right</div>
<div class="middleColumn hasRignt">I have padding right of 210px</div>
<!-- or -->
<div class="leftColumn">Left</div>
<div class="middleColumn hasLeft">I have padding left of 210px</div>
<!-- or -->
<div class="middleColumn">I have no padding</div>
and your css
.leftColumn { width:200px; float:left; }
.rightColumn { width:200px; float:right; }
.middleColumn.hasLeft { padding-left:210px; }
.middleColumn.hasRight { padding-right:210px; }
The result is floated right/left columns and the center area compensates for them with padding. This means you can style your middleColumn how you want to (e.g. .middleColumn .otherCoolSelector ).
It's perfectly acceptable to apply multiple classes to HTML elements. The trick is to be judicious; I usually find that when I do this, the additional classes are additions or exceptions to the basic styling being applied. For example, here are some classes I occasionally add to an element that already has a class:
error -- to style the current element if the user entered invalid data
first -- to style the first element in a list or in a table row, e.g. to suppress padding-left
last -- to style the final element in a list or in a table row, e.g. to suppress margin-right
even -- to apply zebra-striping to alternate elements
hidden -- to hide an element if it's not currently relevant
These extra classes are typically generated dynamically with a server-side language like ASP.NET or PHP. They can also be added or removed on the client side with JavaScript, esp. with a library like jQuery. This is especially useful to show or hide elements in response to an event.
There are a lot of good answers here. The trick is finding out which one fits your situation best.
One thing to consider is your markup size. In a high-traffic situation, your markup size is critical to the speed of your page loads...every byte counts. If this is the case for you, then you may want to create more CSS classes and put less in your markup. That way, the client is caching more and your website is serving up less.
What you're suggesting is a bit like an in-line style, e.g. style="color:#444". So if you want to change the color of your element you'd have to make a change to the html, which means you've defined style as part of your content. Which is exactly what css is supposed to avoid.
Imagine if you'd included 'someColor,' multiple times across multiple html files and you decide some of these elements shouldn't have 'someColor,' after all, you've got a lot of files to go through.
I'd probably avoid the list option too, if I'm making a component, say a button, I want to find .mybutton class in my css file and see all the rules for that component, without having to go through all sorts of unhelpful global classes. Also if someone comes along and changes the color in our global class he may break my button, where as if the button controlled it's own styles it can't be broken in this way.

What are good 'marker' css styles to define?

I am finding it useful to define 'marker' css styles such as 'hidden' or 'selected' so I can easily mark something as hidden or selected - especially when using a tag based technology like ASP.NET MVC or PHP.
.hidden
{
display:none;
}
.newsItemList li.selected
{
background-color: yellow;
}
I don't especially feel like reinventing the wheel here and wanted to know what other things like this are useful or common - or if there are any pitfalls to watch out for.
Should I look at any specific css frameworks for other things like this? Plus is there a name for this type of css class that I can search by.
I agree with the other posters who say only to define what you need, rather than bloating your code with a bunch of unnecessary classes.
That being said, I find myself using the following on a constant basis:
.accessibility - visually hide elements, but keep them intact for screenreaders and print stylesheets
.clear - tied to Easy Clearing
.first-child and .last-child - easily assign styles to the first/last item in a container. This has been a lifesaver many times, and I prefer it over the poorly-supported :pseudo selectors
.replace - tied to Phark IR for transparent image replacement
Finally, I dynamically assign .js to the <html> element with
<script type="text/javascript">if(h=document.documentElement)h.className+=" js"</script>
This will allow me to define .js (rest of selector) styles to target only browsers with JavaScript enabled.
Let me give you an answer from a very novice web developer who has recently considered using CSS classes as "markers". Please don't take this as a definitive answer, as I may be completely wrong, but look at it as another point of view.
I was going to use some marker classes, too. I created one called .center to center the elements in a DIV tag. However, I was struck with the idea that I'm looking at CSS all wrong. I reasoned that CSS is supposed to define how an element is to be displayed without having to change the HTML page. By using marker classes, like .center for example, I would have to change BOTH the CSS and HTML if I wanted that DIV tag to be right-justified next month. So instead, I created a .latestHeader class (the DIV is to hold the "latest information" such as a news item), and in that class I set the text to align center. Now, when I want to change the justification of the text, I simply change the CSS for that DIV and I don't have to touch the HTML.
In regards to your question about CSS frameworks...
Personally I've always found the W3C has the most complex but also most accurate answer to any CSS question.
After many years of programming and playing around with CSS/HTML/PHP I agree with the above comment.
There is no harm in defining a marker for something to be centered or right-aligned using something along the lines of a '.center' or '.righths', but keep in mind as above that if you want to change a whole slab of text your work will be increased because you have to edit both CSS and HTML.
Defining the format for a whole section will mostly likely work out more logical, because if you want to change the section months down the trail, you just have to edit the format of one CSS declaration as opposed to editing each individual article.
CSS was however designed as the ultimate styling language which could allow an administrator to make a website look exactly what they want it to. Keep in mind though that excess CSS will increase the load on a server, will increase the time before your client sees your page and in line with the 'feng shui of web design' it is possible to go overboard with too much styling.
You should really grow this list on a need basis instead of soliciting a list of generic classes across the board--you'll only end up with bloat. If you want to avoid reinventing the wheel the look into some CSS frameworks (blueprint or 960). In some respect, generic classes like .center { text-align:center } do have some level of redundancy but often times they're needed. For example the following pattern which is all too common but should be avoided:
element.onclick(function(e){ this.style.backgroundColor = 'yellow' }
That's bad because you really ought to be using:
element.onclick(function(e){ this.className = 'highlight' }
The latter allows you to modify your styles by only touching the CSS files. But if a CSS class name has only one style element then you should probably avoid it because it doesn't make any sense to have it (.hidden in your example) and call it directly instead:
element.onclick(function(e){ this.display = 'hidden}
I often find myself keeping two classes in all of my stylesheets: "center" (which simply applies text-align: center;, and a float-clearing class that applies clear:both;.
I've considered adding a "reset" statement to all my styles, but haven't had a need for it yet. The reset statement would be something similar to this:
*
{
margin: 0;
padding: 0;
}
I reuse these often enough to include them in just about everything. They're small enough so I don't feel they bloat the code at all.

CSS 'schema' how-to

How does one go about establishing a CSS 'schema', or hierarchy, of general element styles, nested element styles, and classed element styles. For a rank novice like me, the amount of information in stylesheets I view is completely overwhelming. What process does one follow in creating a well factored stylesheet or sheets, compared to inline style attributes?
I'm a big fan of naming my CSS classes by their contents or content types, for example a <ul> containing navigational "tabs" would have class="tabs". A header containing a date could be class="date" or an ordered list containing a top 10 list could have class="chart". Similarly, for IDs, one could give the page footer id="footer" or the logo of the website id="mainLogo". I find that it not only makes classes easy to remember but also encourages proper cascading of the CSS. Things like ol.chart {font-weight: bold; color: blue;} #footer ol.chart {color: green;} are quite readable and takes into account how CSS selectors gain weight by being more specific.
Proper indenting is also a great help. Your CSS is likely to grow quite a lot unless you want to refactor your HTML templates evertime you add a new section to your site or want to publish a new type of content. However hard you try you will inevitably have to add a few new rules (or exceptions) that you didn't anticipate in your original schema. Indeting will allow you to scan a large CSS file a lot quicker. My personal preference is to indent on how specific and/or nested the selector is, something like this:
ul.tabs {
list-style-type: none;
}
ul.tabs li {
float: left;
}
ul.tabs li img {
border: none;
}
That way the "parent" is always furthest to the left and so the text gets broken up into blocks by parent containers. I also like to split the stylesheet into a few sections; first comes all the selectors for HTML elements. I consider these so generic that they should come first really. Here I put "body { font-size: 77%; }" and "a { color: #FFCC00; }" etc. After that I would put selectors for the main framework parts of the page, for instance "ul#mainMenu { float: left; }" and "div#footer { height: 4em; }". Then on to common object classes, "td.price { text-align: right; }", finally followed by extra little bits like ".clear { clear: both; }". Now that's just how I like to do it - I'm sure there are better ways but it works for me.
Finally, a couple of tips:
Make best use of cascades and don't "overclass" stuff. If you give a <ul> class="textNav" then you can access its <li>s and their children without having to add any additional class assignments. ul.textNav li a:hover {}
Don't be afraid to use multiple classes on a single object. This is perfectly valid and very useful. You then have control of the CSS for groups of objects from more than one axis. Also giving the object an ID adds yet a third axis. For example:
<style>
div.box {
float: left;
border: 1px solid blue;
padding: 1em;
}
div.wide {
width: 15em;
}
div.narrow {
width: 8em;
}
div#oddOneOut {
float: right;
}
</style>
<div class="box wide">a wide box</div>
<div class="box narrow">a narrow box</div>
<div class="box wide" id="oddOneOut">an odd box</div>
Giving a class to your document <body> tag (or ID since there should only ever be one...) enables some nifty overrides for individual pages, like hilighting the menu item for the page you're currently on or getting rid of that redundant second sign-in form on the sign-in page, all using CSS only. "body.signIn div#mainMenu form.signIn { display: none; }"
I hope you find at least some of my ramblings useful and wish you the best with your projects!
There are a number of different things you can do to aid in the organisation of your CSS. For example:
Split your CSS up into multiple files. For example: have one file for layout, one for text, one for reset styles etc.
Comment your CSS code.
Why not add a table of contents?
Try using a CSS framework like 960.gs to get your started.
It's all down to personal taste really. But here are a few links that you might find useful:
http://www.smashingmagazine.com/2008/08/18/7-principles-of-clean-and-optimized-css-code/
http://www.smashingmagazine.com/2008/05/02/improving-code-readability-with-css-styleguides/
http://www.louddog.com/bloggity/2008/03/css-best-practices.php
http://natbat.net/2008/Sep/28/css-systems/
Think of the CSS as creating a 'toolkit' that the HTML can refer to. The following rules will help:
Make class names unambiguous. In most cases this means prefixing them in a predicatable way. For example, rather than left, use something like header_links_object2_left.
Use id rather than class only if you know there will only ever be one of an object on a page. Again, make the id unambiguous.
Consider side effects. Rules like margin and padding, float and clear, and so on can all have unexpected consequences on other elements.
If your stylesheet is to be used my several HTML coders, consider writing them a small, clear guide to how to write HTML to match your scheme. Keep it simple, or you'll bore them.
And as always, test it in multiple browsers, on multiple operating systems, on lots of different pages, and under any other unusual conditions you can think of.
Putting all of your CSS declarations in roughly the same order as they will land in the document hierarchy is generally a good thing. This makes it fairly easy for future readers to see what attributes will be inherited, since those classes will be higher up in the file.
Also, this is sort of orthogonal to your question, but if you are looking for a tool to help you read a CSS file and see how everything shakes out, I cannot recommend Firebug enough.
The best organizational advice I've ever received came from a presentation at An Event Apart.
Assuming you're keeping everything in a single stylesheet, there's basically five parts to it:
Reset rules (may be as simple as the
* {margin: 0; padding: 0} rule,
Eric Meyer's reset, or the YUI
reset)
Basic element styling; this
is the stuff like basic typography
for paragraphs, spacing for lists,
etc.
Universal classes; this section
for me generally contains things
like .error, .left (I'm only 80%
semantic), etc.
Universal
layout/IDs; #content, #header,
or whatever you've cut your page up
into.
Page-specific rules; if you
need to modify an existing style
just for one or a few pages, stick a
unique ID high up (body tag is
usually good) and toss your
overrides at the end of the document
I don't recommend using a CSS framework unless you need to mock something up in HTML fast. They're far too bloated, and I've never met one whose semantics made sense to me; it's much better practice to create your own "framework" as you figure out what code is shared by your projects over time.
Reading other people's code is a whole other issue, and with that I wish you the best of luck. There's some truly horrific CSS out there.
Cop-out line of the year: it depends.
How much do you need to be styling? Do you need to change the aspects of alomost every element, or is it only a few?
My favorite place to go for information like this is CSS Zen Garden & A List Apart.
There are two worlds:
The human editor perspective: Where CSS is most easily understand, when it has clear structure, good formatting, verbose names, structured into layout, color and typesetting...
The consumer perspective: The visitor is most happy if your site loades quickly, if it look perfect in his browser, so the css has to be small, in one file (to save further connections) and contain CSS hacks to support all browsers.
I recommend you to start with a CSS framework:
Blueprint if you like smaller things
or YAML for a big and functional one
There is also a list of CSS Frameworks...
And then bring it in shape (for the browser) with a CSS Optimizer (p.e. CSS Form.&Opti.)
You can measure the Results (unpotimized <-> optimized) with YSlow.
A few more tips for keeping organized:
Within each declaration, adopt an order of attributes that you stick to. For example, I usually list margins, padding, height, width, border, fonts, display/float/other, in that order, allowing for easier readability in my next tip
Write your CSS like you would any other code: indent! It's easy to scan a CSS file for high level elements and then drill down rather than simply going by source order of your HTML.
Semantic HTML with good class names can help a lot with remembering what styles apply to which elements.

Resources