Can I shorten my CSS? - css

Here is my original CSS to apply different colour backgrounds:
.one-colour {
background-color:#153a63;
}
.two-colour {
background-color:#f16c24;
}
.three-colour {
background-color:#337db9;
}
I know you can do multiple CSS classes such as .one.two.three {...}
But is my CSS condensed down as much as possible? and I don't mean just putting the code onto one line to make it "shorter".

But is my CSS condensed down as much as possible?
Yes(ish)
Each CSS rule is setting the same property style to a different value. As such, you have condensed the ruleset to the minimum number of rules to allow this level of distinction. If anything, you could simply change background-color to just background- if background properties aren't set in other rules which this could override.
*Although my predisposition is that this should be a comment, I guess in essence it is effectively an answer to your question.
Additional Methods Update:
As mentioned in the comments, there are some other (overkill?) methods for condensing:
Put everything in a single line, remove whitespace (minify)
Shorten your class names, e.g (.one-colour -> .c1), as noted below this is a subjective, context sensitive decision
The last style setting in a CSS rule does not require a trailing semi-colon in order for the rule to process, so you can also remove these
Convert your HEX colors to their 3 digit counterparts (approx), #036, #F63 and #36C

Depending on how you use these classes, there might be a way to remove one of those classes.
If you use those classes in a particular container - you could apply one of the colors to the container and then override it only on 2 of the inner divs.
Again, it depends on how you use the classes.

Yes, I would say so. If you wanted to start doing things to all the classes at once (like add a black border to them all) then you could combine that onto one line, as you suggested. Otherwise, it looks as compact as it's going to get at the moment. I can't suggest an improvement.

Related

What is sharedAttr in CSS?

everybody!
Reading this topic:
Change background color of HTML <area> tag
I saw the part of a CSS code:
area{
sharedAttr: 'attribute';
}
I wonder what is this sharedAttr. What is amazing Google search:
css sharedAttr
gives only 8 (eight!) results. I can not find any documentation mentioning anything about usage of sharedAttr in css sheet. Can anybody shed some light on the topic?
Thank you in advance!
The example you referenced is alluding (albeit rather poorly) to the fact that you can define one or more CSS properties using a fairly generic selector and then use a more restrictive selector to define specific additions/overrides.
area{
/* matches all instances of the area element, so properties
that should be applied to all area elements go here */
}
#one {
/* properties which should only be applied to the element
with the ID "one" go here */
}
In context of the original question, such a technique is commonly used to reduce the number of styles that must be declared. If 100 area tags all need the same background color, it would be silly to define a selector for each one. However, additional selectors can be defined to override that color and/or define additional properties on certain elements.

How do I override widths in 960.css?

I have a 24 column page that is based on the 24 column 960 template. I have an element that needs a specific with of 84px.
I tried to write the markup this way:
<div class="container_24 grid_84">
</div>
I tried writting the css this way:
.container_24 .grid_84 {
width:84px !important;
}
It is not setting to 84px it is setting to 960px.
What is the proper of displaying this.
Your CSS has this:
.container_24 .grid_84
That is looking for an element with a class of grid_84 that is a CHILD of container_24.
But you are actually looking for this in your HTML:
.container_24.grid_84
That is an element with both classes, which is what your HTML shows.
Side advice:
Don't mix grid framework syntax with your own. 24 refers to column. Your 84 refers to specific pixels.
I'd suggest using something along the lines of
.override_84px
So it's clearly not part of the grid framework. Future people that have to look at your markup will thank you.
Also, since you are making your element here, why even use the container_24 class in the first place?
Finally, the !important declaration is usually a method of last resort to over-ride some existing CSS you have no control over of. You typcially do not want to be using that attribute with your own CSS as it's usually a sign that things have gotten a bit messy.
.container_24 .grid_84 { width:84px !important; }
syntax is correct but are you sure you are looking at the right cell? I have not exactly understood your question though.
Also consider using an ID for container_24, if there is going to be only one such container in the page. Make sure you are not setting width of a span element, which does not take width unless you change its display property to block
{display:block}
The latter css statement is always used, I know you can set this with the !important tag, however, I am not sure if this only applies to the other statements within the same file. I would suggest using the order:
reset.css
960.css
text.css
style.css

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.

Is there any pros and cons if i use always CSS Class instead CSS ID for everything?

