Apply style sheet to only a specific element trait - html

After doing a bit of googling I was unable to come up with an answer, so here's my question. Is there a way to specify a specific element trait, such as an id, inwhich an entire style sheet should be applied?
For example if I have a block of html like this
<html>
<head>
<link rel="stylesheet" type="text/css" href="./style.css">
</head>
<body>
<div id="my_id">
<!-- A bunch of elements here -->
</div>
</body>
</html>
Is there a way to specify that the rules contained in ./style.css should only be applied to matching elements with in #my_id, similar to specifying #my_id before each rule in the style sheet.
I understand specifying #my_id before each rule will achieve this, but am wondering if there is a way to do it without the need to add bloat to the style sheet.
I'm working on a greasemonkey(userscript) script, which creates a 'container' element on a specific page in which it creates and places all other GUI elements required. I don't want my CSS interfering with the CSS on the page(such as accidentally over writing rules that already exist on the page), but don't want to add unnecessary bloat to my style sheet if it can be avoided since all rules are only to be applied to the 'wrapper' element and/or it's children.

To my knowledge this is not possible. As you stated you can prefix the rules with the ID, but this is not what you wanted to do.
I should say however, that you shouldn't have to specify a stylesheet for a single ID, because an ID is supposed to be unique in the context of the page. Furthermore, I find it bad practice to apply the same ID to elements which serve different purposes on different pages, because it can make writing common JavaScript pages quite confusing.

And this is one of the reasons people started to use SASS. In SASS this would be as easy as just nesting all the css classes within the id class like so:
#my_id {
// all styles without editing
// Now all these styles are applied only if they fall
// under the element with id "my_id".
}
EDIT : The other (ugly) option is to use an iframe instead of a div and load your child elements and stylesheet within it so that it is sandboxed as follows.
<html>
<head></head>
<body>
<iframe id="my_id">
<html>
<head>
<link rel="stylesheet" type="text/css" href="./style.css" />
</head>
<body>
<!-- A bunch of elements here -->
</body>
</html>
</iframe>
</body>
</html>
P.S: Don't forget to add the doctype. I have not added it in the example for simplicity.

you can apply style to elements within #my_id using the > selector. example:
#my_id {
/* some style for #my_id */
}
#my_id > p {
/* this will style all p tags within #my_id */
}

Related

CSS in head over adding an id

I am working on responsive website that has 100's of pages. It is implemented using a CMS. The problem is, I need to apply some styling only for homepage.
It is a bit cumbersome to add a class or id in the CMS for one page as it uses templates to render pages.
I've added the css in the head section. The reason why I don't want to add in external file is beause the same id might be used on some other page.
Is adding CSS in head section a bad practice in this case.
<head>
<style>
//my css
</style>
</head>
<body>
</body>
Thanks
It's perfectly fine to have inline CSS. Whether you should use inline CSS or simply set a unique ID for the page depends on the complexity and flexibility of the CMS you're using. Using inline CMS just means that you'll have to update the CSS from each individual page, rather than from a single source for all separate pages.
As for your second point, adding CSS to the head in a <style> tag is not bad practice. In fact, <style> is required to be a child of <head> in order to validate correctly. According to the HTML 5.2 specification, <style> can be a child of any element as long as it it scoped, though at the present date, Firefox is the only browser that can use the scoped attribute.
On top of this, using a <style> tag in the <body> could lead to a flash of unstyled content due to the way in which the page gets loaded. So if you use inline CSS, always do so in the head to both validate correctly, and improve user experience :)
Hope this helps!
In a word yes. For reasons of maintainability. You would be better using the cascading nature of css to target a style specific to a specific page than to have lots of inline styles.
For example, consider:
<body class="my-page">
<h1 id="myId">Title</h1>
<body>
<h1 id="myId">Title</h1>
h1#myId{ font-size:12px; }
body.my-page h1#myId{ font-size:14px; }
the latter style will have precedence. h1#myId would be global, yet on a specific page you can override this style. Is there no way to work out what template is in use, and adjust the body class?
If your CMS uses say PHP...
You could detect if you're in homepage and than call your custom external stylesheet, something like:
<?php
$page = $_SERVER["REQUEST_URI"];
$isHomePage = $page==="/" || $page==="/index.php" || $page==="";
if( $isHomePage ) {
echo '<link href="homepage.css" rel="stylesheet" type="text/css" />';
} else {
echo '<link href="style.css" rel="stylesheet" type="text/css" />';
}
?>
</head>

Where should css go in .html page?

