CSS scope and coding/naming guidelines - html

When you have a big website with lots of different pages, then lots of CSS, then big styles file (want single file to improve page load performace) one problem I see with CSS is that they don’t have scope and one style can interfere with others. One style defined in one place can affect all other styles defined after it. Let me explain my question with an example:
If I have in my CSS file
p a {
style-values-X
}
.whatever a {
style-values-Y
}
First style can inadvertently affect an Html like that
<p>
...
<div class="whatever">
...
<a href="…"> /* this will end with style-values-X + style-values-Y */
...
</div>
...
</p>
What is the way to code to avoid problems without having a CSS file for each Html page, long names for style classes…?
Is there any coding/naming guidelines document to organize/name your CSS classes?

That's why you start out general and get more specific when working with CSS. The cascading part of it becomes easy to take advantage.
CSS specificity : http://www.htmldog.com/guides/cssadvanced/specificity/
Also this awesome link (If you're a star wars fan) : http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html

Related

Separate a piece of code from another

I don't know if this will make sense and excuse me for the bad terminology (just started learning) but what I'm trying to do is keep a piece of code separate from another so its tags don't affect the code I don't want to be affected.
I changed up some code in codepen to make a carousel for a page. I typed up the page code in another project. I tried importing that carousel code into the main page's code, but as some tags from the carousel code are the same as the main page's, it isn't laid out as I want it to be as it's interfering. I would change the tags, but they're "universal" ones such as img or a.
Is there a way of separating that CSS code from the main code? Like assigning it a separate div and applying that div to the container for the carousel in the HTML?
Here's the carousel
and the main code (trying to add the carousel underneath the about sections).
Well it is very simple, the best approach in styling with CSS is to:
Never apply styles to HTML tags directly because this will affect all the pages where your style is included, so it would be better to:
Use classes and ids to style some specific elements in your pages, this way including your css in the page will only affect these specific elements:
#myElementId{
...
...
}
.myElementsClass{
...
...
}
Note:
Use id for a unique element in the page and a class for more than one elements in your page.
Nested CSS classes:
To answer your question about using nested classes, you can't do it with CSS only, you should use SASS or LESS
References:
For further reading you may take a look at :
The answer to Nesting CSS
classes question on Stackoverflow
Nested selectors: the inception rule
This is called CSS conflicts, you better never apply much styling attributes on tags directly, use namespace with your classes, like-
If you want to apply/change predefined attributes classes, then you can define classes like-
// same classes with a parent Css class,
// to show it's effects only for that partcular section
.home .carousel{
// your css goes code here
}
OR
.someOther .carousel{
// your css goes code here
}
// Then few more nested classes
OR, if you gotta define whole of bunch new classes for your project, you can do something like-
.home-carousel{
// your css goes code here
}
Hope solves your query!
In that case, you would need to create assign a class or id to the tag you want customised and in your css, identify that class or id. For example:
<div class="myheader">
<p>hello</p>
</div>
<div id="myfooter">
</div>
<style>
.myheader{
/*ur css for myheader*/
}
.myheader > p {
/*css for <p> tag in myheader class*/
color:blue !important;
}
#myfooter{
/*ur css for myfooter*/
}
p {
color:red;
}
</style>
if you noticed, class in css is identified with a . and ids are identified with a #. Classes and id can be applied to any tag you need.
Should you have overlapping css as shown above, just use an !important to specify which takes precedence.
For more info: w3s Does that answer your question?

Using CSS Namespacing

I am noob in CSS and HTML, So bear with me for this question.
I am integrating a web application with our existing application. They defined some css rules which is conflicting with our application.
My problem is: Is there any good way to separate out the CSS rules to be used each application pages?
I tried to look at CSS namespace, seems to be lot of rework, as I have to prepend each tag element with namespace.
Update:
I am trying to integrate a Meteor based app into another Meteor based application, now I don't want the 2 css two mix.
Apply a class to the body per page/module/application.
This way your current CSS will still work and you can override by prepending your new CSS with the body class.
CSS namespace is the only good option. You can edit all rules very easily using multiediting feature of sublime text.
Depending on the size of your application, a very dirty and quick solution is to append the rules that your need to separate files (and apply appropriately)
e.g.
for main.html, you have main.css
about.html, have about.css
however, this is pretty bad practice as your separating all your requests for essentially the same information...
What you COULD do is use a CSS Preprocessing language within your dev environment, like SASS, SCSS or LESS where you could abstract a lot of the specific pages into modular files like, main.sass, about,sass etc... which would be compiled into just one main.css file.
Another thing to consider, is that CSS is how classes, ids and pseudo selectors all effect the specificity of the rules that can be applied.
i.e.
!important > #id > .class > html_element
Here is a great intro article about CSS Specificity for you~
http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/
I ended up following solution which worked out for me.
For another app which i am integrating, i made its whole body into a container and gave a class to it.
In layout of another app,
<!-- Another application body layout-->
<body>
<div class="another-app-container">
<!-- Here goes whole layout of page -->
<p class='someClass' > ....
<div class='myClass'> </div>
</p>
</div>
</body
In CSS of that app, i applied following CSS rule,
.another-app-container * .someclass{
// CSS rule goes here
}
.another-app-container * .myClass {
// CSS rule goes here
}
Beauty of CSS i got here is, '*' which applied the CSS rules even it has lot of nesting of elements CSS.
So, it segregated the CSS for my own from another application

