Scoped Style Sheets without HTML5 - css

I am needing an approach where I can scope CSS files to a certain portion of the page. In theory, this example should do what I need:
<html>
<head>
</head>
<body>
<div>
<style scope>
#import url("style1.css");
</style>
<div class="testText">Test with Style 1</div>
</div>
<div>
<style scope>
#import url("style2.css");
</style>
<div class="testText">Test with Style 2</div>
</div>
</body>
</html>
However, I found out that the scope element is only available in some browsers right now (Firefox 21+ mainly). So, I'm looking for a lazy way out or a problem. I need to integrate some content with different styles into a site. We tried loading both css filesets, but there are some style names that appear in both stylesheets, so it will be a lot of work to rename the style names in one fileset and in the corresponding html content, specially because you cannot just refactor with Eclipse... :)
Is there any other solution that can render such a result that is widely compatible?
Regards

Scoped styles aren't well-supported at this point and are going to cause you problems if you're expecting any sort of cross-browser coverage.
The only way you can really achieve what you're after is to use a unique classname (or ID) for each 'section' and then use inheritance to sort-of namespace your CSS. So if you want to target one specific section of the page, give it's parents a classname (eg: class="testone") and then make sure that any styles you want to apply to that section are appended with that classname:
.testone .title{...}
.testone h1{...}
.testone a{...
etc.
Failing that, there is also a jQuery-based scope polyfill which should give you a more browser-independent way of working with scoped CSS. It isn't something I've worked with so don't have any experience to offer, but it looks very promising from the few moments I've spent with it!
Do remember that as with any JavaScript-based solution like this one, anyone who loads your page without JavaScript enabled isn't going to get those little extra niceties so it's important to ensure that the page still behaves in an acceptable manner even when JS is disabled.

The attribute name in HTML5 drafts is scoped, not scope.
Support to it is slowly being implemented, but there is little reason to use the attribute, or scoped style sheets. Most browsers will take <style scoped> simply as <style> and apply it to the entire document.
Thus, it is best to analyze the problem you are trying to solve and find a different approach to it. In many cases, it is trivial, using suitable contextual selectors. Assign an id attribute to an element and use an id selector as the first component of selectors.

Related

Blazor ignoring scoped CSS in Components

I have a similar problem as mentioned here.
The component MyComponent.razor has the scoped CSS MyComponent.razor.css.
Anyways, the style of the CSS file SOMETIMES is ignored. If I change the CSS it might work on the first start, or it might happen that I have to build the project 10 times before it works. If I move the Component (including the scoped CSS) from one folder to another and move it back, it is more likely to work as well.
It is also not a caching issue. When I hard refresh the browser and clear the cache, the CSS is still not loaded. In the dev tools, I am also not able to find the specific changes in the bundled CSS. E.g., if in the CSS I simply change the background-color of a class from blue to red, the background-color is still blue in the bundled CSS.
Within my _Host.cshtml the bundled style is added.
<head>
...
<link href="<applicationName>.Client.styles.css" rel="stylesheet" />
</head>
Project.Client.csproj does not contain a
<RazorLangVersion>3.0</RazorLangVersion>
The issue was relatively hard to find, but I found the solution. The problems I faced were caused by the components themselves. Basically, my Pages/Components look something like this:
<MyComponentA></MyComponentA>
<div>
<MyComponentB></MyComponentB>
<MyComponentC class="customCssClass">
<MyComponentD></MyComponentD>
</MyComponentC>
</div>
To make styling work, I need to pass down the style with the ::deep CSS-Keyword. Otherwise, the style is not passed down to the component. This means, my CSS looks something like this:
::deep .customCssClass {
}
Keep in mind, that ::deep needs to be added to every CSS class, otherwise, it doesn't work (at least it didn't for me).
Another issue is that I found that under certain circumstances it still didn't work for some components. I honestly have no idea which part of my code breaks it, but the fix was to wrap the entire Page/Component into a div. My code from above would look something like this then:
<div>
<MyComponentA></MyComponentA>
<div>
<MyComponentB></MyComponentB>
<MyComponentC class="customCssClass">
<MyComponentD></MyComponentD>
</MyComponentC>
</div>
</div>
TLDR: Add ::deep to every CSS element and wrap the page/component into a div.

