CSS: overriding specific selectors with a more general one - css

I have a CSS stylesheet that specifies the font for each paragraph class:
p.body {
font-family: Tahoma;
/* (more properties omitted for brevity) */
}
p.bodytextcenter {
font-family: Tahoma;
}
p.bodytextright {
font-family: Tahoma;
}
(etc. for dozens of styles).
Now I have to use a different font for some languages. I can do this by making a new selector p.body[lang="de"] etc, but I'd have to do that for every style in my list.
Is there a way to specify p[lang="de"] and have it apply to all paragraphs with that language attribute? Or would this require me to remove the font-family attribute from every paragraph class?

p[lang="de"] this may work but if not you can add !important on the font family style

Give this a try:
html body p[lang=de]
...or similar, depending on your actual HTML. You just need to add more levels of specificity.
This can't properly be answered without seeing your HTML; but I'm going to guess that the CSS is poorly structured, and that's what's making this hard for you. Doing the above is slightly hackish, but syntactically legit.
The rest of this might not help so much now, but good to keep in mind for the next project....
It's best to design your page structure based on the semantic meaning rather than the specific effect. Navigation, article, aside, sidebar; not left, right, bold, etc. Imagine you have a sidebar on the right. You could name it "sidebar" or "textright". But down the road you decide to put it on the left.... or do something completely different on mobile. Now "textright" is just mislabelled.
Even keeping with your current way of doing it, you should note that an element can have multiple classes. So rather than having:
<p class="body">...</p>
<p class="bodytextcenter">...</p>
<p class="bodytextright">...</p>
you could have something like:
<p class="body">...</p>
<p class="body textcenter">...</p>
<p class="body textright">...</p>
With that you can set fonts on p.body, and layout on p.textcenter and p.textright
That's an imperfect answer for the current project, as it would require changing a lot of existing text, but that goes back to the initial issue -- poorly structured CSS. (And again, without seeing HTML I'm mostly guessing here....)

Related

HTML5 Semantic tag alternatives

