Related
This is impossible to Google for because every article talking about the :before and :after pseudo-elements seems to use the word 'content'.
I heard about it in this CSS-Tricks article, explaining how to implement an image slider as an example use-case for web components. The code example it appears inside is thus:
CSS
#slides ::content img {
width: 25%;
float: left;
}
HTML
<template>
...
<div class="inner">
<content select="img"></content>
</div>
</template>
It seems to be referring to this <content> tag, which is used to allow the user to include Web Components, but I would love to understand this more deeply.
EDIT:
After reading further, in the aforementioned article, I discovered a link the author's "Shadow DOM CSS Cheatsheet" which includes a passage that explains what the ::content pseudo-element is:
Selects distributed nodes inside of an element. Needs to be paired
with polyfill-next-selector for browsers that do not support the
native selector.
::content h1 {
color: red;
}
Source: http://robdodson.me/blog/2014/04/10/shadow-dom-css-cheat-sheet/
This is helpful, but I still find the whole affair rather opaque. Any additional insights?
The ::content pseudo-element is being replaced in future implementations of Web Components / Shadow DOM with the ::slotted pseudo-element. Likewise, the element targeted by this pseudo-element has changed from <content to <slot> in the latest version of the Shadow DOM specification. You can see related discussion about that change here.
Currently browsers still support <content> and ::content.
Original answer:
Summary:
::content is essentially a way to dig deeper and style descendants of the ShadowHost, which normally aren't available to be styled, because your CSS doesn't know to look for the ShadowDOM fragment without ::content.
This answer assumes you are at least somewhat familiar with the <template> element and Web Components, specifically the ShadowDOM, which deals with ShadowTrees and their two main elements, ShadowHost and ShadowRoot.
Note - As of this writing, there is less than 50% support (even prefixed, off-by-default support) for Web Components across the five major browsers. While all modern browsers support <template>, only recent versions of Chrome and Opera support the ShadowDOM fully; with Firefox supporting parts of it after you toggle the requisite feature in about:config (dom.webcomponents.enabled) to true.
The goal of using the ShadowDOM is similar to MVC's separation of concerns. That is, we want to separate our content from our presentation and allow for encapsulated templates in our code to help make it more manageable. We have this already in various programming languages, but it's remained a problem for some time in HTML and CSS. Further, there can be conflicts with class names when styling elements in web apps.
Normally, we interact with the LightDOM (a sort of "Light Realm"), but sometimes it would be helpful to take advantage of encapsulation. Crossing into this sort of "Shadow Realm" (part of Web Components) is a new method to prevent the problems mentioned above by allowing encapsulation. Any styles applied to markup in your ShadowTree won't apply to markup outside of your ShadowTree, even if the exact same classes or selectors are used.
When the ShadowTree (which lives in the ShadowDOM) has a tree from the LightDOM distributed within it, and/or when the ShadowTree is rendered, the result is converted by the browser into what is called a composed tree.
When the browser renders your code, content is being distributed and inserted at new locations other than where it was physically typed. This distributed output is what you see (and what the browser sees), and is called the composed tree. In reality, the content is not originally typed in the order that it now appears, but you won't know this, and neither will the browser. This separation between "end result" and "original code", if you will, is one of the main benefits of encapsulation.
Web Components & the Future of CSS is a great 40-minute video on Web Components and specifically the ShadowDOM, pointed out to me by ZachSaucier.
Specific to your question, the ::content pseudo element applies to what are called distributed nodes. A distributed node is another term for whatever you put within the <content></content> tags. The content is distributed from its place in the original markup to wherever you have placed your <content> tags in the template.
So, when you need specificity in CSS, one way you can handle selectors normally is that you go to the parent element and add that in as part of the selector. Ex: if .container {} is not specific enough, you might use div .container {} or .main .container {} in order to make your selector work.
Thinking about the point of the ShadowDOM, which is scoping and encapsulation, you have to realize that this new ShadowTree you've created is a completely new (discrete) DOM fragment. It's not in the same "Light Realm" as the rest of your content; it's in a "Shadow Realm". So, how does the CSS know to target this "Shadow Realm"? By using the ::content pseudo-element!
The ::content pseudo-element selector acts as the parent element of distributed nodes.
HTML5Rocks has a great sequence of tutorials here, here, and here which cover more information and give some great examples (be sure to visit with Chrome or Opera until more browsers support these features).
For example, see this modified and improved (by Leo) version of the code from HTML5Rocks:
var div = document.querySelector('div');
var root = div.createShadowRoot();
var template = document.querySelector('template');
root.appendChild(template.content);
<template>
<style>
h3 { color: red; }
content[select="h3"]::content > h3 { color: green; }
::content section p { text-decoration: underline; }
</style>
<h3>Shadow DOM</h3>
<content select="h3"></content>
<content select="section"></content>
</template>
<div>
<h3>Light DOM</h3>
<section>
<div>I'm not underlined</div>
<p>I'm underlined in Shadow DOM!</p>
</section>
</div>
Also available on JSFiddle (Remember to visit in a WebKit-based browser like Chrome or Opera)
Here you can see that the ::contentsection p pseudo element is first selecting the content of the ShadowRoot, which is the contents of the div element in your markup, and then specifying further by adding section p.
This may seem unnecessary when compared to normal CSS selector usage (for example, why not just use section p {}?), until you recall that, when traversing a ShadowTree, you cannot normally select descendants of host elements (which distributed nodes are), because they are in the "Shadow Realm" I mentioned earlier.
Too bad! Unfortunately ::content is v0, and was deprecated.
You should now use the v1 ::slotted.
Also, <content> was deprecated in favor of <slot>.
Please see: https://hayato.io/2016/shadowdomv1/
Also see: Web Components - why <content> was replaced with <slot>
I have some css styles with background colors, borders, etc... like this:
.bg-red {
background-color:red;
}
.bg-blue {
background-color:blue;
}
/*more background colors*/
.border-red {
background-color:red;
}
.border-blue {
background-color:blue;
}
/*more border colors*/
/*Like this i also have foreground color, border thickness, border style, transition/hover styles (specially for button hover) */
Like this i can style for example buttons.
example
<button class="fg-green bg-white
border-color-red border-thickness-thick border-style-dashed
hover-bg-grey hover-fg-black
hover-border-blue">
</button>
To make this more readable and shorter, i want to change it to this using custom attributes and css3 selectors
<button color="fg-green bg-white"
border="red thick dashed"
hover-color="bg-grey fg-black"
hover-border="blue">
</button>
but is this good practice?
I've read a lot of questions about this, and i can't really decide what i should do.
1) Is it OK to add your own attributes to HTML elements?
and a lot of other questions
From this question, i learned that custom attributes are not W3C compliant. but that html5 allows you to create custom attributes using the data- prefix.
in my opinion, colors and borders are not really data (or are they?), and the prefix is mostly used for javascript. so i don't know if i should do this.
2)
Is it a bad practice to use custom HTML attributes and style them with CSS?
Here, i read that classes are better, but should i give up readability and use classes instead?
So, what is more important? Making the code more readable by using attributes, or using classes but making it less readable?
Or is there a better solution?
Suggestions are always welcome!
edit: i'm just a beginner, so i don't know much about what's good and what's bad practice...
EDIT AGAIN: Thank you all for this info, all the answers where usefull so i upvoted every single one.
Also thank you Alochi for your helpful comments.
This is not a good practice.
How to use custom attributes?
First, you should use data attributes instead of full-custom attributes:
<button data-color="fg-green bg-white"
data-border="red thick dashed"
data-hover-color="bg-grey fg-black"
data-hover-border="blue">
</button>
These are syntaxically valid, and you can use as many as you want. Keep in mind they shouldn't interfere with external libraries (which are also allowed to create their own data attributes).
Is Object Oriented CSS the solution?
What you're doing is called Object Oriented CSS, and was popularized by frameworks like Bootstrap (formerly Twitter Bootstrap).
You've started to strongly link your HTML to your CSS.
Content is no longer independent from layout!
Sure, you've got less work to maintain your CSS, but:
this work is deported on your HTML
your HTML is dependent from your CSS
your HTML is not semantic
If you want to use CSS, you should think to reduce your amount of classes, and use semantic classes instead, like this for example:
.button-valid {
color: white;
background-color: green;
border: 1px solid green;
border-radius: 5px;
transition: all .2s;
}
.button-valid:hover {
color: green;
background-color: white;
}
Using <button class="button-valid"> has far more meaning than <button class="bg-green fg-white radius-5 b-green bgh-white fgh-green">
From CSS to Sass, and from OOCSS to OOSCSS?
So far, the better solution is to start to use CSS preprocessors.
I you want to go further, I would suggest you to read articles about Sass and OOSCSS.
First of: There was never an exclusive list of allowed tags and attributes, except in XHTML (dtds!) for validation. HTML itself is meant to support custom data structure. I know, there are a lot of people out there, disagreeing with 'if it is not restricted, you may use it'.
Best practice? Well, separating data and style is the rule of thumb. Classes are 'backwards compatible', custom tags in HTML (btw: HTML5-CustomComponents) too. But not attributes used in selectors (please search for a suiting CSS reference yourself).
Adding custom attributes per se is not bad. But there is a general agreement on prefixing custom attributes (HTML5) with data- e.g. data-my-custom-attr="abc". In CSS3, this is used as [data-my-custom-attr] {} or [data-my-custom-attr="abc"] {} to be accessed.
jQuery for example, makes these data attributes natively accessible by their $(elem).data() command, e.g. var val = $(elem).data('my-custom-attr');
This is primarily opinion based but...
Is it OK to add your own attributes to HTML elements?
Can you do it? Yes. Should you do it? Probably not. Why? Well, there are a number of reasons but from the top of my head...
Your code becomes less future proof. For instance, if a future HTML spec decides to introduce a new attribute that clash with yours. This can be overcome with data-prefixed attributes or using XHTML with a custom schema but...
Your code becomes less reliable. Since it does no longer adhere to the W3C spec, results might be inconsistent between browsers. Making a website with a consistent look between browser's versions is hard enough as it is...
Even using data prefixed attributes, it might not improve readability like you claim, specially for others or even a "future you". You might forget what an attribute means and, well, it becomes hard to find it's meaning unless you extensively document your system for future reference.
Also, for readability sake alone, I personally find this equally readable
<button class="fg-green
bg-white
border-color-red
border-thickness-thick
border-style-dashed
hover-bg-grey
hover-fg-black
hover-border-blue">
</button>
Is it a bad practice to use custom HTML attributes and style them with
CSS?
Well, it kind of defeats the purpose of CSS, whose idea is separation of style and content. Your system is not so different than in-line styling. <div style="color: red;"></div>. Why is this separation important? Because if you wish to change the styling later, it becomes a lot harder. You will need to run through your entire html files changing each instance, instead of changing it in your CSS.
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.
I am a CSS newbie. I am just wondering, is that possible to include one common class into another class?
for example,
.center {align: center};
.content { include .center here};
I came across css framework - Blueprint. We need to put the position information into HTML, e.g.
<div class="span-4"><div class="span-24 last">
As such, we will place the positioning attribute inside html, instead of css. If we change the layout, we need to change html, instead of css.
That's the reason I ask this question. If I can include .span-4 into my own css, i won't have to specify it in my html tag.
Bizarrely, even though CSS talks about inheritance, classes can't "inherit" in this way. The best you can really do is this:
.center, .content { align: center; }
.content { /* ... */ }
Also I'd strongly suggest you not do "naked" class selectors like this. Use ID or tag in addition to class where possible:
div.center, div.content { align: center; }
div.content { /* ... */ }
I say this because if you do your selectors as broad as possible it ends up becoming unmanageable (in my experience) once you get large stylesheets. You end up with unintended selectors interacting with each other to the point where you create a new class (like .center2) because changing the original will affect all sorts of things you don't want.
In standard CSS, it's not possible to do this, though it would be nice.
For something like that you'd need to use SASS or similar, which "compiles" to CSS.
This is where the Cascading in Cascading Style Sheets comes in to play.
Think of your html element or widget/module (group of nested html elements) as an object. You know you're going to have objects that share the same properties so you'll want to create a reusable class they can utilize.
.baseModule {align: center;}
Say your module is a message (error, flash...). So you "extend" or "include" your .baseModule class because all messages will be center aligned (see final html example).
.message {border: 1px solid #555;}
Furthermore you want your error messages to have a red background. Additionally you can overwrite the border property from .baseModule.message here if you wanted it to be a different color or something.
.error {background-color: red;}
So now you have a few css definitions that can be reused with ease.
<!-- Regular message module -->
<p class="baseModule message">
I am a regular message.
</p>
<!-- Error message module -->
<p class="baseModule message error">
I am an error message. My background color is red.
</p>
To relate this to your question you'd basically leverage multiple class names for maximum reusability. Granted ie6 doesn't support chained selectors (class1.class2.class3), but it's still a neat trick!
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.