How to apply only one css file out of two css files included?

I am currently using Twitter Bootstrap in developing an web app. Now I also need to use jqgrid for the same app. So, I have a couple of CSS included for a page.
<link href="../css/bootstrap.min.css" rel="stylesheet">
<link href="../css/flick/jquery-ui-1.8.19.custom.css" rel="stylesheet">
<link href="../css/ui.jqgrid.css" rel="stylesheet">
However, the grid table generated by jqgrid on the page looks a bit odd since you find Twitter-ish cells in the jgrid table.
So I am wondering if there are any ways to disable one CSS out of several CSS files that I include for a certain element of the page? This time, I want to disable bootstrap css for div tag with id=grid where the grid will show up.
Pretty vague, but here's your solution: use the dev tools in your browser of choice, but i'm going to explain using Chrome:
hover over the affected jqgrid table and click inspect element. dev tools will open up and you should see all the styles being declared on that element, from the separate stylesheets.
if you see any styles crossed out (being overridden) that come from jqgrid, you need to out specify them in your jqgrid style sheet, for example, by adding a class, id, parent selectors or chaining.
also, if there are styles bootstrap is declaring that jqgrid doesn't address (these you're going to have to sift through manually), the same solution applies: add these styles to jqgrid, while specifying the styles you desire and adding specificity to your declarations so they override bootstrap.
If you posted a link, i could show you, which i think would be much easier then this explanation. but this will achieve the style(s) you desire.
You can't disable a stylesheet reference, but you can change the selectors in it to be more descriptive. e.g. if both of these stylesheets just style div, you'll of course get conflicts. However, if you modify bootstrap's selectors to be #twitter div, you'll get much more precise results.

CSS Files and Unwanted Overriding

I have a simple HTML page that is referencing 3 CSS files. The first is a style sheet that is just for the page. The other two are for the styles of two unique modals. These modal CSS files were not created by me and they are happily being used separately on other pages throughout the site.
My problem is that both of these modal CSS files contain a few common selectors and so they are messing up each other's styles.
I understand that the best way to fix this problem is to take one or both of the files and make their selectors unique. One way would be to namespace the selectors.
My questions is, however, now that I'm knee-deep in this page, is there anyway to prevent these CSS conflicts without changing the modal CSS pages as they currently stand? Are there any tools that can help such as LESS? What is the best practice for preventing this in the future?
The best solution indeed would be to refactor those css-files to your need.
However, an easier solution would be to include your stylesheet after those two third-party css-files and re-declare the styles for the common selectors, which automatically overrides the previous settings.
LESS/SASS are excellent tools to help you write CSS faster and more comfortable. I use SASS for private work and really recommend it. They can't help you though with issues like you have atm.
EDIT:
Using !important is possible, but considered bad habit, as it was intended to give the user the possibility to override author-styles with his own. Instead of using !important what you should do is:
Avoid duplicate styles as much as you can.
if you can't avoid this, try to resolve this by either:
cascading (=using the proper sequence to override previous styles)
using selector specificity (W3C-Spec).
Assuming:
...
<link rel="stylesheet" href="this_page.css" />
<link rel="stylesheet" href="modal_1.css" />
<link rel="stylesheet" href="modal_2.css" />
...
Due to the cascading nature of CSS (sorry, I had to) using the same selector over and over overrides any previous styles. Thus, if modal_1.css and modal_2.css both apply style x to the body tag, for example, the second stylesheet will override the first.
The sad part is that there is no way out other than to, as you suggested, modify the two selectors to make them more specific.
Looking to the future, the best way to avoid overriding previously declared styles, is to always be specific about the particular element you are targeting, and it's proper place in the DOM. Note that LESS is simply a CSS preprocessor, which only allows you a different syntax for CSS.
I would suggest to a common class add into body tag of that particular page & target using that particular class. If you tools like LESS or Compass you can easily achieve the aim.
.pageOne{ /*All the styles for this perticular page*/
.header{
}
.sidebar{
}
}
When parse through LESS or Compass it will look like following.
.pageOne .header{}
.pageOne .sidebar{}
This way your page will get a namespace.