HTML5 has some useful semantic tags for use. They're not actually necessary, but the point of 'Semantic Web' can be helpful for organizing a lot of content.
I just came across a simple <small> tag which I never saw before. It works as it sounds, the text gets smaller.
What if the !DOCTYPE html was not for HTML5 but other legacy doctypes, what are good alternatives besides simply doing following style/CSS adjustments?
CSS: p {font-size: smaller}
HTML attribute: <p style="font-size: ##%">This text.</p>
What if the !DOCTYPE html was not for HTML5 but other legacy doctypes
<small> was introduced in HTML 3.2, not in HTML 5, so you should still use the <small> element.
The semantic meaning that <small> holds in HTML 5 wasn't there in earlier versions of HTML, but there was nothing with equivalent semantics that would be better.
An alternative would be to use a class name such as .small-text to represent small text.
.small-text {
font-size: smaller;
}
However, you should also ask yourself whether defining a class for small text is necessary. For example, you might actually want this instead:
.subtitle {
font-size: smaller;
/* other styles */
}
and avoid creating too many useless class names.
Thanks for the answers people...
I believe the <span> tag is an excellent alternative for the similar results. The difference would be that the tag comes with a preset size. <span> brings a different value being unchanged until inheriting via css/attr or js.
You won't necessarily have to worry about adding a new class, you can have it inherit a style by relative placement.
ie.
<article><p>Text here to continue for who knows how long.<small>This is small text.</small></p></article>
<article><p>Text here to continue for who knows how long.<span>This is small text.</span></p></article>
The advantage is <small> </small> will already be smaller, but who knows at what default size?...
The <span></span> will just be there awaiting definition to it...
CSS:
article > span { font-size: ###;} //no class necessary unless you really want varying span sizes in the content paragraph.

Why use :before pseudo-elements to display glyph icons?

This question is haunting in my brain for a long time. Seem like all glyph icon libraries provide icon by this way, such as Font Awesome. Is this the only way to put glyph in css? or is this the best way?
a:before {
font-family: FontAwesome;
content: "\f095";
}
I feel this question can be divided into two separate ones:
Why use fonts for icons?
Why use :before pseudo-elements to display them?
For the first part, reasons are many, but it boils down to being easy to work with (as they are vectors, have transparent backgrounds by nature, can change colours easily) and had very good support even on older browsers.
For the second part, using pseudo-elements means that your icons can fully "live" in your CSS file. Apart from it being easier to edit there, that's also where they belong - they are not part of your content, but are rather something that affects the appearance of it and thus shouldn't be in your HTML. Think of it as the same distinction as between img tag and background-image CSS property (once again - design vs content).
In addition, this prevents some strange side-effects, for example, pseudo-elements can't be selected and thus can't be copied. If this weren't the case, all icons would, when copied, result in strange characters in the destination where you copy them.
You can also use them as 'i' tags. we can apply much more creative css that way. Here's a codepen:
http://codepen.io/anon/pen/gLdYqj
<script src="https://use.fontawesome.com/2d1d8af5b4.js"></script>
<div><i class="fa fa-user"></i></div>
div{
font-size:50px;
}
i{
color:blue;
}
i:hover{
color:red;
cursor:pointer;
}

CSS for td in table using a wildcard

I'm having some trouble with some CSS. I have a number of unique tables with a similar format name, and I need to set the background color on some of them. However, if I try and use a wildcard the style gets overwritten by a parent CSS file.
The background colour here works fine:
#AllProtectedServers1 td.status.online{
color: green;
background-color: yellow;
font-weight: bold;
}
But the background colour doesn't work here as it's being overwritten higher up (although everything else does):
td.status.online {
color: green;
background-color: yellow;
font-weight: bold;
}
I'm going to have 20+ tables all starting with "AllProtectedServers", so naming them all individually is going to make the css huge. Is there anyway I could use a wildcard? I've tried using div[id^='id_'] and similar selectors without any luck.
Anyone have any ideas of what I could use instead?
Update:
Please note the ID's are unique (AllProtectedServersCompany1, AllProtectedServersCompany2, etc), but they all start with AllProtectedServers. I want to create some CSS that will override the stylesheet for the table that is overriding my changes and use a wildcard so I don't have to specify each one.
Maybe this would help:
td.status.online
{
color: green;
background-color: yellow !important;
font-weight: bold;
}
Alpipego's comment is not correct. You're perfectly fine using ID selectors (#) for CSS. These can be overwritten by other ID selectors of the same or higher specificity (depending on page order) or the !important rule.
However, you want to avoid using !important as a CSS rule because that can back you into a corner and become a maintenance nightmare.
As a matter of fact what you need to learn about is CSS Specificity. I recommend reading the CSS: Specificity Wars for an entertaining but educational overview of how CSS Specificity works.
http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html
Smashing Magazine also published an article on it that's more extensive:
http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/
You do want to be careful about not going crazy with specificity. ID's are (supposed to be) unique per page, so if you end up with a lot of deeply nested rules (#foo .bar .baz .goo), you're probably looking at needing some refactoring.
So, if you use Chrome, pop open the developer tool and look at the CSS selector and determine the specificity. All you need to do is:
a) Match the specificity but make your style come later in the DOM page order
or
b) Use a higher specificity
That's all there really is to it.
I hope that helps!
Cheers.
jmbertucci's answer is quite correct, if perhaps a little incomplete, I will expand with some examlpes.
One of the most overlooked aspects of CSS is specificity rules. As mentioned by jmbertucci please see:
http://csswizardry.com/2014/07/hacks-for-dealing-with-specificity/
http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html
A little more googling will present a wealth of articles for you.
Let's take some base html and css and a bit of a guess as to what you have.
HTML
<table class="myTable">
<tr>
<td class="status online">Online</td>
<td class="status offline">Offline</td>
</tr>
</table>
CSS
table.myTable td.status
{
background-color:#fff;
}
td.status.online
{
background-color:#f00;
}
Fiddle
This will result in a white background for "online" as table.myTable td.status is more specific than td.status.online.
In this example we need to make the second selector more specific. As you mentioned adding an ID results in what you want as IDs have an extremely high specificity score and a very hard to over-write. So much so that some say never to use them*. A simple solution in this example is to add table to the seconde selector.
table td.status.online
{
background-color:#f00;
}
This results in a red background for "online"
Fiddle
Adding table may not work in your instance. YOu need to find the style rule that is being applied using Chrome Developer Tools or Firebug for Firefox and create a rule that is more specific.
If you provide more information I may be able to provide a more specific answer.
* A note on ID's ID's extremely high specificty is both their strenth and weakness. I believe they can be used, but with caution. If you want to style a specific part of a page in a specific manner, you may have a canditate for ID. Think along the lines of a header and footer before the days of HTML5. Another good example may be <section id="discalimer">, using an ID provies two benifits: it's an anchor for specific styling and it can be linked to, e.g: Disclaimer. A further read: http://www.zeldman.com/2012/11/21/in-defense-of-descendant-selectors-and-id-elements/
Keep in mind the arguments on weather to use IDs or not are a matter of optinion and their are good points on both sides. W3C, the standards guys, has no stance on this. If where you work has a coding guide, stick to that mandate. If you're unsure, don't use them in CSS to be safe. Most importantly keep IDs unique.
Andy68man, no wildcard needed, just use a class. Same class for all the tables if they all share the same properties. As in (first the HTML):
<table class="allProtectedServers"> ..... </table>
<table class="allProtectedServers"> ..... </table>
<table class="allProtectedServers secondClass"> ..... </table>
and the CSS:
.AllProtectedServers td.status.online { ... }
If there are one or more properties that only some of the tables have, create another class and give those particular tables both classes, as in the third line of HTML above.
Alternatively, if that still gets overruled by the CSS above, put a single div round all the tables or even the whole page (or there may already be one), give the div an id, and add that into your selector to increase it's specificty (your first bit of code above shows the extra id will be enough to overrule the other CSS that's causing your problem):
#myDiv td.status.online { ... }