In CSS we can use both ID and class. is there any pros and cons if i use Class always instead ID in terms of Semantic, Web standards- W3C , SEO , Accessibility and future maintainability?
One big difference: in CSS, a class has a lower importance level than an ID.
Imagine that each specification in a CSS declaration added a certain number of points to that declaration's value. Let's say the points go something like this (totally made up, but whatever):
Tag name ('a', 'div', 'span'): 1 point
Class name ('.highlight', '.error', '.animal'): 10 points
ID ('#main-headline', '#nav', '#content'): 100 points
So, the following declarations:
a {
color: #00f;
}
.highlight a {
color: #0f0;
}
#nav .highlight a {
color: #f00;
}
are worth 1, 11, and 111 points (respectively). For a given tag, the declaration with the highest number of points that matches it "wins". So for example, with those declarations, all a tags will be blue, unless they're inside an element with the "highlight" class, in which case they'll be green, unless that element is inside the element with id="nav", in which case they'll be red.
Now, you can get yourself into tricky situations if you're only using classes. Let's say you want to make all the links in your content area blue, but all the links in your foo area red:
.content a {
color: #00f;
}
.foo a {
color: #f00;
}
By my previous (made up) scale, those both have 11 points. If you have a foo within your content, which one wins? In this situation, foo wins because it comes after. Now, maybe that's what you want, but that's just lucky. If you change your mind later, and want content to win, you have to change their order, and depending on the order of declarations in a CSS file is A Bad Idea. Now if, instead, you had the following declaration:
#content a {
color: #00f;
}
.foo a {
color: #f00;
}
Content would always win, because that declaration has a value of 101 (beating foo's 11). No matter what order they come in, the content declaration will always beat the foo one. This provides you with some very important consistency. The winners won't arbitrarily change based on changing orders in the file, and if you want to change the the winner, you have to change the declarations (maybe add a #content in front of the .foo declaration, so it will have 111 points).
So basically, the differences in values are important, and you get a lot of inconsistency and seemingly arbitrary winners if you just use classes.
I know i'm not the 'norm' here and i'll get thumbed down for this... but i use classes exclusively and only ever use ID's for scripting :)
This creates a clear line of seperation of designer and coder related tweaks and changes, which is very handy for us!.
Also we have some .NET web form coders (even though we are moving all sites to MVC) and as .NET controls take over ID's to script them dynamically using ID's for CSS is a pain... i'm not a fan of using #ct00_ct02_MyControlName in css files and even if i was changes to code can break the CSS! Classes works GREAT for this.
Some PHP libs others in the company are using also need to use dynamic ID assignment, this creates the problem here too. again Classes work GREAT here.
As more and more of these dynamic outputs and languages use up the ID's (for exactly what they are really intended for... identifiing an element to work with it) it can be more and more of a pain to work with IDs in CSS.
It's seems to me that everyone wants to use them simply cause they think they should, becuase they are 'there', i offer the idea that ID's are not there at all for CSS and their use in CSS is just there as an extra helper via the selector and their real use is scripting.
There has not been a single instance where i needed an ID for css use or even a single instance where it would have been eaiser.
But perhaps i'm just used to it and thats why? My HTML output is small, my CSS files small and direct. Nested elements work in all browsers as i expect, i dont have issues and can create complicated nicely rendered pages. Changes take mere minutes as i can apply multiple classes to an element or make a new one.
ID's for scripting, CLASS for css... works a treat.
Obivously there is no major issue (Even in a team of designers and coders) in using them both for css as we all get used to what we get used to :) but the way we work it outputs the expected results fast, and noone can step on anyones toes even in anonomous sharing enviroments.
My biggest one would be from the future maintenance point of view. Not only is it nice to know that a style is only used for one element on a page, but if you ever start integrated javascript into your page its nice to be able to access elements quickly using their IDs rather than try and access them by their class's.
If you're using a decent javascript library (like prototype or jQuery) then no, I can't think of any technical reasons why this would matter. However, it might help your own internal thinking and consistency to think separately about whether it is an attribute-like collective characteristic (=> class) or a specific item (=> ID).
Use id when an element is unique on a page and you always expect it to be. Use class when multiple elements will be assigned the value of the attribute. It's true that it may not make a big difference from a purely CSS perspective, but from the JavaScript or Selenium perspective, it's a big deal to be able to uniquely identify elements by their id attribute.
In simple we can define id and class as below
ID = A person's Identification (ID) is unique to one person.
Class = There are many people in a class.
Use IDs when there is only one occurence per page. Use classes when there are one or more occurences per page.There is no hard rule on when to use ID and when to use Class. My suggestion is to use class as much as possible for maximum flexibility, with the only exception being when you want to use Javascript's getElementByID function, in which case you need use ID.
IDs are good for elements that need to be accessed from JavaScript. But the IDs must be unique in the page according to w3 standards, that is:
you cannot have two <div id="Header"> in one document
you cannot have a <div id="Header"> and <p id="Header"> in one document
Class names are good for elements that do not need to be accessed from JavaScript (although it is possible to do so). One class name can be used for multiple elements, and one element can have more than one class names attached to it. Class names therefore allow you to create more "generic" css definitions, for example:
<div class="column">
<div class="column left-column">
<div class="column right-column"> -- all three can be in the same document
You can mix IDs and classes together.
To summarize: use IDs for specific cases; class names for generic cases; and cascad classes for elements that share some general properties but not all.
See following:
CSS Best Practice about ID and Class?
For SEO: It will make absolutely no difference to seo at all.
You should choose names that reflect the semantic content of that section. eg: id="leftMenu" class="footerNotes"
Don't use any underscores in your class and id names (common mistake).
The only difference between classes and ids, except for the fact that an id MUST be unique and a class does not, is that the browser can use an element's id for navigational purposes. For example, this page has a logo with id="hlogo". If you append to this page's url the hash #hlogo, like this https://stackoverflow.com/questions/1878810/is-there-any-pros-and-cons-if-i-use-always-css-class-instead-css-id-for-everythi#hlogo, the browser will automatically scroll to the logo.

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.

Resources