What's so bad about in-line CSS?

When I see website starter code and examples, the CSS is always in a separate file, named something like "main.css", "default.css", or "Site.css". However, when I'm coding up a page, I'm often tempted to throw the CSS in-line with a DOM element, such as by setting "float: right" on an image. I get the feeling that this is "bad coding", since it's so rarely done in examples.
I understand that if the style will be applied to multiple objects, it's wise to follow "Don't Repeat Yourself" (DRY) and assign it to a CSS class to be referenced by each element. However, if I won't be repeating the CSS on another element, why not in-line the CSS as I write the HTML?
The question: Is using in-line CSS considered bad, even if it will only be used on that element? If so, why?
Example (is this bad?):
<img src="myimage.gif" style="float:right" />
Having to change 100 lines of code when you want to make the site look different. That may not apply in your example, but if you're using inline css for things like
<div style ="font-size:larger; text-align:center; font-weight:bold">
on each page to denote a page header, it would be a lot easier to maintain as
<div class="pageheader">
if the pageheader is defined in a single stylesheet so that if you want to change how a page header looks across the entire site, you change the css in one place.
However, I'll be a heretic and say that in your example, I see no problem. You're targeting the behavior of a single image, which probably has to look right on a single page, so putting the actual css in a stylesheet would probably be overkill.
The advantage for having a different css file are
Easy to maintain your html page
Change to the Look and feel will be easy and you can have support for many themes on your pages.
Your css file will be cached on the browser side. So you will contribute a little on internet traffic by not loading some kbs of data every time a the page is refreshed or user navigates your site.
The html5 approach to fast css prototyping
or: <style> tags are no longer just for the head any more!
Hacking CSS
Let's say you're debugging, and want to modify your page-css, make a certain section only look better. Instead of creating your styles inline the quick and dirty and un-maintainable way, you can do what I do these days and take a staged approach.
No inline style attribute
Never create your css inline, by which I mean: <element style='color:red'> or even <img style='float:right'> It's very convenient, but doesn't reflect actual selector specificity in a real css file later, and if you keep it, you'll regret the maintenance load later.
Prototype with <style> instead
Where you would have used inline css, instead use in-page <style> elements. Try that out! It works fine in all browsers, so is great for testing, yet allows you to gracefully move such css out to your global css files whenever you want/need to! ( *just be aware that the selectors will only have page-level specificity, instead of site-level specificity, so be wary of being too general) Just as clean as in your css files:
<style>
.avatar-image{
float:right
}
.faq .warning{
color:crimson;
}
p{
border-left:thin medium blue;
// this general of a selector would be very bad, though.
// so be aware of what'll happen to general selectors if they go
// global
}
</style>
Refactoring other people's inline css
Sometimes you're not even the problem, and you're dealing with someone else's inline css, and you have to refactor it. This is another great use for the <style> in page, so that you can directly strip the inline css and immediate place it right on the page in classes or ids or selectors while you're refactoring. If you are careful enough with your selectors as you go, you can then move the final result to the global css file at the end with just a copy & paste.
It's a little hard to transfer every bit of css immediately to the global css file, but with in-page <style> elements, we now have alternatives.
In addition to other answers.... Internationalization.
Depending of the language of the content - you often need to adapt the styling of an element.
One obvious example would be right-to-left languages.
Let's say you used your code:
<img src="myimage.gif" style="float:right" />
Now say you want your website to support rtl languages - you would need:
<img src="myimage.gif" style="float:left" />
So now, if you want to support both languages, there's no way to assign a value to float using inline styling.
With CSS this is easily taken care of with the lang attribute
So you could do something like this:
img {
float:right;
}
html[lang="he"] img { /* Hebrew. or.. lang="ar" for Arabic etc */
float:left;
}
Demo
Inline CSS will always, always win in precedence over any linked-stylesheet CSS. This can cause enormous headache for you if and when you go and write a proper cascading stylesheet, and your properties aren't applying correctly.
It also hurts your application semantically: CSS is about separating presentation from markup. When you tangle the two together, things get much more difficult to understand and maintain. It's a similar principle as separating database code from your controller code on the server side of things.
Finally, imagine that you have 20 of those image tags. What happens when you decide that they should be floated left?
This only applies to handwritten code. If you generate code, I think that it's okay to use inline styles here and then, especially in cases where elements and controls need special treatment.
DRY is a good concept for handwritten code, but in machine-generated code, I opt for "Law of Demeter": "What belongs together, must stay together". It's easier to manipulate code that generates Style tags than to edit a global style a second time in a different and "remote" CSS file.
The answer to your question: it depends...
Using inline CSS is much harder to maintain.
For every property you want to change, using inline CSS requires you to look for the corresponding HTML code, instead of just looking inside clearly-defined and hopefully well-structured CSS files.
The whole point of CSS is to separate content from its presentation. So in your example you are mixing content with presentation and this may be "considered harmful".
In addition to the other answers, another concern is that it violates the recommended Content Security Policy from MDN, https://infosec.mozilla.org/guidelines/web_security#content-security-policy
The justification they use is that inline javascript is harmful, XSS, etc., but it doesn't justify why inline styles should also be disabled. Maybe someone can comment as to why, but until then, I'll just rely on appeal-to-authority and claim: it's a security best practice to avoid inline styles.
Code how you like to code, but if you are passing it on to someone else it is best to use what everyone else does. There are reasons for CSS, then there are reasons for inline. I use both, because it is just easier for me. Using CSS is wonderful when you have a lot of the same repetition. However, when you have a bunch of different elements with different properties then that becomes a problem. One instance for me is when I am positioning elements on a page. Each element as a different top and left property. If I put that all in a CSS that would really annoy the mess out of me going between the html and css page. So CSS is great when you want everything to have the same font, color, hover effect, etc. But when everything has a different position adding a CSS instance for each element can really be a pain. That is just my opinion though. CSS really has great relevance in larger applications when your having to dig through code. Use Mozilla web developer plugin and it will help you find the elements IDs and Classes.
I think that even if you want to have a certain style for one element, you have to consider the possibility that you may want to apply the same style on the same element on different pages.
One day somebody may ask to change or add more stylistic changes to the same element on every page. If you had the styles defined in an external CSS file, you would only have to make changes there, and it would be reflected in the same element in all of the pages, thus saving you a headache. :-)
Even if you only use the style once as in this example you've still mixed CONTENT and DESIGN. Lookup "Separation of concerns".
Using inline styles violates the Separation of Concerns principle, as you are effectively mixing markup and style in the same source file. It also, in most cases, violates the DRY (Don't Repeat Yourself) principle since they are only applicable to a single element, whereas a class can be applied to several of them (and even be extended through the magic of CSS rules!).
Furthermore, judicious use of classes is beneficial if your site contains scripting. For example, several popular JavaScript libs such as JQuery depend heavily on classes as selectors.
Finally, using classes adds additional clarity to your DOM, since you effectively have descriptors telling you what kind of element a given node in it is. For example:
<div class="header-row">It's a row!</div>
Is a lot more expressive than:
<div style="height: 80px; width: 100%;">It's...something?</div>
Inline CSS is good for machine-generated code, and can be fine when most visitors only browse one page on a site, but one thing it can't do is handle media queries to allow different looks for screens of different sizes. For that, you need to include the CSS either in an external style sheet or in an internal style tag.
In-page css is the in-thing at the moment because Google rates it as giving a better user experience than css loaded from a separate file. A possible solution is to put the css in a text file, load it on the fly with php, and output it into the document head. In the <head> section include this:
<head> ...
<?php
$codestring = file_get_contents("styles/style1.txt");
echo "<style>" . $codestring . "</style>";
?>
... </head>
Put the required css in styles/style1.txt and it'll get spat out in the <head> section of your document. This way, you'll have in-page css with the benefit of using a style template, style1.txt, which can be shared by any and all pages, allowing site-wide style changes to be made via only that one file. Furthermore, this method doesn't require the browser to request separate css files from the server (thus minimising retrieval / rendering time), since everything is delivered at once by php.
Having implemented this, individual one-time-only styles can be manually coded where needed.
According to the AMP HTML Specification it is necessary to put CSS in your HTML file (vs an external stylesheet) for performance purposes. This does not mean inline CSS but they do specify no external stylesheets.
An incomplete list of optimizations such a serving system might do is:
Replace image references with images sized to the viewer’s viewport.
Inline images that are visible above the fold.
Inline CSS variables.
Preload extended components.
Minify HTML and CSS.
Personally, I think the hatred of inline css is just ridiculous. Hardcore cult behaviour, people just sheepishly repeat "Separation of concerns!". Yes, there are times where if there is a repeating element and you will need repeated styling to use a class targeted from a CSS file, but most of the time it improves speed of development and CLARITY OF CODE to put the style inline, it's great if I can look at the code and see that there is a custom margin height, it helps me picture the HTML document as a whole, instead of some named class that gives me little insight into which styles will be applied.
So I will be the contrarian here and say that inline css is great and that people who scream at you for using it are just following what they have been told without actually giving it any original unbiased consideration.
Even though I totally agree with all the answers given above that writing CSS in a separate file is always better from code reusability, maintainability, better separation of concerns there are many scenarios where people prefer inline CSS in their production code -
The external CSS file causes one extra HTTP call to browser and thus additional latency. Instead if the CSS is inserted inline then browser can start parsing it right away. Especially over SSL HTTP calls are more costly and adds up additional latency to the page. There are many tools available that helps to generate static HTML pages (or page snippet) by inserting external CSS files as inline code. These tools are used at the Build and Release phase where the production binary is generated. This way we get all the advantages of external CSS and also the page becomes faster.
In addition to other answers, you cant target the pseudo-classes or pseudo-elements in inline CSS
We have created a template-driven artifact generator that provides an include file capability for any kind of text artifact -- HTML, XML, computer languages, unstructured text, DSV, etc. (E.g., it's great for handling common Web or manual page headers and footers without scripting.)
Once you have that and use it to provide "style" tags inside your "head" tag, the "separation of concerns" argument goes away, to be replaced by "we have to regenerate after every change to the template" and "we have to debug the template from what it generates". Those gripes have been around since the first computer language to get a preprocessor (or someone started using M4).
On balance, we think the meta-izing capability of either a CSS file or "style" tags is cleaner and less error-prone than element-level styling. But it does require some professional judgment, so newbies and scatterbrains don't bother.

Multiple classes in body tag, multi-dimensional css structure or blueprint for insanity?

This question is about an approach to css structuring, and so is more discussion oriented.
I'm working with some outsourced css where the body tags have multiple classes assigned, up to half a dozen. (To make things a little worse, none of the css selectors include an html tag which is making it confusing to analyze the css.) These body classes are then used to modify classed or id'd widgets within.
It seems like this approach is like adding an additional dimension to the css, perhaps in some attempt to create a structured css approach. Documentation might have helped, had we been provided any.
This differs from my approach where widgets are styled primarily via id'd divs, perhaps extracting the more generic elements into a class, i.e. div#MyWidget.widgets.
Any ideas on whether such an approach is maintainable, especially considering I am dealing with websites with thousands of pages including tons of legacy stuff, all done by different people with different skill levels? Thanks...
I find nothing particularly wrong with this approach, provided you are conceptually using the body tags to apply very general style rules. The higher up the class is in the DOM, the more generic it should be.
It's hard to answer specifically without examples. One I frequently use is to turn the URL segments into classes for body tag in my pages, for relatively small sites:
// mysite.com/users/show/
<body class="users show">
<div id="Content">
...
</div>
</body>
I use this almost exclusively for overriding default styles on very specific pages:
#Content {
width:500px;
}
.users.show #Content {
width:600px;
}

Resources