Using data attributes instead of classes in CSS - css

HTML
<div data-foo> ... </div>
CSS
div[data-foo]{ ... }
Is this a good idea? Are there any drawbacks?
I think the data- approach makes sense when I have hundreds of "foo" elements, because the HTML markup size decreases (-3 characters for each element).

div[data-foo] is not supported in old IE (IE6, see here: http://www.quirksmode.org/css/selectors/)
div[data-foo] makes less semantic sense
class="foo" and data-foo will take up about the same space when DEFLATE-d. If you haven't set up your server to deflate, you should.
class=foo is only one character longer than data-foo even uncompressed, and is perfectly valid HTML.

It totally depends on you, for example elements must be having different attributes, so you need to define styles and even repeat some, instead I'll use a class which I can use for both, instead of using attribute selector which will limit my declared properties upto an element with that attribute, where you can freely use classes regardless of element attribute combination
.class { /* You can use this anywhere you need these properties */
font-family: Arial;
font-size: 13px;
}
Where as this will limit to ELEMENT-ATTRIBUTE combination
div[data-menu] { /* This will LIMIT you to a combination of div
element having an attribute called data-menu */
font-family: Arial;
font-size: 13px;
}
Important : Specificity will make you a huge mess

Related

How are unknown/invalid pseudo-classes in CSS selectors handled?

What does this CSS selector should point to? AFAIK :bar pseudo-class does not exist...
.Today_s_foo:bar
{
font-size: 21px;
font-family: "Ubuntu";
}
Normally it should invalidate the whole rule, which may be important when using multiple selectors in one rule, see simple example: http://jsfiddle.net/S56xM/
HTML:
<div>Hello!</div>
CSS:
div, div:foobaresque { font-size: 100px; }
You will see that the div { font-size: 100px; } "sub-rule" is not applied, even if our mind tells us it would be applied.
Per the current specification for parsing errors in selectors: "the entire rule in which the selector is used is dropped." See also this part of the spec for an example of the consequences.
By "rule" it means every property setting inside the {brackets} will be ignored if any part of the selector is parsed as invalid.
Correction applied
The rules in .Today_s_foo will not be set on any working browser.
I thought it was listed as an Unrecommended hack on http://www.javascriptkit.com/dhtmltutors/csshacks3.shtml
IE
.Today_s_foo:IE6 /* IE6 hack */
but its not there.

What is the purpose of using font: inherit?

I just wanted to know why font: inherit; is used in Cascading Style Sheets.
Like the other answers have said, it’s to inherit a CSS property from the parent element.
What the other answers have failed to say is why you’d need this. Because, after all, CSS properties are inherited anyway, right?
Well, no. Most are, by default (but link colour isn’t inherited from the parent element, for instance). But consider this case:
p { color: blue; }
div.important { color: red; }
<div class="important">
<p>This is a text</p>
</div>
Now the text will be blue, not red. If we want the <p> to have its parent’s styling rather than its default styling, we have to override its CSS. We could of course repeat the property value (red) but that violates DRY (don’t repeat yourself). Instead, we inherit it:
div.important p { color: inherit; }
The declaration font:inherit is used in many “CSS Reset” stylesheets, which have often been copied into various libraries and frameworks. The original Reset CSS by Eric Meyer has font:inherit. No specific motivation is given. The overall rationale is said to be “to reduce browser inconsistencies in things like default line heights, margins and font sizes of headings, and so on”. But Meyer links to a previous post of his where he explains the idea, saying, among other things: “I want all this because I don’t want to take style effects for granted. This serves two purposes. First, it makes me think just that little bit harder about the semantics of my document. With the reset in place, I don’t pick strong because the design calls for boldfacing. Instead, I pick the right element—whether it’s strong or em or b or h3 or whatever—and then style it as needed.”
Several HTML elements have a default rendering in browsers as regards to font properties: headings, form fields, table header cells, some phrase elements, etc. Using CSS Reset, or specifically font: inherit means that on browsers supporting the inherit value, all such elements are rendered in copy text font, unless otherwise specified in a style sheet.
So this is about a particular methodology (or, as some people might say, ideology or religion) of authoring and design. It has gained popularity and often applied routinely.
The font CSS property is either a shorthand property for setting font-style, font-variant, font-weight, font-size, line-height, and font-family; or a way to set the element's font to a system font, using specific keywords. -MDN
By using font: inherit;, it tells an element to inherit those relevant values from its parent container. See the examples below:
In the 1st group: you can see there are some special style set by default from the browser, h1 is bolder and larger it also inherits the relevant values from body automatically. However, for the input element, it doesn't inherit any of those values, since it's a replaced element and serves its unique purpose.
In the 2nd group: It forces those elements to inherit those values from body by using font: inherit;.
Now, you see what it does. It's entirely up to you when to use it, for instance you might want to use <h1> tag for the site logo in the home page, and you probably want to make it look no difference than it appears on other pages. And of course, it's commonly being used in CSS reset frameworks.
body {
font-family: "Comic Sans MS", "Comic Sans", cursive;
font-style: italic;
}
.inherit {
font: inherit;
}
<h1>Heading</h1>
<input type="button" value="Button">
<hr>
<h1 class="inherit">Heading</h1>
<input class="inherit" type="button" value="Button">
Not all browsers inherit font properties on all elements. Netscape 4.x was notoriously bad about about inheritance. Consider the following style:
body { background: black; color: white }
In Netscape 4.x, the color was not applied to table elements, so you would end up with the default black text inside the table on a black background.
Font properties have the same kind of deal for some elements, particularly form elements (and table elements for older browsers). It's not uncommon to see a definition like this:
table, form { font: inherit }
The inherit is used to get the properties from the parent element. In other words, inherit the properties of parent element.
The default property is inherit, it means, say you have div and a p.
<div>
<p>Hello World!</p>
</div>
Now you give a style:
div {font-famlily: Tahoma;}
p {font-family: inherit;}
That font-family is inherited to the p from its parent element div.
Using {font:inherit;} in CSS makes sense because various user agents (a.k.a. browsers) have user agent stylesheet (read: default stylesheet) with something like
body
{
font: -magic-font-from-user-preferences;
}
textarea, input
{
font: monospace;
}
The {font:inherit;} is used to workaround the special case where font or font-family is not inherited by default due to user agent stylesheet but the author of the content wishes the font family to be inherited.
The actual user agent behavior with the value inherit differs due to various bugs, unfortunately. Resulting behavior may be closer to author intent than the default value, though.
inherit in CSS simply means it inherits the values from parent element, so for example:
<div style="font-family: Arial;">
<p style="font-family: inherit; /* This will inherit the font-family of the parent p*/">
This text will be Arial..And inherit is default behavior of the browser
</p>
</div>
Here <p> inherits the font-family: Arial; from it's parent div
You need to use inherit for example in the case of anchor elements,
the color property is commonly set to blue in the user agent style
sheet. If you wanted to reinforce the importance of the inherited
value, you could use the value inherit in an author or user style
sheet, overwriting the user agent style sheet declaration.
More Reference

Override font size in a DIV using CSS

In a DIV I place some text/html code which get loaded from a database. This text sometimes contains font size definitions (ex: font size="3"). is there a way to override this font size in this specific DIV using CSS.
I am grateful for any help.
Assuming mark-up similar to the following:
<div>
<font size="1">Some text at 'size="1"'</font> and natively-sized text, with more at <font size="26">'size="26".'</font>
</div>​
Then you can explicitly instruct CSS to inherit the font-size from the parent element:
div {
font-size: 1.5em;
}
div font {
font-size: inherit;
}
JS Fiddle demo.
Please note, of course, that font is deprecated and should, therefore, not be used (as support for the element can stop without notice, and/or implementations change without warning).
Incidentally, while !important will force a declaration to override the usual cascade of styles, it's taking a sledgehammer to crack a nut; and, if it can be avoided (and in this case, it seems, it can be avoided) it should be, since it complicates later debugging of styles, and associated inheritance problems.
Further, this is treating the symptom of your problem; the problem you're really facing is the presence of the font tags in your content/database. This should be corrected, by removing the elements, and replacing them with appropriately-styled elements, such as em, span and so forth...
References:
font element, at the W3.org.
font element at the MDN.
Using the CSS !important notation you are telling the browser to overwrite any font-size defined inside your div:
From the above link it reads:
However, for balance, an "!important" declaration (the delimiter token "!" and keyword "important" follow the declaration) takes precedence over a normal declaration.
Example
See this working Fiddle Example!
.htmlContents * {font-size:10px!important;}
<div class="htmlContents">my database html content</div>
One idea: give these text tags an id or class, then use JavaScript to find these elements and change the style on them.
How about stripping the "font" tags from the text before inserting into the div? Then just style the div with a font size.
Thanks had same problem couldn't override font-size of footer of a nested element a.
.footer ul li a {
font-size: 20px ;
height: 25px;
}

Use HTML tag names, classes or IDs in CSS?

In designing the HTML and CSS for a page, when should I use
img.className
versus
.className
versus
#idName
or some other variant?
Are there guidelines or recommendations?
Summary from answers
Thank you to all answerers - there is some excellent stuff here!
make CSS as specific as possible
use an OO approach
order: #id, tag, tag.className, .className
when to use each selector, also class/ID comparison
give selectors names based on purpose, not what they look like
use advanced selectors for smaller code, leave CSS classes for exceptions/overrides only
manage ASP.NET munging ID
In general you should be as specific as the item demands.
There is no general rule, it depends on the style in question.
A lot of people will recommend you keep to the lowest specificity with the theory that this allows the maximum cascading reuse but this is absolutely toxic in real world situations where you have multiple developers all working on slightly different versions of what a .foo might look like. Pollution from inheritance you did not want leads to massive bloat in trying to undo that locally or time-loss in refactoring.
The best guideline I always offer is to try and think of CSS in OO terms: class selectors map to interfaces more or less, tags map to classes, and ID selectors map to instances. Consequently decide if the style you want to apply really applies to that thing, all things like it, or anything which wants it.
I also strongly encourage you to make use of high level IDs on wrapper elements so you can write selectors in a namespace like fashion (i.e. #foo .bar, #foo .baz where #foo is unique to a page or set of page designs) which allows you both a level of specificity which reduces cross-design pollution and a level of generality which lets you make the most of cascading CSS reuse.
Best of both worlds.
It depends on the intended semantics, and, as others said, be as specific as possible.
#idName for unique elements on the page. Good examples are #header and #footer
TAGNAME for general purpose page styling.
TAG.classname and .classname for exceptions/overrides to the above rules.
And don't forget the use of advanced selectors. A bad example:
<style>
H1{ font-size: 200%; color: #008; }
#mainMenu { color: #800; }
.in_the_menu { color: #800; font-size: 150%; }
</style>
<h1>Hello World!</h1>
<div id="mainMenu">
<h1 class="in_the_menu">My Menu</h1>
</div>
The same could have been achieved with:
<style>
H1{ font-size: 200%; color: #008; }
#mainMenu { color: #800; }
#mainMenu H1 { color: #800; font-size: 150%; }
</style>
<h1>Hello World!</h1>
<div id="mainMenu">
<h1>My Menu</h1>
</div>
The second example gets rid of the superflous "class" attribute on the H1 element in the "mainMenu" div. This has two important benefits:
The HTML code is smaller and cleaner
You are less likely to forget to add the class attribute
If you take good care of you CSS, and make use of proper advanced selectors, you can nearly completely leave out CSS classes. And keep them only for exceptions/overrides.
Take this example which draws boxes with headers:
#content H2{
border: 1px solid #008789;
padding: 0em 1em;
margin: 0.2em 0em;
margin-bottom: 1em;
font-size: 100%;
background: #cccb79
}
#content H2 + DIV{
margin-top: -1em;
border-left: 1px solid #008789;
border-right: 1px solid #008789;
border-bottom: 1px solid #008789;
margin-bottom: 1em;
}
Now, as soon as you follow a H2 with a DIV in the #content element, you have a nice box. other DIVs and H2s are left alone:
<div id="content">
<h2>Hello Box!</h2>
<div>Some text</div>
<div>Some more text</div>
<div>Some more text</div>
<h2>And another title</h2>
</div>
If you get these rules right, you hardly ever need classes, and can work with IDs and TAG names alone. And as an added bonus, your HTML will be a lot nicer to read and maintain.
You preference should be, in order from highest to lowest:
id
tag
tag.className
.className
ID selectors are fast. Tag selectors are reasonably fast. Pure class selectors are slow because the browser essentially has to interrogate every element and see if each has that class. Getting elements by ID or tag name are "native" operations from a browser's context.
Also, I find it good practice to make your CSS selectors as restrictive as possible otherwise it just turns into a mess and you end up getting all sorts of unintended consequences where CSS rules apply where you didn't otherwise expect, which often forces you to create a similar yet different selector just so none of the rules regarding the first don't apply (translating into more mess).
Basically if you know if you only use a class on div elements then do this
div.className
not
.className
If you apply a class to several elements just list them:
h1.selected, h2.selected, h3.selected
instead of
.selected
In practice I find very few situations where you need to use "naked" class selectors or where it is advisable to do so.
you should use the selector best describing your rules
id: when you want to select one single element
.classname: when you want to style elements regardless of their tag
tag.classname: when you want to style only tags with the given class
tag tag tag: when you want to style all subelements of a tag
Class selectors
.className
This is to be used when you have more than one element on the page that you would like to apply the same style to. It can be to any tag element. So in the following all will use the same style as set out by the .className.
<p class="className"></p>
<img src="/path/to/image.png" class="className" />
But you can also restrict it like so:
img.className
By placing the tag along with the style definition, you're saying that this style is only to be used when it's the class used by that particular tag, in this case, an image.
HTML code will look like this:
<img src="/path/to/image.png" class="className" />
If you have other elements on the page using the same class style, but are not of the same tag, then the styles set out in this will not be applied and they will take on the more generic version as mentioned in the first example.
So repeating the example above:
<p class="className"></p>
<img src="/path/to/image.png" class="className" />
Only the image will take on the style as set out by img.className whereas all the rest will take on the style rules set in .className.
ID selectors
#idName
This is to be used when there is only one instance of a particular element that you wish to apply the style to.
You can also force it to apply only in certain tag conditions as you have earlier with the class definitions.
p#idName
This example will only apply to the paragraph block marked with the ID:
<p id="idName">
If you were to put that id on another element, like this:
<div id="idName"></div>
Then it will not take on the style set out and be ignored.
As to your two first selectors, the first of the two will overwrite the second, as it's more specific. You can calculate the specificity of a selector.
One thing worth noting is that some server side scripting technologies (most notably ASP.NET) don't play well with using IDs for your styling. If there is a chance your design will be used with such a technology, I recommend forgetting about #id selectors and use tag.className instead.
The reason is that ASP.NET actually changes the ID that ends up in the HTML based on a number of criteria, if the tag is output by a server side control.
I know this is a pretty old question but for all those who are reading this just now...
There are 4 categories of rules in general:
ID Rules, Class Rules, Tag Rules, Universal Rules.
And it's important to mention that class selectors are faster than tag selectors. So you should always use them in the following order
1. ID Selector
2. Class Selector
3. Tag Selector
4. Universal Selectors
In your case you should never use the tag name before class name.
You can find more information here: Writing efficient CSS
It really depends on the situation:
.error{
color:red;
}
p.error{
background-color:yellow;
}
div.error{
background-color:grey;
}
Always use the cascading effect of CSS to your advantage.
It's good practise to use the least specific rules you can for each rule.
How you structure your CSS will depend on the particular needs of the design.
Yes. You may want to use the same classname for two elements in the future. Be explicit and clear. This will also prevent class-rules from overlapping onto unintended elements.
h1.title { font-size:18px; } /* My h1's are big */
p.title { font-size:16px; } /* My p's are smaller */
.title { color:#336699; } /* All titles are blue */
Use ID's only when necessary, and only once per page.
When to use what depends on what you want to select. img.className (type selector + class selector) selects only IMG elements that’s in the class “className” while .className (just class selector) selects any element that’s in that class and #idName (id selector) any element with the ID “idName”.
But besides that, the selector all have a differente specificity that affects the order in which the properties of that rules overwrite the one of others.
So if you have an IMG element with the ID “idName” that’s in the class “className”:
<img src="…" id="idName" class="className">
The properties of the rules would be applied in the following order (specificity from highest to lowest):
#idName
img.className
.className
But when you use a specific class only for one specific type of elements (e.g. “className” only for IMG element), you can go with only .className.

CSS Reset, default styles for common elements

After applying a CSS reset, I want to get back to 'normal' behavior for html elements like: p, h1..h6, strong, ul and li.
Now when I say normal I mean e.g. the p element adds spacing or a carriage return like result when used, or the size of the font and boldness for a h1 tag, along with the spacing.
I realize it is totally up to me how I want to set the style, but I want to get back to normal behavior for some of the more common elements (at least as a starting point that I can tweak later on).
YUI provides a base CSS file that will give consistent styles across all 'A-grade' browsers. They also provide a CSS reset file, so you could use that as well, but you say you've already reset the CSS. For further details go to the YUI website. This is what I've been using and it works really well.
One of the rules in applying CSS styles is "last in wins." This means if your CSS reset styles set elements to margin:0; padding:0 you can then override these rules by declaring your desired values for the same elements afterwards.
You can do this in the same file (YUI offers a one-liner reset I think so I sometimes include it as the first line in my CSS file) or in a separate file that appears after the reset CSS <link/> tag.
I think by normal behavior you mean "the defaults for my favorite browser." Your building up CSS rules for these elements is a part of the reset exercise.
Now you might want to look into Blueprint CSS or other grid frameworks. These grid frameworks almost always first reset styles to nothing, then build up the typography for common elements, etc. This could save you some time and effort.
You mean like:
* {
padding: 0;
margin: 0;
}
h1, h2, h3, h4, h5, h6, p, blockquote, form, label, ul, ol, dl, fieldset, address {
margin-bottom: 1em;
}
?
Actually, sorry I mis-read your question, you're after something more like Eric Meyer's total reset # http://meyerweb.com/eric/tools/css/reset/
Rather than using a total CSS reset, think about using something like Normalize, which "preserves useful defaults".
To find out what your browser thinks of as default, open a plain HTML file with lists and view the lists with a CSS debugger like Firebug, and look under the Computed tab.
Check out YUI (Yahoo's open source user interface conventions).
They have a base stylesheet that undoes their own reset css.
They dont actaully recommend you use it in production - since its counter productive but definitely might be worth checking out the file to get relevant snippets for what you want to 'undo'.
I recommend you watch the 40 minute talk to get up to speed.
Heres a short snippet of their base.css file :
ol li {
/*giving OL's LIs generated numbers*/
list-style: decimal outside;
}
ul li {
/*giving UL's LIs generated disc markers*/
list-style: disc outside;
}
dl dd {
/*giving UL's LIs generated numbers*/
margin-left:1em;
}
th,td {
/*borders and padding to make the table readable*/
border:1px solid #000;
padding:.5em;
}
th {
/*distinguishing table headers from data cells*/
font-weight:bold;
text-align:center;
}
Download the full stylesheets below or read full documentation.
Yahoo reset css | Yahoo base (undo) reset css
I'm personally a big fan of BlueprintCSS. It resets styles across browsers and provides some really convenient defaults (that are what you want 90% of the time). It also provides a layout grid, but you don't have to use that if you don't need it.
If you want to see the css defaults for firefox, look for a file called 'html.css' in the distribution (there should be some other useful css files in the same directory). You could pick out the rules that you want, and apply them after a reset.
Also, the CSS2 standard has a sample stylesheet for html 4.
Normal behaviour for WebKit h1:
h1 {
display: block;
font-size: 2em;
margin: .67__qem 0 .67em 0;
font-weight: bold
}
Normal behaviour for Gecko h1:
h1 {
display: block;
font-size: 2em;
font-weight: bold;
margin: .67em 0;
}
The rest of the elements should be there if you search the files.
"After applying a CSS reset, I want to get back to 'normal' behavior for html elements..."
If you've applied a reset, you would then have to add the rules for what you believe to be normal behavior. Since normal behavior varies from browser to browser this question is something of a non sequitur. I like #da5id's answer - use one of the many available resets and tweak it to suit your needs.
Once you have assigned a value to a CSS property of an element, there is no way getting back the “normal” value for it, assuming “normal” means “browser default”, as it seems to mean here. So the only way to have, say, an h1 element have the browser default font-size is to not set the property at all for it in your CSS code.
Thus, to exempt some properties and elements from CSS reset, you need to use a more limited CSS reset. For example, you must not use * { font-size: 100% } but replace * by a list of selectors, like input, textarea { font-size: 100% } (the list could be rather long, but e.g. browser defaults for font-size differ from 100% for a few elements only).
It is of course possible to set properties to values that you expect to be browser defaults. There is no guarantee that this will have the desired effect on all browsers, current and future. But for some properties and elements, this can be relatively safe, because the defaults tend to be similar.
In particular, you might use section Rendering in HTML5 CR. It describes “expected rendering” – not a requirement, though browser vendors may decide to claim conformance to them if they so wish, and generally this will probably keep implementations rather similar in this respect. For example, for h1 the expected settings are (collected here into one rule – in HTML5 CR they are scattered around):
h1 {
unicode-bidi: isolate;
display: block;
margin-top: 0.67em;
margin-bottom: 0.67em;
font-size: 2.00em;
font-weight: bold;
}
(There are additional contextual rules. E.g., nesting h1 inside section is expected to affect the settings.)
I'm not resetting all the elements by default because the default styles are somehow browser depended, so they varies from browser to browser. Instead of using something like ul, ol { list-style: none; }, I'm adding a CSS class like r or reset and then I specify that if that is a ul which has a r class, reset it or otherwise please leave it to be untouched.
By the way you need to add class="reset" (for example) to all of those elements, which is extra work and code, however you'd have all of your default styles untouched at the end in return!

Resources