I have a index.html page and a style.css file.
I have a style class called .slider and a style class called .logo. Should I put both .slider and .logo inside the style.css page or should i put .slider in index.html and .logo inside .css?
im asking this because i dont know if I should put styles only related to one page inside a global style.css or should i just put it inline in the page it applies to?
Typically you embed css that is page specific. Here is how I do my css:
Global css (seperate file(s)):
<link type="text/css" rel="stylesheet" href="css/style.css" media="all" />
NOTE: In today's web world we use a ton of plugins/themes and these plugins/themes tend to roll out newer versions so when you override these plugins/themes make sure you create a css file specific to that theme.
For instance,
Bootstrap 3.1
<link href="/css/bootstrap.3.1.css" rel="stylesheet" type="text/css">
Create this for all your bootstrap overrides so you can use the latest version when it comes out.
<link href="/css/bootstrap.overrides.css" rel="stylesheet" type="text/css">
Page specific css(embedded):
<head>
<!-- last element in head //-->
<style type="text/css">
.pageSpecific
{
color: red;
}
</style>
</head>
When I am in development stages or the html element does not require css classification.
Simple style format (inline):
<th style="min-width: 65px;">Column Header</th>
You may have print specific css as well:
<link href="/css/print.css" rel="stylesheet" type="text/css">
and inside this file wrap your css as such:
#media print{
<!-- print specific css here//-->
}
Keep in mind that you may want to use a css classifcation at a later date when at the time it may seem page specific. Always code for reusability!
Finally:
I like to use css minifier when I put my file(s) into production. I do the same with my javascript files using UglyJs. There is also LESS css that you can use but for now I would stick to these simple conventions or something similar.
Styles can go in one of three places.
Inline on the element itself
In the html page
In a separate file
I would suggest either putting it in a <style> tag in the <head> of your html or putting it in a separate file, either will work just as well. Obviously having the styles in a separate file means you could reuse those styles on another page if needed.
Either way, it won't make a difference. Personally, I like to have all of my CSS in one place, but you can do whatever you want. If you do put all of your CSS in one document, use comments to separate it into groups, so everything will be easy to find.
You should NEVER have inline or on-page CSS. It should all go in the stylesheet (of which you should only have one per media-type) - why? Because stylesheets are cached, and the cache is way better to hold it than the HTML-files (which may also be cached, by all means, but with dynamic content, they often load quite more often than CSS).
Second, it's a nightmare to update and change, if not everything is in one file.

How can I override css property?

Let say that I have a global css file, global.css :
.my-class {
background-color:red;
}
And I need a specific css file, specific.css, just for a certain html file. And this html file also has class named my-class. In this time, however, I want to make this html's background color as blue. How can I do that in specific.css file?
There are several ways to do this.
Option #1 is to make sure your specific.css file is included after your global one. this will cause the styles to overwrite.
For example:
<link href="global.css" rel="stylesheet" type="text/css" />
<link href="specific.css" rel="stylesheet" type="text/css" />
Option #2 is to leverage CSS specificity.
See here for more info on that: https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity
Option #3 is to use !important in your style that you want to take precedence.
This isn't highly recommended, but will work if the above two options fail to get you what you need.
If you define the other element's background-color in a CSS file that was loaded AFTER global.css (e.g. load specific.css after global.css in your HTML markup). You can also use the !important tag to overwrite ALL other defined styles, but typically you won't need this. Its called cascading style sheets for a reason.

Why does the <link> ‘title’ attribute cause browsers to ignore my styles?