Nullify css rules

Okay, this is a gross oversimplification, but I have a javascript application to help people develop webpages. It has its interface superimposed over the page that is being developed, and it all works fine, apart from one thing.
If the div class used in the interface is used by the webpage that is being developed, the interface' embedded stylesheet overrides the properties of the webpage!
This happens on jsfiddle, the embedded css is takes precedence over the external css.
JSfIDDLE
external css:
.color {
color: green;
}
Index.html:
<style>
.color {
color: blue;
}
</style>
<div class="color"> Text to be coloured </div>
When run, the text is blue. If someone could make the text turn green, I think it would demonstrate how to overcome the problem.
Obviously, one way to fix this would be to change the interface classes and rules to something like this:
<style>
.color_interface {
color: blue;
}
</style>
<div class="color_interface"> Text to be coloured </div>
And make them unique, but the project has hundreds of css rules, and I'm just wondering if there's a better way, and a safer way (there's still a small chance someone has a rule "color_interface") to do nullify css rules, so they won't contaminate the page.
I'm thinking the only way to do it is probably a 'reset' stylesheet concerning my rules, setting them all back to their defaults. Is there a way to do this dynamically with jquery, maybe?
What you're witnessing is CSS by design. Specifically, specificity.
If your goal is to release some kind of library that can be used publicly and you want to avoid naming conflicts, I think a fair practice is to simply namespace your selectors, e.g., .starkers-color { color: blue; }. That won't necessarily avoid specificity issues, but it should prevent against having your selectors overridden by implementors.
If you inspect the JSFiddle page you'll see that the reason for it not working is that your inline style definition is placed in the body where it has no effect.
The CSS rules you specify is instead placed as an inline style in the head element.
To your problem:
Again, referring to JSFiddle, would it be possible to load the page in development inside an iframe? This would mean you get the separation you require.
This is because the order of the CSS when rendering. Your include is at the top of the page but your style tags are below that, meaning your style tags will alway take precedence over you include at the top. You could try adding an important to you css includes but this is majorly hacky and could create a whole load of new issues.

override definition in css file

I have a css file that defines style for all <p> tags.
like this
p { ......... }
How can I write a <p> in a page where the stylesheet is included that has default styling?
There's no easy way to do this.
There a some common tricks to simulate that behavior though. The best one to use would vary based on how complex the overridden region is, and how often you want to do this.
Method 1 (for simple overrides):
Add an extra class definition in the statement similar to the one where you clear the default styling (such as is discussed at http://www.wordpress.darfuria.com/blog/clear-css-defaults). You might have to arrange the declarations carefully to prevent the 'normal' style from taking precedence.
.override {/*Your default style overrides, color: white;
margin: 0; background:none; etc */}
<p class="override">foo</p>
Method 2 (clunky, but good for complex regions):
Use an iframe to pull the whole region from a separate .html file hosted elsewhere on your site. The content inside iframes respects the CSS of the page inside the frame, and generally ignores the CSS from the surrounding page.
Method 3 (good for one-shot overrides):
Use inline styles, as others have described here.
Edit:
Not Really a Method, But Probably The Most Correct Way
Also probably not what you want to hear
Re-think your how you've arranged your classes.
For example:
If the overridden <p> is special in some way, it probably deserves it's own class that describes what it's purpose is. <p class='override'> doesn't help people who will be looking at your design after you're done, since it doesn't tell them what the overridden text is for or why it's styled that way.
Are the overrides coming in a specific region? If so, them a style definition like div.left_nav p {/*styles*/} might be a better fit.
Lastly, Is your default <p> styling not really default? Maybe a more loosely specified p style might be in order, with additional p.foo and p.bar definitions later on.
This doesn't fix your immediate problem, but it might be worth chewing on before you start your next project.
You can use inline styling to override the default styling.
<p style="background-color: #ffffff">white bg</p>
Inline styles have the highest precedence. The only styles that have higher precedence than inline styles are user styles applied by the readers themselves.
Just to check. For all the talk of "default styles", if you set the style for a type of element in a CSS file, e.g.:-
li {...}
Then you also include a css file that contains a class definition and apply that class to an individual instance of that element type, e.g.:-
<li class="myLiClass">Some Text</li>
From what I understand it is impossible to get the class myLiClass to override any attribute of the style specification "li {...}" for the element by providing that overriding style in a css class.
Therefore I assert that this means:-
"If you specify a style attribute for any html element type (element type, not a class) in a css file, then all pages that use that css file cannot show that element type attribute using any different styling, where that different styling is stated as a css class."
Can anyone confirm this with an absolute yes, or a working example of why this assertion is not true.
You can apply the style for your tag from your stylesheet like this:
CSS
p.first{ color: blue; }
p.second{ color: red; }
HTML
<html>
<body>
<p>This is a normal paragraph.</p>
<p class="first">This is a paragraph that uses the p.first CSS code!</p>
<p class="second">This is a paragraph that uses the p.second CSS code!</p>
</body>
</html>
I would agree that there isn't really a "Default" style for a tag since each browser has significant freedom on how to display it.
I think the easiest answer is to rethink the problem - define a class that you use for all P tags and then if you fail to use the class it will give you the default styling.
<style>
p.all {margin.top:9px;}
</style>
<p>This would be default style</p>
<p class="all">This would have your style</p>
Alternately, if you wrapped all of your stylized content in a div or some other tag, you could nest the styles like this:
<style>
div.foo p{border:1px solid black;}
</style>
<p>normal</p>
<div class="foo">
<p>abnormal</p>
</div>
Hope this helps.
What makes this impossible is that there is no "default style".
Default styles come from the browser's internal style sheet and the user's preferences. So different browsers and different users have different defaults.
You could assume that white/transparent background, black foreground and Arial font were going to be most people's default styles, but you couldn't be sure.
So, like other people are saying, you have a fundamental problem because you've got a style for all P elements, and there's no way to code a P which doesn't inherit from that style, you can only over-ride it using CSS of greater specificity.

Do I have always use .css files?

Are .css files always needed? Or may I have a .css "basic" file and define other style items inside the HTML page?
Does padding, borders and so on always have to be defined in a .css file that is stored separately, or may I embed then into an HTML page?
It is technically possible to use inline CSS formatting exclusively and have no external stylesheet. You can also embed the stylesheet within the HTML document. The best practice in web design is to separate out the CSS into a separate stylesheet. The reason for this is that the CSS stylesheet exists for the purpose of defining the presentation style of the document. The HTML file exists to define the structure and content of the document. And perhaps you may have JavaScript files which exist to add additional behavior to the document.
Keeping the presentation, markup, and behavior separate creates a cleaner design.
From a practical perspective, if you have a single external CSS stylesheet the browser can cache it. If multiple pages on your site have the same look and feel, they can use the same external stylesheet which only needs to be downloaded once by the web browser. This will make your network bandwidth bills lower as well as creating a faster end user experience.
You can include CSS inside an HTML page. It goes within the <style> tag, which goes within the <head> tag:
<head>
<style type="text/css">
body{ background-color: blue; }
</style>
</head>
Note, however, that it is best practice to use .css files.
Putting rules into the HTML page gives them greater "specificity," and therefore priority, over external rules. If several CSS rules conflict, ID wins over class, and inline styles win over ID.
<head>
<style type="text/css">
span.reminder {color: blue;}
span#themostimportant {color: red;}
</style>
</head>
<body>
<span class="reminder" id="themostimportant">
This text will be red.
</span>
<span class="reminder" id="themostimportant" style="color: green;">
This text will be green.
</span>
</body>
You can define CSS at three levels, externally, embedded in the document (inside a <style> tag), or inline on the element.
Depending on your needs, you might use all three, as a rule of thumb external sheets are good for overall styles as you can apply them globally. If you have specific cases that you must handle you can then use the other levels.
You can do either. However, by shifting your CSS out to a separate file, it can be cached. This reduces the amount of data that you need to transmit for each page, cutting down on bandwidth costs, and increasing speed.
You don't have to keep your CSS in an external file, no. What you're asking about is "inline" css: including style directives directly within the page itself via <style> blocks.
There are times where that may makes sense, in moderation, but in general it's not the way you want to go. Keep your CSS isolated in an external stylesheet makes it much easier to maintain both your HTML and your styling, especially as a project scales and changes hands.
One big advantage of having CSS in an external file is that one rule can apply to many different pages. Here is a contrast of three CSS approaches:
Inline Styles - to change the color to blue, you have to find each place that the red style exists - maybe on many pages.
<span style="color: red;">This is a warning.</span>
Page Styles - this allows you to label what something is - in this case, a warning - rather than what it looks like. You could change all the "warnings" on the page to instead have a yellow background by changing one line of code at the top of the page.
<head>
<style type="text/css">
.warning {color: red;}
</style>
<body>
<span class="warning">This is a warning.</span*>
External File - same code as above, but the fact that the style info is in a separate file means that you can use the "warning" class on many pages.
You can use anywhere, css files are not a requirement. using css files however is recommended as it makes the site easier to maintain and change in the future
Have to? No. You can do it however you prefer.
Generally it's better stype to keep your CSS out of your html whenever possible though.
That's what i usually do.
At least at the begining. When a page design gets close to final, I move most things to the 'main' style.css
I prefer to keep styling in CSS as it separates view from presentation, allowing me to swap between presentations fairly easily. Plus it keeps all the information in one place instead of split between two places.
Css can improve performance, because they are cached from browser, and pages are smaller!
Use an external file for all styles that are used sitewide, document stylesheet for styles that are only used on that page and use inline styles when the style only affects that single element.
External stylesheets do not always lower bandwidth. If you put every style for every page in your site into one giant css file, your users incur a large initial download even if they only visit your homepage once ever.
Thoughtful division of your styles into a main.css with the most common styles and then into additional stylesheets as users drill down deeper can help to make the downloads smaller for some paths through the site.