CSS selector style?

Sometimes I find myself creating a CSS class for a single element. So instead, I can use an ID and set a rule for this ID. Which way is preferable stylistically?
I'd say that this is more of a person-by-person preference.
For me, I try to think ahead: will I ever create two of these on one page? If the answer is even vaguely "yes," then I use classes. If I can't see the need for creating a second of the particular element, I'll use an ID.
In terms of the ID itself, I try to name it something that I won't conflict with. For instance, I'll choose something like:
#aboutus_team_wrapper {}
It's long and ugly, but I know exactly what it's for, where I'm using it, and I know I'll never create something that conflicts with the name.
Hope this helps!
Don't forget about selector specificity! I avoid using ID selectors whenever possible.
Reference: http://www.w3.org/TR/CSS2/cascade.html (6.4.3)
An ID selector is 10 times stronger than a class selector. That means you would have to use 11 class selectors to cancel an ID selector, or you would have to append the same ID selector to every CSS rule you write, or my favorite, use inline styles or !important rules!
"But why use a class style on an element that I know is only going to show up once? That's what ID selectors are for."
Because ID selectors screw up the cascade. Consider the following (un-semantic) code to illustrate this statement.
<style type="text/css">
#header a { /*Selector Weight: 101*/
font-weight: normal;
}
.bold { /*Selector Weight: 10*/
font-weight: bold;
}
</style>
<div id="header">
Happily not bold.
Sadly, not so bold.
</div>
SO bold...
To make this work, you'd have to add:
#header .bold { /*Selector Weight: 110*/
font-weight: bold;
}
Great, now we have two bold classes. You can see how quickly this can ruin you. Imagine trying to deal with this on a full featured web application.
No hard and fast rules on this one, it's as much about:
why you're using the style
what you're doing
where you're going
more than the number of elements that are involved.
If a style only refers to one, unique element, an ID based selector is the most appropriate.
If a style may refer to multiple elements, use a class.
The other thing to keep in mind is ID based selectors have higher priority than class based ones. This helps if any of your unique, ID'd elements inherit styles from more generic, classed based rules.
I prefer to use the ids for the most important elements that are repeated in the page, such as the Stackoverflow logo (and all the header) on this page.
Use a CSS class when the elements are not page-specific and can be repeated among different pages, or many times in the same page.

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