The following html document (together with the CSS) fails to render the styles in b.css.
<!doctype html>
<html>
<head>
<link rel="stylesheet" media="screen" type="text/css" title="A" href="a.css" />
<link rel="stylesheet" media="screen" type="text/css" title="B" href="b.css" />
</head>
<body>
<div id="A">A</div>
<div id="B">B</div>
</body>
</html>
/* a.css */
div#A { color: blue; }
/* b.css */
div#B { color: red; }
Making the titles the same (e.g. both <link ... title="A"> fixes it, but I don't see the reason, why it should. What is the title doing, here, that makes this wrong?
The HTML spec states that there are three kinds of stylesheets: persistent, preferred, and alternate.
A stylesheet is "persistent" if it is linked with rel="stylesheet" and has no title attribute. All persistent stylesheets are used when rendering.
A stylesheet is "preferred" if it is linked with rel="stylesheet" and has a title attribute; preferred stylesheets with the same title are grouped together, but there should not be more than one group. It seems browsers will choose just one preferred stylesheet to render since there should be only one.
Finally, a stylesheet is "alternate" if it is linked with rel="alternate stylesheet" and has a title. These stylesheets are supposed to allow the user to choose stylesheets, they are grouped together by title and show up in the browser's stylesheet selector if it has one (View >> Page Style in Firefox). Each group (by title) is mutually exclusive.
By putting title attributes on your stylesheets, you're unwittingly making them into preferred stylesheets rather than the expected persistent stylesheet. This is also why they work when they all have the same title.
Following up on Neil Williams' answer:
Authors may specify a number of mutually exclusive style sheets called alternate style sheets.... User agents should allow users to select from alternate style sheets.
(emphasis added)
Also:
To make a style sheet preferred, set the rel attribute to "stylesheet" and name the style sheet with the title attribute.
This is from http://www.w3.org/TR/REC-html40/present/styles.html#h-14.3.1
Read this: http://blogs.telerik.com/dimodimov/posts/08-05-15/title_attributes_in_css_link_tags_prevent_styles_from_being_applied.aspx
I have been aware for some time now
that title attributes in CSS
tags trigger problems and prevent some
CSS styles from being applied on the
web page. Today I invested a couple of
hours in finding out what actually
happens and this is what we've got.
If you have several tags in the
page and one of them has a
title attribute, then the tags
coming after it must either have a
title attribute with the same value or
no title attribute at all, otherwise
the styles in the latter CSS files the
will not be applied on the page.
The issue can be easily reproduced in
various versions of Firefox, Opera and
Safari. The only browser, which does
not exhibit the unexpected behavior is
Internet Explorer.

Placing CSS information on an HTML page

Where are all of the places you can put CSS style information on an HTML page?
I know you can place CSS style info in the head of an HTML page, where else is it valid to put CSS elements?
I would like to place my CSS someplace else on the page due to inheritance, e.g:
<style type="text/css">
...
</style>
You can use
<link rel="stylesheet" type="text/css" href="style.css" />
in the head to link to an external stylesheet.
You can also have inline style attributes, such as
Hello
And you can also set the styles in your scripts, e.g. using jQuery (which can go where ever your script is):
$('textBox').css("font-weight", "bold");
However, it is good practise to try to keep all the style information in one standard spot, i.e. the head of the document - it makes it easier for others to maintain your work for you.
Note that if you really want to override a particular attribute, the best way to do it is to use the !important option, such as
color: red !important;
You can use this with any of the methods listed above, and it will override any later settings that conflict.
You can link external stylesheets in the <head> block. You can use more than one stylesheet, and they are loaded in order (in this example, both screen.css and print.css override some elements of style.css.
<link rel="stylesheet" href="style.css" type="text/css" media="all" />
<link rel="stylesheet" href="screen.css" type="text/css" media="screen" />
<link rel="stylesheet" href="print.css" type="text/css" media="print" />
You can import it from an external stylesheet in the <head> block:
<style>
#import url(style.css)
</style>
Or import it using another method:
<style type="text/css" media="all">
#import "style.css";
</style>
You can put the CSS in the <head> block:
<style type="text/css">
p {font-face:Arial;}
</style>
You can put the CSS inline into the html:
<ul> <li style="list-style:none">Item 1</li></ul>
You can add the CSS to the DOM via javascript:
function addCss(cssCode) {
var styleElement = document.createElement("style");
styleElement.type = "text/css";
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = cssCode;
} else {
styleElement.appendChild(document.createTextNode(cssCode));
}
document.getElementsByTagName("head")[0].appendChild(styleElement);
}
You can specify it "inline"
<div style="border: 1px solid red" />
Other than that I'm not used to place it anywhere else than separate files / <head>
Off hand:
In other documents. Include CSS files with the LINK element:
<link href="style.css" type="text/css" rel="stylesheet">
Inline with HTML elements:
<h1 style="color: red">Title</h1>
That is usually the only two other places you will put CSS. You can also apply CSS to documents via JavaScript.
As the others have said, non-inline CSS belongs in the head, if you want to write syntactically-correct code. Check the schema if you're not sure.
If you need to generate the CSS during dynamic page creation, you can easily inject it into the DOM, at the bottom of the head, using javascript:
document.getElementsByTags('head')[0].appendChild( -- css here --);
Be forewarned that this will cause your page rendering to slow down and "blink," as the browser must restyle the page when your new CSS is inserted. The same thing will happen if you ignore the schema and place your CSS in the body.
This leads to a poor user experience.
If you're concerned with inheritance in css then you need to remember this general rule. 
Inline styles > everything else. 
Tag > id
Id > class
Then you have combinations of these rules. 
Tag + id (div#main) > id
Parent tag + tag+id > tag+id 
Remember these are just general rules but they should take care of 99% of your situations. Placing styles in your scripts are generally a bad idea because it affects perfoance as others have noted and it adds another place for you to update when you need to change  the styles. 
So, you can specify it inline as an attribute on the element you want to style...
<p style=" font-weight:bold; ">
Or, you could add it in a style block in the page body or header
<style>
p {font-weight:bold;}
</style>
And lastly, you could include it from a linked CSS file by importing...
<style>
#import url(css/bold.css)
</style>
Or by linking it...
<link rel="stylesheet" href="css/bold.css" />
Honestly, linking is, 99.9999% of the time, is the best way to include stylesheets on a page as it neatly separates your CSS from your code, making updates to either much faster.