#css compound selectors
Explore tagged Tumblr posts
thecommoncoder · 3 months ago
Video
youtube
Boost Your CSS Skills with Compound Selectors!
🚨 NEW VIDEO ALERT! 🚨 
 Ready to take your CSS skills to the next level? In today’s video, we dive into CSS compound selectors and show you how to combine basic selectors to create more specific rules. Compound selectors help you target elements that meet multiple criteria and reuse existing styles to create new ones—all without duplicating code. Enjoy! 🎉
#csscompoundselectors #css #cssselectors #webdevelopment #thecommoncoder
0 notes
jcmarchi · 9 months ago
Text
CSS Functions and Mixins Module Notes
New Post has been published on https://thedigitalinsider.com/css-functions-and-mixins-module-notes/
CSS Functions and Mixins Module Notes
Most days, I’m writing vanilla CSS. Thanks to CSS variables and nesting, I have fewer reasons to reach for Sass or any other preprocessor. The times I reach for Sass tend to be when I need a @mixin to loop through a list of items or help keep common styles DRY.
That could change for me in the not-so-distant future since a new CSS Functions and Mixins Module draft was published in late June after the CSSWG resolved to adopt the proposal back in February.
Notice the module’s name: Functions and Mixins. There’s a distinction between the two.
This is all new and incredibly unbaked at the moment with plenty of TODO notes in the draft and points to consider in future drafts. The draft spec doesn’t even have a definition for mixins yet. It’ll likely be some time before we get something real to work and experiment with, but I like trying to wrap my mind around these sorts of things while they’re still in early days, knowing things are bound to change.
In addition to the early draft spec, Miriam Suzanne published a thorough explainer that helps plug some of the information gaps. Miriam’s an editor on the spec, so I find anything she writes about this to be useful context.
There’s a lot to read! Here are my key takeaways…
Custom functions are advanced custom properties
We’re not talking about the single-purpose, built-in functions we’ve come to love in recent years — e.g., calc(), min(), max(), etc. Instead, we’re talking about custom functions defined with an @function at-rule that contains logic for returning an expected value.
That makes custom functions a lot like a custom property. A custom property is merely a placeholder for some expected value that we usually define up front:
:root --primary-color: hsl(25 100% 50%);
Custom functions look pretty similar, only they’re defined with @function and take parameters. This is the syntax currently in the draft spec:
@function <function-name> [( <parameter-list> )]? <function-rules> result: <result>;
The result is what the ultimate value of the custom function evaluates to. It’s a little confusing to me at the moment, but how I’m processing this is that a custom function returns a custom property. Here’s an example straight from the spec draft (slightly modified) that calculates the area of a circle:
@function --circle-area(--r) --r2: var(--r) * var(--r); result: calc(pi * var(--r2));
Calling the function is sort of like declaring a custom property, only without var() and with arguments for the defined parameters:
.elenent inline-size: --circle-area(--r, 1.5rem); /* = ~7.065rem */
Seems like we could achieve the same thing as a custom property with current CSS features:
:root --r: 1rem; --r2: var(--r) * var(--r); --circle-area: calc(pi * var(--r2)); .element inline-size: var(--circle-area, 1.5rem);
That said, the reasons we’d reach for a custom function over a custom property are that (1) they can return one of multiple values in a single stroke, and (2) they support conditional rules, such as @supports and @media to determine which value to return. Check out Miriam’s example of a custom function that returns one of multiple values based on the inline size of the viewport.
/* Function name */ @function --sizes( /* Array of possible values */ --s type(length), --m type(length), --l type(length), /* The returned value with a default */ ) returns type(length) --min: 16px; /* Conditional rules */ @media (inline-size < 20em) result: max(var(--min), var(--s, 1em)); @media (20em < inline-size < 50em) result: max(var(--min), var(--m, 1em + 0.5vw)); @media (50em < inline-size) result: max(var(--min), var(--l, 1.2em + 1vw));
Miriam goes on to explain how a comma-separated list of parameters like this requires additional CSSWG work because it could be mistaken as a compound selector.
Mixins help maintain DRY, reusable style blocks
Mixins feel more familiar to me than custom functions. Years of writing Sass mixins will do that to you, and indeed, is perhaps the primary reason I still reach for Sass every now and then.
Mixins sorta look like the new custom functions. Instead of @function we’re working with @mixin which is exactly how it works in Sass.
/* Custom function */ @function <function-name> [( <parameter-list> )]? <function-rules> result: <result>; /* CSS/Sass mixin */ @mixin <mixin-name> [( <parameter-list> )]? <mixin-rules>
So, custom functions and mixins are fairly similar but they’re certainly different:
Functions are defined with @function; mixins are defined with @mixin but are both named with a dashed ident (e.g. --name).
Functions result in a value; mixins result in style rules.
This makes mixins ideal for abstracting styles that you might use as utility classes, say a class for hidden text that is read by screenreaders:
.sr-text position: absolute; left: -10000px; top: auto; width: 1px; height: 1px; overflow: hidden;
In true utility fashion, we can sprinkle this class on elements in the HTML to hide the text.
<a class="sr-text">Skip to main content</a>
Super handy! But as any Tailwind-hater will tell you, this can lead to ugly markup that’s difficult to interpret if we rely on many utility classes. Screereader text isn’t in too much danger of that, but a quick example from the Tailwind docs should illustrate that point:
<div class="origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg">
It’s a matter of preference, really. But back to mixins! The deal is that we can use utility classes almost as little CSS snippets to build out other style rules and maintain a clearer separation between markup and styles. If we take the same .sr-text styles from before and mixin-erize them (yep, I’m coining this):
@mixin --sr-text position: absolute; left: -10000px; top: auto; width: 1px; height: 1px; overflow: hidden;
Instead of jumping into HTML to apply the styles, we can embed them in other CSS style rules with a new @apply at-rule:
header a:first-child @apply --sr-text; /* Results in: */ position: absolute; left: -10000px; top: auto; width: 1px; height: 1px; overflow: hidden;
Perhaps a better example is something every project seems to need: centering something!
@mixin --center-me display: grid; place-items: center;
This can now be part of a bigger ruleset:
header @apply --center-me; /* display: grid; place-items: center; */ background-color: --c-blue-50; color: --c-white; /* etc. */
That’s different from Sass which uses @include to call the mixin instead of @apply. We can even return larger blocks of styles, such as styles for an element’s ::before and ::after pseudos:
@mixin --center-me display: grid; place-items: center; position: relative; &::after background-color: hsl(25 100% 50% / .25); content: ""; height: 100%; position: absolute; width: 100%;
And, of course, we saw that mixins accept argument parameters just like custom functions. You might use arguments if you want to loosen up the styles for variations, such as defining consistent gradients with different colors:
@mixin --gradient-linear(--color-1, --color-2, --angle) /* etc. */
We’re able to specify the syntax for each parameter as a form of type checking:
@mixin --gradient-linear( --color-1 type(color), --color-2 type(color), --angle type(angle), ) /* etc. */
We can abstract those variables further and set default values on them:
@mixin --gradient-linear( --color-1 type(color), --color-2 type(color), --angle type(angle), ) --from: var(--color-1, orangered); --to: var(--from-color, goldenrod); --angle: var(--at-angle, to bottom right); /* etc. */
…then we write the mixin’s style rules with the parameters as variable placeholders.
@mixin --gradient-linear( --color-1 type(color), --color-2 type(color), --angle type(angle), ) --from: var(--color-1, orangered); --to: var(--from-color, goldenrod); --angle: var(--at-angle, to bottom right); background: linear-gradient(var(--angle), var(--from), var(--to));
Sprinkle conditional logic in there if you’d like:
@mixin --gradient-linear( --color-1 type(color), --color-2 type(color), --angle type(angle), ) --from: var(--color-1, orangered); --to: var(--from-color, goldenrod); --angle: var(--at-angle, to bottom right); background: linear-gradient(var(--angle), var(--from), var(--to)); @media (prefers-contrast: more) background: color-mix(var(--from), black); color: white;
This is all set to @apply the mixin in any rulesets we want:
header @apply --gradient-linear; /* etc. */ .some-class @apply --gradient-linear; /* etc. */
…and combine them with other mixins:
header @apply --gradient-linear; @apply --center-me; /* etc. */
This is all very high level. Miriam gets into the nuances of things like:
Applying mixins at the root level (i.e., not in a selector)
Working with Container Queries with the limitation of having to set global custom properties on another element than the one that is queried.
The possibility of conditionally setting mixin parameters with something like @when/@else in the mixin. (Which makes me wonder about the newly-proposed if() function and whether it would be used in place of @when.)
Why we might draw a line at supporting loops the same way Sass does. (CSS is a declarative language and loops are imperative flows.)
Scoping mixins (@layer? scope? Something else?)
Miriam has an excellent outline of the open questions and discussions happening around mixins.
That’s, um, it… at least for now.
Gah, this is a lot for my blonde brain! Anytime I’m neck-deep in CSS specification drafts, I have to remind myself that the dust is still settling. The spec authors and editors are wrestling with a lot of the same questions we have — and more! — so it’s not like a cursory read of the drafts is going to make experts out of anyone. And that’s before we get to the fact that things can, and likely will, change by the time it all becomes a recommended feature for browsers to implement.
This will be an interesting space to watch, which is something you can do with the following resources:
0 notes
verenawulfweb · 4 years ago
Text
CSS Baby Steps: You Need to Crawl Before You Walk
Cascade - Just Like a Waterfall
Like everyone who begins to learn coding for front-end development, I started off by learning some basic HTML. And like - I would guess - most people, I thought it was quite straightforward and found it incredibly satisfying to see a page develop in front of my eyes while I was inputting tags and elements in my code editor. 
But then came CSS - Cascading Style Sheet. It made sense to me that we need to create a separate style sheet in our editor that we then link to our HTML pages, to make sure that we keep the content (created through HTML) neatly separated from layout, looks and style (created through CSS). What I did not understand, however, was what the C stands for.
One of the definitions of cascade that Merriam Webster offers apart from “a steep usually small waterfall” is:
“ something arranged or occurring in a series or in a succession of stages so that each stage derives from or acts upon the product of the preceding” 
Looking back at the mistakes I made while trying to implement CSS - mistakes I absolutely could not understand, and which seemed completely random to me - now make a lot more sense. Cascading means there is a certain succession, and the order in which we write rules onto our style sheets is important. 
Tumblr media
Just like the flow of a waterfall: we need to create our style sheets from top to bottom. Image by  sgcdesignco on unsplash.
Once I understood one needs to follow a certain order, I also understood why some of the things I had input were suddenly overruled by others. Shay Howe’s Website Learn to Code HTML and CSS perfectly breaks this down:
p {  background: orange;  font-size: 24px; } p {  background: green; }
“ Because the paragraph selector that sets the background color to green comes after the paragraph selector that sets the background color to orange, it will take precedence in the cascade. All of the paragraphs will appear with a green background.”
Thanks to Shay Howe, I also finally understood the different kinds of selectors we are working with in CSS - type selectors, class selectors and id selectors - and that these selectors have a different specificity, and consequently a different weight in the cascade. 
Type selectors such as <p> (paragraph) or <div> (dividers) select elements according to their type. They are quite broad.
Class selectors are more specific, they allow us to target elements according to their class attributes. They can be used several times throughout a page. The example Howe uses here is
CSS
.awesome { ... }
HTML
<div class="awesome">...</div> <p class="awesome">...</p>
What became clear to me through his examples is that I as the developer can come up with my own class attributes (as seen in .awesome). Before, I had always thought that there are a number of attributes one needs to choose from. But in fact, I have complete creative freedom over the choice of my attributes.
Id Selectors are even more specific than class selectors. They are unique and can only be used one single time. 
CSS
#shayhowe { ... }
HTML
<div id="shayhowe">...</div>
Just like the class attributes, I as the developer can come up with my own id attributes. And most importantly to note: there more specific a selector is, the more weight it carries, which means it receives precedence in the cascade. 
Combining Selectors: Just like German Compound Words
One of the most relevant things I learned from Howe’s  Learn to Code HTML and CSS is that you can combine selectors and thus be more specific and detailed. To understand the logic behind this, it helped me to draw the analogy to German compound words.
The German language is famous for producing extremely long words, because it can simply “glue” words together to express something very specific. In English, for example, those words would often be separated by “of” or “by” or “from.”
Tumblr media
Confusing? Maybe. But looking only at the very last word of this compound, we know this is just a very specific kind of Barbier, a barber.
To give a simple example:
Blume = flower; Topf = pot; Erde = soil; Dünger = fertilizer
Blumentopf= flower pot. It is a specific pot used for flowers. Topf (or pot) is the main qualifier.
Blumentopferde = a specific kind of soil that is used for flowers in a pot. Erde (soil) is the main qualifier. 
Blumentopferdendünger = a specific kind of fertilizer that is used for soil that is used for flowers in a pot. Dünger is the main qualifier. 
From this example we can see that the word at the end (or at the very right) is always the main qualifier. The words preceding just give extra information, and add specificity. 
With regard to selectors in CSS, it seems to work the same way. Again, an example taken from Howe: the goal is to make the background of only one specific paragraph yellow amidst an otherwise completely brown-coloured block of paragraphs(the <p>s inside the <div>):
HTML
<div class="hotdog">
 <p>...</p>  <p>...</p>  <p class="mustard">...</p> </div>
CSS
.hotdog p {  background: brown; } .hotdog p.mustard {  background: yellow; }
The combination of several selectors .hotdog p.mustard allows us to target only one specific paragraph without affecting the others. Like the German compound words, we need to read from right to left. The selector at the very right is the key selector, all the others to the left are prequalifies. Like the Barbier and the Dünger are just a very specific kind of barber and fertilizer, the .mustard selector is a very specific kind of selector that can be found inside the p selector that can be found inside the .hotdog selector.
So far the theory. Now let’s hope this will also work when put into practice.
0 notes
siva3155 · 5 years ago
Text
300+ TOP SASS Interview Questions and Answers
SASS Interview Questions for freshers experienced :-
1. What is SASS? SASS means Syntactically Awesome Style sheets. It is a CSS preprocessor which is used to reduce repetition with CSS and save time. It adds power and elegance to the basic language and facilitates you to add variables, nested rules, mixins, inline imports, inheritance and more, all with fully CSS-compatible syntax. 2. Who is the inventor of SASS? Hampton Catlin is known as the father of SASS. 3. What are the reasons behind using SASS? Following are some important reasons behind the popularity of SASS. You can write codes easily and efficiently, and they are easy to maintain. It is a pre-processing language which provides its syntax for CSS. It is a superset of CSS which contains all the features of CSS and is an open source pre-processor, coded in Ruby. It is more stable and powerful CSS extension and style documents more clearly and structurally. It facilitates reusability methods, logic statements and some of the built-in functions like color manipulation, mathematics, and parameter lists item. 4. How many ways can we use SASS? We can use SASS in three different ways: As a command line tool. As a standalone Ruby module. As a plug-in for any Rack-enabled framework. 5. What are the most attractive features of SASS? It is more stable, powerful and fully compatible to CSS3. It is time-saving because it facilitates you to write CSS in less code. It uses its syntax. It is based on the JavaScript and superset of CSS. It is an Open source pre-processor that interprets into CSS. It contains various functions for manipulating colors and other values. It has advanced control directives for libraries. It provides well formatted, customizable output. 6. Which data types does the Sass Script supports? Following data types are supported by the Sass Script: Boolean (true or false) Number (1, 5, 13, 10px) Nulls Colors (red, #FF0000) Text String, without quote ("foo", "bar") List of values that are separated by commas or space (2.0em, Verdana, Arial, Helvetica) Maps from one value to another value (key 1: value 1, key 2: value 2) Function reference. SASS always supports all other types of CSS property value such as Unicode range, special character, and unquoted string. 7. Which variable is used to define SASS? A variable begins with a dollar ($) sign, and the assignment of the variable is completed with a semicolon (;) sign. 8. Explain the difference between SCSS and Sass? The main differences between SCSS and Sass are as follow: Sass is like a CSS pre-processor. It has the extension of CSS3. Sass is derived from another preprocessor known as Haml. Sass contains two types of syntax: "SCSS" is the first syntax and it uses the extension of .scss. Indented syntax or "Sass" is the other syntax and it uses the extension of .sass You can covert the valid CSS document into Sass by simply change the extension from .CSS to .SCSS. It is fully CSS compatible. SCSS provides the CSS friendly syntax to closing the gap between Sass and CSS. SCSS is called Sassy CSS. 9. Explain the use of Sass @import function? It facilitates you to extend the CSS import rule. To do this you need to enable import of Sass and SCSS files. It can merge the all the imported files into a single outputted CSS file. It is used to virtually match and mix any file. It needs a filename to import function. It provides document style presentation better than flat CSS. It facilitates you to keep your responsive design project more organized. 10. What are the advantages of Sass? Time saving. More efficient and quicker. Compatible with all versions of CSS. You can use nested syntax and useful functions such as color manipulation, mathematics and other values. Write clean CSS in programming construct It is the super set of the CSS and using nested and others value.
Tumblr media
SASS Interview Questions 11. What are nested rules in Sass? Nesting is a method of combining multiple logic structures within one another. In Sass, various CSS rules are connected to one another. For example, if you are using multiple selectors then you can use one selector inside another to create compound selectors. 12. Which one is better, Sass or Less? Due to the following reasons, Sass is better than less: Sass provides the facilities to use logical statements like loops, conditions and also facilitates you to write reusable methods. The user of Sass can access the library of the company. Sass users can also use some awesome features like cross-browser support, legacy browser hacks, and dynamic sprite map generation. Compass also provides the facilities to add an external framework like Bootstrap on top, Blueprint. Sass provides you the facility to write your handy functions 13. What is the way to write a placeholder selector in Sass? In Sass, the placeholder selectors can be used with class or id selector. In standard CSS, these are specified with "#" or ".", but in SASS they are replaced with "%". It uses @extend directive to display the result in CSS. For example: .para1 { color: blue; } .para2 { @extend .para1; font-size:30px; } 14. What are number operations in Sass? In Sass, the number operations are used for mathematical operations like addition, subtraction, multiplication and division. The Sass number operation will do something like take pixel values and convert them to percentages without much hassle. 15. What are the color operations in Sass? In Sass, color operation allows to use color In Sass, color operation allows to use color components along with arithmetic operations. 16. How can we perform Boolean operations in Sass? The Boolean operations can be performed on Sass script by using and, & and not operators. 17. What are parentheses in Sass? Parentheses are used to provide a symbolic logic that affects the order of the operation. It is a pair of signs which are usually marked off by round () brackets or square brackets. 18. Define the use of Sass Mixin function? The Mixin function is used to define styles. Functions and Mixins are very similar. You can re-use this style throughout the style sheet. To re-use it you do not need to resort the non-semantic classes like .float-left. The Mixin can store multiple values or parameters and call a function to avoid writing repetitive codes. It names can use underscores and hyphens interchangeably. 19. What is the use of DRY-ing out a Mixin function in Sass? DDRY-ing out a Mixin function splits into two parts: the static part and dynamic parts. The static Mixin contains the pieces of information that would otherwise get duplicated and the dynamic Mixin is the function that the user going to call. 20. Describe the difference between Sass comment and regular CSS comment? Comments in regular CSS starts with /* */ and Sass contains two commands. The single line comment with // and multiple CSS comments with /* */. 21. Which directive is used to detect the errors in SASS? Sass @debug directive is used to detect the errors and display the Sass Script expressions values to the standard error output stream. For example: $font-sizes: 10px + 20px; $style: ( color: #bdc3c7 ); .container{ @debug $style; @debug $font-sizes; } 22. What are the requirements of SASS system? These are the requirements for Sass system:- Operating System - Cross platform Browser support - Internet Explorer, Google Chrome, Safari, Opera. Programming language - Ruby. 23. What is the use of @extend directive in SASS? The SASS @extend directive is used to share a set of CSS properties from one selector to another. It is a very important and useful feature of Sass. It allows classes to share a set of properties with one another. It makes your code less and facilitates you to rewrite it repeatedly. For example: .message border: 1px solid #ccc padding: 10px color: #333 .success @extend .message border-color: green .error @extend .message border-color: red .warning @extend .message border-color: yellow 24. What is the role of @media directive in SASS? The Sass @media directive is used to set style rules to different media types. It supports and extends the @media rules. This directive can be nested inside the selector SASS but the main impact is displayed to the top level of the style sheet. For example:- h2{ color: violet; } .style{ width: 500px; @media screen and (orientation: portrait){ width:200px; margin-left: 80px; } } 25. What is the use of at-root directive in SASS? The Sass @at-root directive is a collection of nested rules that are used to style block at the root of the document. For example:- h2{ color: blue; background-color: pink; @at-root { .style{ font-size: 20px; font-style: bold; color: violet; } } } SASS Questions and Answers Pdf Download Read the full article
0 notes
siliconwebx · 6 years ago
Text
Breaking CSS Custom Properties out of :root Might Be a Good Idea
CSS Custom Properties have been a hot topic for a while now, with tons of great articles about them, from great primers on how they work to creative tutorials to do some real magic with them. If you’ve read more than one or two articles on the topic, then I’m sure you’ve noticed that they start by setting up the custom properties on the :root about 99% of the time.
While putting custom properties on the :root is great for things that you need to be available throughout your site, there are times when it makes more sense to scope your custom properties locally.
In this article, we’ll be exploring:
Why we put custom properties on the :root to begin with.
Why global scoping isn’t right for everything.
How to overcome class clashing with locally scoped custom properties
What’s the deal with custom properties and :root?
Before we jump into looking at the global scope, I think it’s worth looking at why everyone sets custom properties in the :root to begin with.
I’ve been declaring custom properties on the :root without even a second thought. Pretty much everyone does it without even a mention of why — including the official specification.
When the subject of :root is actually breached, it mentions how :root is the same as html, but with higher specificity, and that’s about it.
But does that higher specificity really matter?
Not really. All it does is select html with a higher specificity, the same way a class selector has higher specificity than an element selector when selecting a div.
:root { --color: red; } html { --color: blue; } .example { background: var(--color); /* Will be red because of :root's higher specificity */ }
The main reason that :root is suggested is because CSS isn’t only used to style HTML documents. It is also used for XML and SVG files.
In the case of XML and SVG files, :root isn’t selecting the html element, but rather their root (such as the svg tag in an SVG file).
Because of this, the best practice for a globally-scoped custom property is the :root. But if you’re making a website, you can throw it on an html selector and not notice a difference.
That said, with everyone using :root, it has quickly become a “standard.” It also helps separate variables to be used later on from selectors which are actively styling the document.
Why global scope isn’t right for everything
With CSS pre-processors, like Sass and Less, most of us keep variables tucked away in a partial dedicated to them. That works great, so why should we consider locally scoping variables all of a sudden?
One reason is that some people might find themselves doing something like this.
:root { --clr-light: #ededed; --clr-dark: #333; --clr-accent: #EFF; --ff-heading: 'Roboto', sans-serif; --ff-body: 'Merriweather', serif; --fw-heading: 700; --fw-body: 300; --fs-h1: 5rem; --fs-h2: 3.25rem; --fs-h3: 2.75rem; --fs-h4: 1.75rem; --fs-body: 1.125rem; --line-height: 1.55; --font-color: var(--clr-light); --navbar-bg-color: var(--clr-dark); --navbar-logo-color: var(--clr-accent); --navbar-border: thin var(--clr-accent) solid; --navbar-font-size: .8rem; --header-color: var(--clr-accent); --header-shadow: 2px 3px 4px rgba(200,200,0,.25); --pullquote-border: 5px solid var(--clr-light); --link-fg: var(--clr-dark); --link-bg: var(--clr-light); --link-fg-hover: var(--clr-dark); --link-bg-hover: var(--clr-accent); --transition: 250ms ease-out; --shadow: 2px 5px 20px rgba(0, 0, 0, .2); --gradient: linear-gradient(60deg, red, green, blue, yellow); --button-small: .75rem; --button-default: 1rem; --button-large: 1.5rem; }
Sure, this gives us one place where we can manage styling with custom properties. But, why do we need to define my --header-color or --header-shadow in my :root? These aren’t global properties, I’m clearly using them in my header and no where else.
If it’s not a global property, why define it globally? That’s where local scoping comes into play.
Locally scoped properties in action
Let’s say we have a list to style, but our site is using an icon system — let’s say Font Awesome for simplicity’s sake. We don’t want to use the disc for our ul bullets — we want a custom icon!
If I want to switch out the bullets of an unordered list for Font Awesome icons, we can do something like this:
ul { list-style: none; } li::before { content: "\f14a"; /* checkbox */ font-family: "Font Awesome Free 5"; font-weight: 900; float: left; margin-left: -1.5em; }
While that’s super easy to do, one of the problems is that the icon becomes abstract. Unless we use Font Awesome a lot, we aren’t going to know that f14a means, let alone be able to identify it as a checkbox icon. It’s semantically meaningless.
We can help clarify things with a custom property here.
ul { --checkbox-icon: "\f14a"; list-style: none; }
This becomes a lot more practical once we start having a few different icons in play. Let’s up the complexity and say we have three different lists:
<ul class="icon-list checkbox-list"> ... </ul> <ul class="icon-list star-list"> ... </ul> <ul class="icon-list bolt-list"> ... </ul>
Then, in our CSS, we can create the custom properties for our different icons:
.icon-list { --checkbox: "\f14a"; --star: "\f005"; --bolt: "\f0e7"; list-style: none; }
The real power of having locally scoped custom properties comes when we want to actually apply the icons.
We can set content: var(--icon) on our list items:
.icon-list li::before { content: var(--icon); font-family: "Font Awesome Free 5"; font-weight: 900; float: left; margin-left: -1.5em; }
Then we can define that icon for each one of our lists with more meaningful naming:
.checkbox-list { --icon: var(--checkbox); } .star-list { --icon: var(--star); } .bolt-list { --icon: var(--bolt); }
We can step this up a notch by adding colors to the mix:
.icon-list li::before { content: var(--icon); color: var(--icon-color); /* Other styles */ }
Moving icons to the global scope
If we’re working with an icon system, like Font Awesome, then I’m going to assume that we’d be using them for more than just replacing the bullets in unordered lists. As long as we're using them in more than one place it makes sense to move the icons to the :root as we want them to be available globally.
Having icons in the :root doesn’t mean we can’t still take advantage of locally scoped custom properties, though!
:root { --checkbox: "\f14a"; --star: "\f005"; --bolt: "\f0e7"; --clr-success: rgb(64, 209, 91); --clr-error: rgb(219, 138, 52); --clr-warning: rgb(206, 41, 26); } .icon-list li::before { content: var(--icon); color: var(--icon-color); /* Other styles */ } .checkbox-list { --icon: var(--checkbox); --icon-color: var(--clr-success); } .star-list { --icon: var(--star); --icon-color: var(--clr-warning); } .bolt-list { --icon: var(--bolt); --icon-color: var(--clr-error); }
Adding fallbacks
We could either put in a default icon by setting it as the fallback (e.g. var(--icon, "/f1cb")), or, since we’re using the content property, we could even put in an error message var(--icon, "no icon set").
See the Pen Custom list icons with CSS Custom Properties by Kevin (@kevinpowell) on CodePen.
By locally scoping the --icon and the --icon-color variables, we’ve greatly increased the readability of our code. If someone new were to come into the project, it will be a whole lot easier for them to know how it works.
This isn’t limited to Font Awesome, of course. Locally scoping custom properties also works great for an SVG icon system:
:root { --checkbox: url(../assets/img/checkbox.svg); --star: url(../assets/img/star.svg); --baby: url(../assets/img/baby.svg); } .icon-list { list-style-image: var(--icon); } .checkbox-list { --icon: checkbox; } .star-list { --icon: star; } .baby-list { --icon: baby; }
Using locally scoped properties for more modular code
While the example we just looked at works well to increase the readability of our code — which is awesome — we can do a lot more with locally scoped properties.
Some people love CSS as it is; others hate working with the global scope of the cascade. I’m not here to discuss CSS-in-JS (there are enough really smart people already talking about that), but locally scoped custom properties offer us a fantastic middle ground.
By taking advantage of locally scoped custom properties, we can create very modular code that takes a lot of the pain out of trying to come up with meaningful class names.
Let’s um, scope the scenario.
Part of the reason people get frustrated with CSS is that the following markup can cause problems when we want to style something.
<div class="card"> <h2 class="title">This is a card</h2> <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Libero, totam.</p> <button class="button">More info</button> </div> <div class="cta"> <h2 class="title">This is a call to action</h2> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Aliquid eveniet fugiat ratione repellendus ex optio, ipsum modi praesentium, saepe, quibusdam rem quaerat! Accusamus, saepe beatae!</p> <button class="button">Buy now</button> </div>
If I create a style for the .title class, it will style both the elements containing the .card and .cta classes at the same time. We can use a compound selector (i.e. .card .title), but that raises the specificity which can lead to less maintainability. Or, we can take a BEM approach and rename our .title class to .card__title and .cta__title to isolate those elements a little more.
Locally scoped custom properties offer us a great solution though. We can apply them to the elements where they’ll be used:
.title { color: var(--title-clr); font-size: var(--title-fs); } .button { background: var(--button-bg); border: var(--button-border); color: var(--button-text); }
Then, we can control everything we need within their parent selectors, respectively:
.card { --title-clr: #345; --title-fs: 1.25rem; --button-border: 0; --button-bg: #333; --button-text: white; } .cta { --title-clr: #f30; --title-fs: 2.5rem; --button-border: 0; --button-bg: #333; --button-text: white; }
Chances are, there are some defaults, or commonalities, between buttons or titles even when they are in different components. For that, we could build in fallbacks, or simply style those as we usually would.
.button { /* Custom variables with default values */ border: var(--button-border, 0); /* Default: 0 */ background: var(--button-bg, #333); /* Default: #333 */ color: var(--button-text, white); /* Default: white */ /* Common styles every button will have */ padding: .5em 1.25em; text-transform: uppercase; letter-spacing: 1px; }
We could even use calc() to add a scale to our button, which would have the potential to remove the need for .btn-sm, btn-lg type classes (or it could be built into those classes, depending on the situation).
.button { font-size: calc(var(--button-scale) * 1rem); /* Multiply `--button-scale` by `1rem` to add unit */ } .cta { --button-scale: 1.5; }
Here is a more in-depth look at all of this in action:
See the Pen Custom list icons with CSS Custom Properties by Kevin (@kevinpowell) on CodePen.
Notice in that example above that I have used some generic classes, such as .title and .button, which are styled with locally scoped properties (with the help of fallbacks). With those being setup with custom properties, I can define those locally within the parent selector, effectively giving each its own style without the need of an additional selector.
I also set up some pricing cards with modifier classes on them. Using the generic .pricing class, I set everything up, and then using modifier classes, I redefined some of the properties, such as --text, and --background, without having to worry about using compound selectors or additional classes.
By working this way, it makes for very maintainable code. It’s easy to go in and change the color of a property if we need to, or even come in and create a completely new theme or style, like the rainbow variation of the pricing card in the example.
It takes a bit of foresight when initially setting everything up, but the payoff can be awesome. It might even seem counter-intuitive to how you are used to approaching styles, but next time you go to create a custom property, try keeping it defined locally if it doesn’t need to live globally, and you’ll start to see how useful it can be.
The post Breaking CSS Custom Properties out of :root Might Be a Good Idea appeared first on CSS-Tricks.
😉SiliconWebX | 🌐CSS-Tricks
0 notes
aracecvliwest · 7 years ago
Text
We Write CSS Like We Did in the 90s, and Yes, It’s Silly
As web developers, we marvel at technology. We enjoy the many tools that help with our work: multipurpose editors, frameworks, libraries, polyfills and shims, content management systems, preprocessors, build and deployment tools, development consoles, production monitors—the list goes on.
Our delight in these tools is so strong that no one questions whether a small website actually requires any of them. Tool obesity is the new WYSIWYG—the web developers who can’t do without their frameworks and preprocessors are no better than our peers from the 1990s who couldn’t do without FrontPage or Dreamweaver. It is true that these tools have improved our lives as developers in many ways. At the same time, they have perhaps also prevented us from improving our basic skills.
I want to talk about one of those skills: the craft of writing CSS. Not of using CSS preprocessors or postprocessors, but of writing CSS itself. Why? Because CSS is second in importance only to HTML in web development, and because no one needs processors to build a site or app.
Most of all, I want to talk about this because when it comes to writing CSS, it often seems that we have learned nothing since the 1990s. We still write CSS the natural way, with no advances in sorting declarations or selectors and no improvements in writing DRY CSS.
Instead, many developers argue fiercely about each of these topics. Others simply dig in their heels and refuse to change. And a third cohort protests even the discussion of these topics.
I don’t care that developers do this. But I do care about our craft. And I care that we, as a profession, are ignoring simple ways to improve our work.
Let’s talk about this more after the code break.
Here’s unsorted, unoptimized CSS from Amazon in 2003.
.serif { font-family: times, serif; font-size: small; } .sans { font-family: verdana, arial, helvetica, sans-serif; font-size: small; } .small { font-family: verdana, arial, helvetica, sans-serif; font-size: x-small; } .h1 { font-family: verdana, arial, helvetica, sans-serif; color: #CC6600; font-size: small; } .h3color { font-family: verdana, arial, helvetica, sans-serif; color: #CC6600; font-size: x-small; } .tiny { font-family: verdana, arial, helvetica, sans-serif; font-size: xx-small; } .listprice { font-family: arial, verdana, sans-serif; text-decoration: line-through; font-size: x-small; } .price { font-family: verdana, arial, helvetica, sans-serif; color: #990000; font-size: x-small; } .attention { background-color: #FFFFD5; }
And here’s CSS from contemporary Amazon:
.a-box { display: block; border-radius: 4px; border: 1px #ddd solid; background-color: #fff; } .a-box .a-box-inner { border-radius: 4px; position: relative; padding: 14px 18px; } .a-box-thumbnail { display: inline-block; } .a-box-thumbnail .a-box-inner { padding: 0 !important; } .a-box-thumbnail .a-box-inner img { border-radius: 4px; } .a-box-title { overflow: hidden; } .a-box-title .a-box-inner { overflow: hidden; padding: 12px 18px 11px; background: #f0f0f0; }
Just as in 2003, the CSS is unsorted and unoptimized. Did we learn anything over the past 15 years? Is this really the best CSS we can write?
Let’s look at three areas where I believe we can easily improve the way we do our work: declaration sorting, selector sorting, and declaration repetition.
Declaration sorting
The 90s web developer, if he or she wrote CSS, wrote CSS as it occurred to them. Without sense or order—with no direction whatsoever. The same was true of last decade’s developer. The same is true of today’s developer, whether novice or expert.
.foo { font: arial, sans-serif; background: #abc; margin: 1em; text-align: center; letter-spacing: 1px; -x-yaddayadda: yes; }
The only difference between now and then: today’s expert developer uses eight variables, because “that’s how you do it” (even with one-pagers) and because at some point in their life they may need them. In twenty-something years of web development we have somehow not managed to make our CSS consistent and easier to work on by establishing the (or even a) common sense standard to sort declarations.
(If this sounds harsh, it’s because it’s true. Developers condemn selectors, shorthands, !important, and other useful aspects of CSS rather than concede that they don’t even know how to sort their declarations.)
In reality, the issue is dead simple: Declarations should be sorted alphabetically. Period.
Why?
For one, sorting makes collaborating easier.
Untrained developers can do it. Non-English speakers (such as this author) can do it. I wouldn’t be surprised to learn that even houseplants can do it.
For another reason, alphabetical sorting can be automated. What’s that? Yes, one can use or write little scripts (such as CSS Declaration Sorter) to sort declarations.
Given the ease of sorting, and its benefits, the current state of affairs borders on the ridiculous, making it tempting to ignore our peers who don’t sort declarations, and to ban from our lives those who argue that it’s easier—or even logical—not to sort alphabetically but instead to sort based on 1) box dimensions, 2) colors, 3) grid- or flexbox-iness, 4) mood, 5) what they ate for breakfast, or some equally random basis.
With this issue settled (if somewhat provocatively), on to our second problem from the 90s.
Selector sorting
The situation concerning selectors is quite similar. Almost since 1994, developers have written selectors and rules as they occurred to them. Perhaps they’ve moved them around (“Oh, that belongs with the nav”). Perhaps they’ve refactored their style sheets (“Oh, strange that site styles appear amidst notification styles”). But standardizing the order—no.
Let’s take a step back and assume that order does matter, not just for aesthetics as one might think, but for collaboration. As an example, think of the letters below as selectors. Which list would be easiest to work with?
c, b · a · a, b · c, d · d, c, a · e · a c · b · a, b · a · c, d · a, c, d · a · e a, b · a, c, d · a · b, c · c, d · e
The fact that one selector (a) was a duplicate that only got discovered and merged in the last row perhaps gives away my preference. But then, if you wanted to add d, e to the list, wouldn’t the order of the third row make placing the new selector easier than placing it in either of the first two rows?
This example gets at the two issues caused by not sorting selectors:
No one knows where to add new selectors, creating a black hole in the workflow.
There’s a higher chance of both selector repetition and duplication of rules with the same selectors.
Both problems get compounded in larger projects and larger teams. Both problems have haunted us since the 90s. Both problems get fixed by standardizing—through coding guidelines—how selectors should be ordered.
The answer in this case is not as trivial as sorting alphabetically (although we could play with the idea—the cognitive ease of alphabetical selector sorting may make it worth trying). But we can take a path similar to how the HTML spec roughly groups elements, so that we first define sections, and then grouping elements, text elements, etc. (That’s also the approach of at least one draft, the author’s.)
The point is that ideal selector sorting doesn’t just occur naturally and automatically. We can benefit from putting more thought into this problem.
Declaration repetition
Our third hangover from the 90s is that there is and has always been an insane amount of repetition in our style sheets. According to one analysis of more than 200 websites, a median of 66% of all declarations are redundant, and the repetition rate goes as high as 92%—meaning that, in this study at least, the typical website uses each declaration at least three times and some up to ten times.
As shown by a list of some sample sites I compiled, declaration repetition has indeed been bad from the start and has even increased slightly over the years.
Yes, there are reasons for repetition: notably for different target media (we may repeat ourselves for screen, print, or different viewport sizes) and, occasionally, for the cascade. That is why a repetition rate of 10–20% seems to be acceptable. But the degree of repetition we observe right now is not acceptable—it’s an unoptimized mess that goes mostly unnoticed.
What’s the solution here? One possibility is to use declarations just once. We’ve seen with a sample optimization of Yandex’s large-scale site that this can lead to slightly more unwieldy style sheets, but we also know that in many other cases it does make them smaller and more compact.
This approach of using declarations just once has at least three benefits:
It reduces repetition to a more acceptable amount.
It reduces the pseudo need for variables.
Excluding outliers like Yandex, it reduces file size and payload (10–20% according to my own experience—we looked at the effects years ago at Google).
No matter what practice we as a field come up with—whether to use declarations just once or follow a different path—the current level of “natural repetition” we face on sample websites is too high. We shouldn’t need to remind ourselves not to repeat ourselves if we repeat code up to nine times, and it’s getting outright pathetic—again excuse the strong language—if then we’re also the ones to scream for constants and variables and other features only because we’ve never stopped to question this 90s-style coding.
The unnatural, more modern way of writing CSS
Targeting these three areas would help us move to a more modern way of writing style sheets, one that has a straightforward but powerful way to sort declarations, includes a plan for ordering selectors, and minimizes declaration repetition.
In this article, we’ve outlined some options for us to adhere to this more modern way:
Sort declarations alphabetically.
Use an existing order system or standardize and follow a new selector order system.
Try to use declarations just once.
Get assistance through tools.
And yet there’s still great potential to improve in all of these areas. The potential, then, is what we should close with. While I’ve emphasized our “no changes since the 90s” way of writing CSS, and stressed the need for robust practices, we need more proposals, studies, and conversations around what practices are most beneficial. Beneficial in terms of writing better, more consistent CSS, but also in terms of balancing our sense of craft (our mastery of our profession) with a high degree of efficiency (automating when it’s appropriate). Striving to achieve this balance will help ensure that developers twenty years from now won’t have to write rants about hangovers from the 2010s.
http://ift.tt/2H6YyWz
0 notes
pattersondonaldblk5 · 7 years ago
Text
We Write CSS Like We Did in the 90s, and Yes, It’s Silly
As web developers, we marvel at technology. We enjoy the many tools that help with our work: multipurpose editors, frameworks, libraries, polyfills and shims, content management systems, preprocessors, build and deployment tools, development consoles, production monitors—the list goes on.
Our delight in these tools is so strong that no one questions whether a small website actually requires any of them. Tool obesity is the new WYSIWYG—the web developers who can’t do without their frameworks and preprocessors are no better than our peers from the 1990s who couldn’t do without FrontPage or Dreamweaver. It is true that these tools have improved our lives as developers in many ways. At the same time, they have perhaps also prevented us from improving our basic skills.
I want to talk about one of those skills: the craft of writing CSS. Not of using CSS preprocessors or postprocessors, but of writing CSS itself. Why? Because CSS is second in importance only to HTML in web development, and because no one needs processors to build a site or app.
Most of all, I want to talk about this because when it comes to writing CSS, it often seems that we have learned nothing since the 1990s. We still write CSS the natural way, with no advances in sorting declarations or selectors and no improvements in writing DRY CSS.
Instead, many developers argue fiercely about each of these topics. Others simply dig in their heels and refuse to change. And a third cohort protests even the discussion of these topics.
I don’t care that developers do this. But I do care about our craft. And I care that we, as a profession, are ignoring simple ways to improve our work.
Let’s talk about this more after the code break.
Here’s unsorted, unoptimized CSS from Amazon in 2003.
.serif { font-family: times, serif; font-size: small; } .sans { font-family: verdana, arial, helvetica, sans-serif; font-size: small; } .small { font-family: verdana, arial, helvetica, sans-serif; font-size: x-small; } .h1 { font-family: verdana, arial, helvetica, sans-serif; color: #CC6600; font-size: small; } .h3color { font-family: verdana, arial, helvetica, sans-serif; color: #CC6600; font-size: x-small; } .tiny { font-family: verdana, arial, helvetica, sans-serif; font-size: xx-small; } .listprice { font-family: arial, verdana, sans-serif; text-decoration: line-through; font-size: x-small; } .price { font-family: verdana, arial, helvetica, sans-serif; color: #990000; font-size: x-small; } .attention { background-color: #FFFFD5; }
And here’s CSS from contemporary Amazon:
.a-box { display: block; border-radius: 4px; border: 1px #ddd solid; background-color: #fff; } .a-box .a-box-inner { border-radius: 4px; position: relative; padding: 14px 18px; } .a-box-thumbnail { display: inline-block; } .a-box-thumbnail .a-box-inner { padding: 0 !important; } .a-box-thumbnail .a-box-inner img { border-radius: 4px; } .a-box-title { overflow: hidden; } .a-box-title .a-box-inner { overflow: hidden; padding: 12px 18px 11px; background: #f0f0f0; }
Just as in 2003, the CSS is unsorted and unoptimized. Did we learn anything over the past 15 years? Is this really the best CSS we can write?
Let’s look at three areas where I believe we can easily improve the way we do our work: declaration sorting, selector sorting, and declaration repetition.
Declaration sorting
The 90s web developer, if he or she wrote CSS, wrote CSS as it occurred to them. Without sense or order—with no direction whatsoever. The same was true of last decade’s developer. The same is true of today’s developer, whether novice or expert.
.foo { font: arial, sans-serif; background: #abc; margin: 1em; text-align: center; letter-spacing: 1px; -x-yaddayadda: yes; }
The only difference between now and then: today’s expert developer uses eight variables, because “that’s how you do it” (even with one-pagers) and because at some point in their life they may need them. In twenty-something years of web development we have somehow not managed to make our CSS consistent and easier to work on by establishing the (or even a) common sense standard to sort declarations.
(If this sounds harsh, it’s because it’s true. Developers condemn selectors, shorthands, !important, and other useful aspects of CSS rather than concede that they don’t even know how to sort their declarations.)
In reality, the issue is dead simple: Declarations should be sorted alphabetically. Period.
Why?
For one, sorting makes collaborating easier.
Untrained developers can do it. Non-English speakers (such as this author) can do it. I wouldn’t be surprised to learn that even houseplants can do it.
For another reason, alphabetical sorting can be automated. What’s that? Yes, one can use or write little scripts (such as CSS Declaration Sorter) to sort declarations.
Given the ease of sorting, and its benefits, the current state of affairs borders on the ridiculous, making it tempting to ignore our peers who don’t sort declarations, and to ban from our lives those who argue that it’s easier—or even logical—not to sort alphabetically but instead to sort based on 1) box dimensions, 2) colors, 3) grid- or flexbox-iness, 4) mood, 5) what they ate for breakfast, or some equally random basis.
With this issue settled (if somewhat provocatively), on to our second problem from the 90s.
Selector sorting
The situation concerning selectors is quite similar. Almost since 1994, developers have written selectors and rules as they occurred to them. Perhaps they’ve moved them around (“Oh, that belongs with the nav”). Perhaps they’ve refactored their style sheets (“Oh, strange that site styles appear amidst notification styles”). But standardizing the order—no.
Let’s take a step back and assume that order does matter, not just for aesthetics as one might think, but for collaboration. As an example, think of the letters below as selectors. Which list would be easiest to work with?
c, b · a · a, b · c, d · d, c, a · e · a c · b · a, b · a · c, d · a, c, d · a · e a, b · a, c, d · a · b, c · c, d · e
The fact that one selector (a) was a duplicate that only got discovered and merged in the last row perhaps gives away my preference. But then, if you wanted to add d, e to the list, wouldn’t the order of the third row make placing the new selector easier than placing it in either of the first two rows?
This example gets at the two issues caused by not sorting selectors:
No one knows where to add new selectors, creating a black hole in the workflow.
There’s a higher chance of both selector repetition and duplication of rules with the same selectors.
Both problems get compounded in larger projects and larger teams. Both problems have haunted us since the 90s. Both problems get fixed by standardizing—through coding guidelines—how selectors should be ordered.
The answer in this case is not as trivial as sorting alphabetically (although we could play with the idea—the cognitive ease of alphabetical selector sorting may make it worth trying). But we can take a path similar to how the HTML spec roughly groups elements, so that we first define sections, and then grouping elements, text elements, etc. (That’s also the approach of at least one draft, the author’s.)
The point is that ideal selector sorting doesn’t just occur naturally and automatically. We can benefit from putting more thought into this problem.
Declaration repetition
Our third hangover from the 90s is that there is and has always been an insane amount of repetition in our style sheets. According to one analysis of more than 200 websites, a median of 66% of all declarations are redundant, and the repetition rate goes as high as 92%—meaning that, in this study at least, the typical website uses each declaration at least three times and some up to ten times.
As shown by a list of some sample sites I compiled, declaration repetition has indeed been bad from the start and has even increased slightly over the years.
Yes, there are reasons for repetition: notably for different target media (we may repeat ourselves for screen, print, or different viewport sizes) and, occasionally, for the cascade. That is why a repetition rate of 10–20% seems to be acceptable. But the degree of repetition we observe right now is not acceptable—it’s an unoptimized mess that goes mostly unnoticed.
What’s the solution here? One possibility is to use declarations just once. We’ve seen with a sample optimization of Yandex’s large-scale site that this can lead to slightly more unwieldy style sheets, but we also know that in many other cases it does make them smaller and more compact.
This approach of using declarations just once has at least three benefits:
It reduces repetition to a more acceptable amount.
It reduces the pseudo need for variables.
Excluding outliers like Yandex, it reduces file size and payload (10–20% according to my own experience—we looked at the effects years ago at Google).
No matter what practice we as a field come up with—whether to use declarations just once or follow a different path—the current level of “natural repetition” we face on sample websites is too high. We shouldn’t need to remind ourselves not to repeat ourselves if we repeat code up to nine times, and it’s getting outright pathetic—again excuse the strong language—if then we’re also the ones to scream for constants and variables and other features only because we’ve never stopped to question this 90s-style coding.
The unnatural, more modern way of writing CSS
Targeting these three areas would help us move to a more modern way of writing style sheets, one that has a straightforward but powerful way to sort declarations, includes a plan for ordering selectors, and minimizes declaration repetition.
In this article, we’ve outlined some options for us to adhere to this more modern way:
Sort declarations alphabetically.
Use an existing order system or standardize and follow a new selector order system.
Try to use declarations just once.
Get assistance through tools.
And yet there’s still great potential to improve in all of these areas. The potential, then, is what we should close with. While I’ve emphasized our “no changes since the 90s” way of writing CSS, and stressed the need for robust practices, we need more proposals, studies, and conversations around what practices are most beneficial. Beneficial in terms of writing better, more consistent CSS, but also in terms of balancing our sense of craft (our mastery of our profession) with a high degree of efficiency (automating when it’s appropriate). Striving to achieve this balance will help ensure that developers twenty years from now won’t have to write rants about hangovers from the 2010s.
http://ift.tt/2H6YyWz
0 notes
waltercostellone · 7 years ago
Text
We Write CSS Like We Did in the 90s, and Yes, It’s Silly
As web developers, we marvel at technology. We enjoy the many tools that help with our work: multipurpose editors, frameworks, libraries, polyfills and shims, content management systems, preprocessors, build and deployment tools, development consoles, production monitors—the list goes on.
Our delight in these tools is so strong that no one questions whether a small website actually requires any of them. Tool obesity is the new WYSIWYG—the web developers who can’t do without their frameworks and preprocessors are no better than our peers from the 1990s who couldn’t do without FrontPage or Dreamweaver. It is true that these tools have improved our lives as developers in many ways. At the same time, they have perhaps also prevented us from improving our basic skills.
I want to talk about one of those skills: the craft of writing CSS. Not of using CSS preprocessors or postprocessors, but of writing CSS itself. Why? Because CSS is second in importance only to HTML in web development, and because no one needs processors to build a site or app.
Most of all, I want to talk about this because when it comes to writing CSS, it often seems that we have learned nothing since the 1990s. We still write CSS the natural way, with no advances in sorting declarations or selectors and no improvements in writing DRY CSS.
Instead, many developers argue fiercely about each of these topics. Others simply dig in their heels and refuse to change. And a third cohort protests even the discussion of these topics.
I don’t care that developers do this. But I do care about our craft. And I care that we, as a profession, are ignoring simple ways to improve our work.
Let’s talk about this more after the code break.
Here’s unsorted, unoptimized CSS from Amazon in 2003.
.serif { font-family: times, serif; font-size: small; } .sans { font-family: verdana, arial, helvetica, sans-serif; font-size: small; } .small { font-family: verdana, arial, helvetica, sans-serif; font-size: x-small; } .h1 { font-family: verdana, arial, helvetica, sans-serif; color: #CC6600; font-size: small; } .h3color { font-family: verdana, arial, helvetica, sans-serif; color: #CC6600; font-size: x-small; } .tiny { font-family: verdana, arial, helvetica, sans-serif; font-size: xx-small; } .listprice { font-family: arial, verdana, sans-serif; text-decoration: line-through; font-size: x-small; } .price { font-family: verdana, arial, helvetica, sans-serif; color: #990000; font-size: x-small; } .attention { background-color: #FFFFD5; }
And here’s CSS from contemporary Amazon:
.a-box { display: block; border-radius: 4px; border: 1px #ddd solid; background-color: #fff; } .a-box .a-box-inner { border-radius: 4px; position: relative; padding: 14px 18px; } .a-box-thumbnail { display: inline-block; } .a-box-thumbnail .a-box-inner { padding: 0 !important; } .a-box-thumbnail .a-box-inner img { border-radius: 4px; } .a-box-title { overflow: hidden; } .a-box-title .a-box-inner { overflow: hidden; padding: 12px 18px 11px; background: #f0f0f0; }
Just as in 2003, the CSS is unsorted and unoptimized. Did we learn anything over the past 15 years? Is this really the best CSS we can write?
Let’s look at three areas where I believe we can easily improve the way we do our work: declaration sorting, selector sorting, and declaration repetition.
Declaration sorting
The 90s web developer, if he or she wrote CSS, wrote CSS as it occurred to them. Without sense or order—with no direction whatsoever. The same was true of last decade’s developer. The same is true of today’s developer, whether novice or expert.
.foo { font: arial, sans-serif; background: #abc; margin: 1em; text-align: center; letter-spacing: 1px; -x-yaddayadda: yes; }
The only difference between now and then: today’s expert developer uses eight variables, because “that’s how you do it” (even with one-pagers) and because at some point in their life they may need them. In twenty-something years of web development we have somehow not managed to make our CSS consistent and easier to work on by establishing the (or even a) common sense standard to sort declarations.
(If this sounds harsh, it’s because it’s true. Developers condemn selectors, shorthands, !important, and other useful aspects of CSS rather than concede that they don’t even know how to sort their declarations.)
In reality, the issue is dead simple: Declarations should be sorted alphabetically. Period.
Why?
For one, sorting makes collaborating easier.
Untrained developers can do it. Non-English speakers (such as this author) can do it. I wouldn’t be surprised to learn that even houseplants can do it.
For another reason, alphabetical sorting can be automated. What’s that? Yes, one can use or write little scripts (such as CSS Declaration Sorter) to sort declarations.
Given the ease of sorting, and its benefits, the current state of affairs borders on the ridiculous, making it tempting to ignore our peers who don’t sort declarations, and to ban from our lives those who argue that it’s easier—or even logical—not to sort alphabetically but instead to sort based on 1) box dimensions, 2) colors, 3) grid- or flexbox-iness, 4) mood, 5) what they ate for breakfast, or some equally random basis.
With this issue settled (if somewhat provocatively), on to our second problem from the 90s.
Selector sorting
The situation concerning selectors is quite similar. Almost since 1994, developers have written selectors and rules as they occurred to them. Perhaps they’ve moved them around (“Oh, that belongs with the nav”). Perhaps they’ve refactored their style sheets (“Oh, strange that site styles appear amidst notification styles”). But standardizing the order—no.
Let’s take a step back and assume that order does matter, not just for aesthetics as one might think, but for collaboration. As an example, think of the letters below as selectors. Which list would be easiest to work with?
c, b · a · a, b · c, d · d, c, a · e · a c · b · a, b · a · c, d · a, c, d · a · e a, b · a, c, d · a · b, c · c, d · e
The fact that one selector (a) was a duplicate that only got discovered and merged in the last row perhaps gives away my preference. But then, if you wanted to add d, e to the list, wouldn’t the order of the third row make placing the new selector easier than placing it in either of the first two rows?
This example gets at the two issues caused by not sorting selectors:
No one knows where to add new selectors, creating a black hole in the workflow.
There’s a higher chance of both selector repetition and duplication of rules with the same selectors.
Both problems get compounded in larger projects and larger teams. Both problems have haunted us since the 90s. Both problems get fixed by standardizing—through coding guidelines—how selectors should be ordered.
The answer in this case is not as trivial as sorting alphabetically (although we could play with the idea—the cognitive ease of alphabetical selector sorting may make it worth trying). But we can take a path similar to how the HTML spec roughly groups elements, so that we first define sections, and then grouping elements, text elements, etc. (That’s also the approach of at least one draft, the author’s.)
The point is that ideal selector sorting doesn’t just occur naturally and automatically. We can benefit from putting more thought into this problem.
Declaration repetition
Our third hangover from the 90s is that there is and has always been an insane amount of repetition in our style sheets. According to one analysis of more than 200 websites, a median of 66% of all declarations are redundant, and the repetition rate goes as high as 92%—meaning that, in this study at least, the typical website uses each declaration at least three times and some up to ten times.
As shown by a list of some sample sites I compiled, declaration repetition has indeed been bad from the start and has even increased slightly over the years.
Yes, there are reasons for repetition: notably for different target media (we may repeat ourselves for screen, print, or different viewport sizes) and, occasionally, for the cascade. That is why a repetition rate of 10–20% seems to be acceptable. But the degree of repetition we observe right now is not acceptable—it’s an unoptimized mess that goes mostly unnoticed.
What’s the solution here? One possibility is to use declarations just once. We’ve seen with a sample optimization of Yandex’s large-scale site that this can lead to slightly more unwieldy style sheets, but we also know that in many other cases it does make them smaller and more compact.
This approach of using declarations just once has at least three benefits:
It reduces repetition to a more acceptable amount.
It reduces the pseudo need for variables.
Excluding outliers like Yandex, it reduces file size and payload (10–20% according to my own experience—we looked at the effects years ago at Google).
No matter what practice we as a field come up with—whether to use declarations just once or follow a different path—the current level of “natural repetition” we face on sample websites is too high. We shouldn’t need to remind ourselves not to repeat ourselves if we repeat code up to nine times, and it’s getting outright pathetic—again excuse the strong language—if then we’re also the ones to scream for constants and variables and other features only because we’ve never stopped to question this 90s-style coding.
The unnatural, more modern way of writing CSS
Targeting these three areas would help us move to a more modern way of writing style sheets, one that has a straightforward but powerful way to sort declarations, includes a plan for ordering selectors, and minimizes declaration repetition.
In this article, we’ve outlined some options for us to adhere to this more modern way:
Sort declarations alphabetically.
Use an existing order system or standardize and follow a new selector order system.
Try to use declarations just once.
Get assistance through tools.
And yet there’s still great potential to improve in all of these areas. The potential, then, is what we should close with. While I’ve emphasized our “no changes since the 90s” way of writing CSS, and stressed the need for robust practices, we need more proposals, studies, and conversations around what practices are most beneficial. Beneficial in terms of writing better, more consistent CSS, but also in terms of balancing our sense of craft (our mastery of our profession) with a high degree of efficiency (automating when it’s appropriate). Striving to achieve this balance will help ensure that developers twenty years from now won’t have to write rants about hangovers from the 2010s.
http://ift.tt/2H6YyWz
0 notes
jeanshesallenberger · 7 years ago
Text
We Write CSS Like We Did in the 90s, and Yes, It’s Silly
As web developers, we marvel at technology. We enjoy the many tools that help with our work: multipurpose editors, frameworks, libraries, polyfills and shims, content management systems, preprocessors, build and deployment tools, development consoles, production monitors—the list goes on.
Our delight in these tools is so strong that no one questions whether a small website actually requires any of them. Tool obesity is the new WYSIWYG—the web developers who can’t do without their frameworks and preprocessors are no better than our peers from the 1990s who couldn’t do without FrontPage or Dreamweaver. It is true that these tools have improved our lives as developers in many ways. At the same time, they have perhaps also prevented us from improving our basic skills.
I want to talk about one of those skills: the craft of writing CSS. Not of using CSS preprocessors or postprocessors, but of writing CSS itself. Why? Because CSS is second in importance only to HTML in web development, and because no one needs processors to build a site or app.
Most of all, I want to talk about this because when it comes to writing CSS, it often seems that we have learned nothing since the 1990s. We still write CSS the natural way, with no advances in sorting declarations or selectors and no improvements in writing DRY CSS.
Instead, many developers argue fiercely about each of these topics. Others simply dig in their heels and refuse to change. And a third cohort protests even the discussion of these topics.
I don’t care that developers do this. But I do care about our craft. And I care that we, as a profession, are ignoring simple ways to improve our work.
Let’s talk about this more after the code break.
Here’s unsorted, unoptimized CSS from Amazon in 2003.
.serif { font-family: times, serif; font-size: small; } .sans { font-family: verdana, arial, helvetica, sans-serif; font-size: small; } .small { font-family: verdana, arial, helvetica, sans-serif; font-size: x-small; } .h1 { font-family: verdana, arial, helvetica, sans-serif; color: #CC6600; font-size: small; } .h3color { font-family: verdana, arial, helvetica, sans-serif; color: #CC6600; font-size: x-small; } .tiny { font-family: verdana, arial, helvetica, sans-serif; font-size: xx-small; } .listprice { font-family: arial, verdana, sans-serif; text-decoration: line-through; font-size: x-small; } .price { font-family: verdana, arial, helvetica, sans-serif; color: #990000; font-size: x-small; } .attention { background-color: #FFFFD5; }
And here’s CSS from contemporary Amazon:
.a-box { display: block; border-radius: 4px; border: 1px #ddd solid; background-color: #fff; } .a-box .a-box-inner { border-radius: 4px; position: relative; padding: 14px 18px; } .a-box-thumbnail { display: inline-block; } .a-box-thumbnail .a-box-inner { padding: 0 !important; } .a-box-thumbnail .a-box-inner img { border-radius: 4px; } .a-box-title { overflow: hidden; } .a-box-title .a-box-inner { overflow: hidden; padding: 12px 18px 11px; background: #f0f0f0; }
Just as in 2003, the CSS is unsorted and unoptimized. Did we learn anything over the past 15 years? Is this really the best CSS we can write?
Let’s look at three areas where I believe we can easily improve the way we do our work: declaration sorting, selector sorting, and declaration repetition.
Declaration sorting
The 90s web developer, if he or she wrote CSS, wrote CSS as it occurred to them. Without sense or order—with no direction whatsoever. The same was true of last decade’s developer. The same is true of today’s developer, whether novice or expert.
.foo { font: arial, sans-serif; background: #abc; margin: 1em; text-align: center; letter-spacing: 1px; -x-yaddayadda: yes; }
The only difference between now and then: today’s expert developer uses eight variables, because “that’s how you do it” (even with one-pagers) and because at some point in their life they may need them. In twenty-something years of web development we have somehow not managed to make our CSS consistent and easier to work on by establishing the (or even a) common sense standard to sort declarations.
(If this sounds harsh, it’s because it’s true. Developers condemn selectors, shorthands, !important, and other useful aspects of CSS rather than concede that they don’t even know how to sort their declarations.)
In reality, the issue is dead simple: Declarations should be sorted alphabetically. Period.
Why?
For one, sorting makes collaborating easier.
Untrained developers can do it. Non-English speakers (such as this author) can do it. I wouldn’t be surprised to learn that even houseplants can do it.
For another reason, alphabetical sorting can be automated. What’s that? Yes, one can use or write little scripts (such as CSS Declaration Sorter) to sort declarations.
Given the ease of sorting, and its benefits, the current state of affairs borders on the ridiculous, making it tempting to ignore our peers who don’t sort declarations, and to ban from our lives those who argue that it’s easier—or even logical—not to sort alphabetically but instead to sort based on 1) box dimensions, 2) colors, 3) grid- or flexbox-iness, 4) mood, 5) what they ate for breakfast, or some equally random basis.
With this issue settled (if somewhat provocatively), on to our second problem from the 90s.
Selector sorting
The situation concerning selectors is quite similar. Almost since 1994, developers have written selectors and rules as they occurred to them. Perhaps they’ve moved them around (“Oh, that belongs with the nav”). Perhaps they’ve refactored their style sheets (“Oh, strange that site styles appear amidst notification styles”). But standardizing the order—no.
Let’s take a step back and assume that order does matter, not just for aesthetics as one might think, but for collaboration. As an example, think of the letters below as selectors. Which list would be easiest to work with?
c, b · a · a, b · c, d · d, c, a · e · a c · b · a, b · a · c, d · a, c, d · a · e a, b · a, c, d · a · b, c · c, d · e
The fact that one selector (a) was a duplicate that only got discovered and merged in the last row perhaps gives away my preference. But then, if you wanted to add d, e to the list, wouldn’t the order of the third row make placing the new selector easier than placing it in either of the first two rows?
This example gets at the two issues caused by not sorting selectors:
No one knows where to add new selectors, creating a black hole in the workflow.
There’s a higher chance of both selector repetition and duplication of rules with the same selectors.
Both problems get compounded in larger projects and larger teams. Both problems have haunted us since the 90s. Both problems get fixed by standardizing—through coding guidelines—how selectors should be ordered.
The answer in this case is not as trivial as sorting alphabetically (although we could play with the idea—the cognitive ease of alphabetical selector sorting may make it worth trying). But we can take a path similar to how the HTML spec roughly groups elements, so that we first define sections, and then grouping elements, text elements, etc. (That’s also the approach of at least one draft, the author’s.)
The point is that ideal selector sorting doesn’t just occur naturally and automatically. We can benefit from putting more thought into this problem.
Declaration repetition
Our third hangover from the 90s is that there is and has always been an insane amount of repetition in our style sheets. According to one analysis of more than 200 websites, a median of 66% of all declarations are redundant, and the repetition rate goes as high as 92%—meaning that, in this study at least, the typical website uses each declaration at least three times and some up to ten times.
As shown by a list of some sample sites I compiled, declaration repetition has indeed been bad from the start and has even increased slightly over the years.
Yes, there are reasons for repetition: notably for different target media (we may repeat ourselves for screen, print, or different viewport sizes) and, occasionally, for the cascade. That is why a repetition rate of 10–20% seems to be acceptable. But the degree of repetition we observe right now is not acceptable—it’s an unoptimized mess that goes mostly unnoticed.
What’s the solution here? One possibility is to use declarations just once. We’ve seen with a sample optimization of Yandex’s large-scale site that this can lead to slightly more unwieldy style sheets, but we also know that in many other cases it does make them smaller and more compact.
This approach of using declarations just once has at least three benefits:
It reduces repetition to a more acceptable amount.
It reduces the pseudo need for variables.
Excluding outliers like Yandex, it reduces file size and payload (10–20% according to my own experience—we looked at the effects years ago at Google).
No matter what practice we as a field come up with—whether to use declarations just once or follow a different path—the current level of “natural repetition” we face on sample websites is too high. We shouldn’t need to remind ourselves not to repeat ourselves if we repeat code up to nine times, and it’s getting outright pathetic—again excuse the strong language—if then we’re also the ones to scream for constants and variables and other features only because we’ve never stopped to question this 90s-style coding.
The unnatural, more modern way of writing CSS
Targeting these three areas would help us move to a more modern way of writing style sheets, one that has a straightforward but powerful way to sort declarations, includes a plan for ordering selectors, and minimizes declaration repetition.
In this article, we’ve outlined some options for us to adhere to this more modern way:
Sort declarations alphabetically.
Use an existing order system or standardize and follow a new selector order system.
Try to use declarations just once.
Get assistance through tools.
And yet there’s still great potential to improve in all of these areas. The potential, then, is what we should close with. While I’ve emphasized our “no changes since the 90s” way of writing CSS, and stressed the need for robust practices, we need more proposals, studies, and conversations around what practices are most beneficial. Beneficial in terms of writing better, more consistent CSS, but also in terms of balancing our sense of craft (our mastery of our profession) with a high degree of efficiency (automating when it’s appropriate). Striving to achieve this balance will help ensure that developers twenty years from now won’t have to write rants about hangovers from the 2010s.
http://ift.tt/2H6YyWz
0 notes
mariaaklnthony · 7 years ago
Text
We Write CSS Like We Did in the 90s, and Yes, It’s Silly
As web developers, we marvel at technology. We enjoy the many tools that help with our work: multipurpose editors, frameworks, libraries, polyfills and shims, content management systems, preprocessors, build and deployment tools, development consoles, production monitors—the list goes on.
Our delight in these tools is so strong that no one questions whether a small website actually requires any of them. Tool obesity is the new WYSIWYG—the web developers who can’t do without their frameworks and preprocessors are no better than our peers from the 1990s who couldn’t do without FrontPage or Dreamweaver. It is true that these tools have improved our lives as developers in many ways. At the same time, they have perhaps also prevented us from improving our basic skills.
I want to talk about one of those skills: the craft of writing CSS. Not of using CSS preprocessors or postprocessors, but of writing CSS itself. Why? Because CSS is second in importance only to HTML in web development, and because no one needs processors to build a site or app.
Most of all, I want to talk about this because when it comes to writing CSS, it often seems that we have learned nothing since the 1990s. We still write CSS the natural way, with no advances in sorting declarations or selectors and no improvements in writing DRY CSS.
Instead, many developers argue fiercely about each of these topics. Others simply dig in their heels and refuse to change. And a third cohort protests even the discussion of these topics.
I don’t care that developers do this. But I do care about our craft. And I care that we, as a profession, are ignoring simple ways to improve our work.
Let’s talk about this more after the code break.
Here’s unsorted, unoptimized CSS from Amazon in 2003.
.serif { font-family: times, serif; font-size: small; } .sans { font-family: verdana, arial, helvetica, sans-serif; font-size: small; } .small { font-family: verdana, arial, helvetica, sans-serif; font-size: x-small; } .h1 { font-family: verdana, arial, helvetica, sans-serif; color: #CC6600; font-size: small; } .h3color { font-family: verdana, arial, helvetica, sans-serif; color: #CC6600; font-size: x-small; } .tiny { font-family: verdana, arial, helvetica, sans-serif; font-size: xx-small; } .listprice { font-family: arial, verdana, sans-serif; text-decoration: line-through; font-size: x-small; } .price { font-family: verdana, arial, helvetica, sans-serif; color: #990000; font-size: x-small; } .attention { background-color: #FFFFD5; }
And here’s CSS from contemporary Amazon:
.a-box { display: block; border-radius: 4px; border: 1px #ddd solid; background-color: #fff; } .a-box .a-box-inner { border-radius: 4px; position: relative; padding: 14px 18px; } .a-box-thumbnail { display: inline-block; } .a-box-thumbnail .a-box-inner { padding: 0 !important; } .a-box-thumbnail .a-box-inner img { border-radius: 4px; } .a-box-title { overflow: hidden; } .a-box-title .a-box-inner { overflow: hidden; padding: 12px 18px 11px; background: #f0f0f0; }
Just as in 2003, the CSS is unsorted and unoptimized. Did we learn anything over the past 15 years? Is this really the best CSS we can write?
Let’s look at three areas where I believe we can easily improve the way we do our work: declaration sorting, selector sorting, and declaration repetition.
Declaration sorting
The 90s web developer, if he or she wrote CSS, wrote CSS as it occurred to them. Without sense or order—with no direction whatsoever. The same was true of last decade’s developer. The same is true of today’s developer, whether novice or expert.
.foo { font: arial, sans-serif; background: #abc; margin: 1em; text-align: center; letter-spacing: 1px; -x-yaddayadda: yes; }
The only difference between now and then: today’s expert developer uses eight variables, because “that’s how you do it” (even with one-pagers) and because at some point in their life they may need them. In twenty-something years of web development we have somehow not managed to make our CSS consistent and easier to work on by establishing the (or even a) common sense standard to sort declarations.
(If this sounds harsh, it’s because it’s true. Developers condemn selectors, shorthands, !important, and other useful aspects of CSS rather than concede that they don’t even know how to sort their declarations.)
In reality, the issue is dead simple: Declarations should be sorted alphabetically. Period.
Why?
For one, sorting makes collaborating easier.
Untrained developers can do it. Non-English speakers (such as this author) can do it. I wouldn’t be surprised to learn that even houseplants can do it.
For another reason, alphabetical sorting can be automated. What’s that? Yes, one can use or write little scripts (such as CSS Declaration Sorter) to sort declarations.
Given the ease of sorting, and its benefits, the current state of affairs borders on the ridiculous, making it tempting to ignore our peers who don’t sort declarations, and to ban from our lives those who argue that it’s easier—or even logical—not to sort alphabetically but instead to sort based on 1) box dimensions, 2) colors, 3) grid- or flexbox-iness, 4) mood, 5) what they ate for breakfast, or some equally random basis.
With this issue settled (if somewhat provocatively), on to our second problem from the 90s.
Selector sorting
The situation concerning selectors is quite similar. Almost since 1994, developers have written selectors and rules as they occurred to them. Perhaps they’ve moved them around (“Oh, that belongs with the nav”). Perhaps they’ve refactored their style sheets (“Oh, strange that site styles appear amidst notification styles”). But standardizing the order—no.
Let’s take a step back and assume that order does matter, not just for aesthetics as one might think, but for collaboration. As an example, think of the letters below as selectors. Which list would be easiest to work with?
c, b · a · a, b · c, d · d, c, a · e · a c · b · a, b · a · c, d · a, c, d · a · e a, b · a, c, d · a · b, c · c, d · e
The fact that one selector (a) was a duplicate that only got discovered and merged in the last row perhaps gives away my preference. But then, if you wanted to add d, e to the list, wouldn’t the order of the third row make placing the new selector easier than placing it in either of the first two rows?
This example gets at the two issues caused by not sorting selectors:
No one knows where to add new selectors, creating a black hole in the workflow.
There’s a higher chance of both selector repetition and duplication of rules with the same selectors.
Both problems get compounded in larger projects and larger teams. Both problems have haunted us since the 90s. Both problems get fixed by standardizing—through coding guidelines—how selectors should be ordered.
The answer in this case is not as trivial as sorting alphabetically (although we could play with the idea—the cognitive ease of alphabetical selector sorting may make it worth trying). But we can take a path similar to how the HTML spec roughly groups elements, so that we first define sections, and then grouping elements, text elements, etc. (That’s also the approach of at least one draft, the author’s.)
The point is that ideal selector sorting doesn’t just occur naturally and automatically. We can benefit from putting more thought into this problem.
Declaration repetition
Our third hangover from the 90s is that there is and has always been an insane amount of repetition in our style sheets. According to one analysis of more than 200 websites, a median of 66% of all declarations are redundant, and the repetition rate goes as high as 92%—meaning that, in this study at least, the typical website uses each declaration at least three times and some up to ten times.
As shown by a list of some sample sites I compiled, declaration repetition has indeed been bad from the start and has even increased slightly over the years.
Yes, there are reasons for repetition: notably for different target media (we may repeat ourselves for screen, print, or different viewport sizes) and, occasionally, for the cascade. That is why a repetition rate of 10–20% seems to be acceptable. But the degree of repetition we observe right now is not acceptable—it’s an unoptimized mess that goes mostly unnoticed.
What’s the solution here? One possibility is to use declarations just once. We’ve seen with a sample optimization of Yandex’s large-scale site that this can lead to slightly more unwieldy style sheets, but we also know that in many other cases it does make them smaller and more compact.
This approach of using declarations just once has at least three benefits:
It reduces repetition to a more acceptable amount.
It reduces the pseudo need for variables.
Excluding outliers like Yandex, it reduces file size and payload (10–20% according to my own experience—we looked at the effects years ago at Google).
No matter what practice we as a field come up with—whether to use declarations just once or follow a different path—the current level of “natural repetition” we face on sample websites is too high. We shouldn’t need to remind ourselves not to repeat ourselves if we repeat code up to nine times, and it’s getting outright pathetic—again excuse the strong language—if then we’re also the ones to scream for constants and variables and other features only because we’ve never stopped to question this 90s-style coding.
The unnatural, more modern way of writing CSS
Targeting these three areas would help us move to a more modern way of writing style sheets, one that has a straightforward but powerful way to sort declarations, includes a plan for ordering selectors, and minimizes declaration repetition.
In this article, we’ve outlined some options for us to adhere to this more modern way:
Sort declarations alphabetically.
Use an existing order system or standardize and follow a new selector order system.
Try to use declarations just once.
Get assistance through tools.
And yet there’s still great potential to improve in all of these areas. The potential, then, is what we should close with. While I’ve emphasized our “no changes since the 90s” way of writing CSS, and stressed the need for robust practices, we need more proposals, studies, and conversations around what practices are most beneficial. Beneficial in terms of writing better, more consistent CSS, but also in terms of balancing our sense of craft (our mastery of our profession) with a high degree of efficiency (automating when it’s appropriate). Striving to achieve this balance will help ensure that developers twenty years from now won’t have to write rants about hangovers from the 2010s.
http://ift.tt/2H6YyWz
0 notes
joannlyfgnch · 7 years ago
Text
We Write CSS Like We Did in the 90s, and Yes, It’s Silly
As web developers, we marvel at technology. We enjoy the many tools that help with our work: multipurpose editors, frameworks, libraries, polyfills and shims, content management systems, preprocessors, build and deployment tools, development consoles, production monitors—the list goes on.
Our delight in these tools is so strong that no one questions whether a small website actually requires any of them. Tool obesity is the new WYSIWYG—the web developers who can’t do without their frameworks and preprocessors are no better than our peers from the 1990s who couldn’t do without FrontPage or Dreamweaver. It is true that these tools have improved our lives as developers in many ways. At the same time, they have perhaps also prevented us from improving our basic skills.
I want to talk about one of those skills: the craft of writing CSS. Not of using CSS preprocessors or postprocessors, but of writing CSS itself. Why? Because CSS is second in importance only to HTML in web development, and because no one needs processors to build a site or app.
Most of all, I want to talk about this because when it comes to writing CSS, it often seems that we have learned nothing since the 1990s. We still write CSS the natural way, with no advances in sorting declarations or selectors and no improvements in writing DRY CSS.
Instead, many developers argue fiercely about each of these topics. Others simply dig in their heels and refuse to change. And a third cohort protests even the discussion of these topics.
I don’t care that developers do this. But I do care about our craft. And I care that we, as a profession, are ignoring simple ways to improve our work.
Let’s talk about this more after the code break.
Here’s unsorted, unoptimized CSS from Amazon in 2003.
.serif { font-family: times, serif; font-size: small; } .sans { font-family: verdana, arial, helvetica, sans-serif; font-size: small; } .small { font-family: verdana, arial, helvetica, sans-serif; font-size: x-small; } .h1 { font-family: verdana, arial, helvetica, sans-serif; color: #CC6600; font-size: small; } .h3color { font-family: verdana, arial, helvetica, sans-serif; color: #CC6600; font-size: x-small; } .tiny { font-family: verdana, arial, helvetica, sans-serif; font-size: xx-small; } .listprice { font-family: arial, verdana, sans-serif; text-decoration: line-through; font-size: x-small; } .price { font-family: verdana, arial, helvetica, sans-serif; color: #990000; font-size: x-small; } .attention { background-color: #FFFFD5; }
And here’s CSS from contemporary Amazon:
.a-box { display: block; border-radius: 4px; border: 1px #ddd solid; background-color: #fff; } .a-box .a-box-inner { border-radius: 4px; position: relative; padding: 14px 18px; } .a-box-thumbnail { display: inline-block; } .a-box-thumbnail .a-box-inner { padding: 0 !important; } .a-box-thumbnail .a-box-inner img { border-radius: 4px; } .a-box-title { overflow: hidden; } .a-box-title .a-box-inner { overflow: hidden; padding: 12px 18px 11px; background: #f0f0f0; }
Just as in 2003, the CSS is unsorted and unoptimized. Did we learn anything over the past 15 years? Is this really the best CSS we can write?
Let’s look at three areas where I believe we can easily improve the way we do our work: declaration sorting, selector sorting, and declaration repetition.
Declaration sorting
The 90s web developer, if he or she wrote CSS, wrote CSS as it occurred to them. Without sense or order—with no direction whatsoever. The same was true of last decade’s developer. The same is true of today’s developer, whether novice or expert.
.foo { font: arial, sans-serif; background: #abc; margin: 1em; text-align: center; letter-spacing: 1px; -x-yaddayadda: yes; }
The only difference between now and then: today’s expert developer uses eight variables, because “that’s how you do it” (even with one-pagers) and because at some point in their life they may need them. In twenty-something years of web development we have somehow not managed to make our CSS consistent and easier to work on by establishing the (or even a) common sense standard to sort declarations.
(If this sounds harsh, it’s because it’s true. Developers condemn selectors, shorthands, !important, and other useful aspects of CSS rather than concede that they don’t even know how to sort their declarations.)
In reality, the issue is dead simple: Declarations should be sorted alphabetically. Period.
Why?
For one, sorting makes collaborating easier.
Untrained developers can do it. Non-English speakers (such as this author) can do it. I wouldn’t be surprised to learn that even houseplants can do it.
For another reason, alphabetical sorting can be automated. What’s that? Yes, one can use or write little scripts (such as CSS Declaration Sorter) to sort declarations.
Given the ease of sorting, and its benefits, the current state of affairs borders on the ridiculous, making it tempting to ignore our peers who don’t sort declarations, and to ban from our lives those who argue that it’s easier—or even logical—not to sort alphabetically but instead to sort based on 1) box dimensions, 2) colors, 3) grid- or flexbox-iness, 4) mood, 5) what they ate for breakfast, or some equally random basis.
With this issue settled (if somewhat provocatively), on to our second problem from the 90s.
Selector sorting
The situation concerning selectors is quite similar. Almost since 1994, developers have written selectors and rules as they occurred to them. Perhaps they’ve moved them around (“Oh, that belongs with the nav”). Perhaps they’ve refactored their style sheets (“Oh, strange that site styles appear amidst notification styles”). But standardizing the order—no.
Let’s take a step back and assume that order does matter, not just for aesthetics as one might think, but for collaboration. As an example, think of the letters below as selectors. Which list would be easiest to work with?
c, b · a · a, b · c, d · d, c, a · e · a c · b · a, b · a · c, d · a, c, d · a · e a, b · a, c, d · a · b, c · c, d · e
The fact that one selector (a) was a duplicate that only got discovered and merged in the last row perhaps gives away my preference. But then, if you wanted to add d, e to the list, wouldn’t the order of the third row make placing the new selector easier than placing it in either of the first two rows?
This example gets at the two issues caused by not sorting selectors:
No one knows where to add new selectors, creating a black hole in the workflow.
There’s a higher chance of both selector repetition and duplication of rules with the same selectors.
Both problems get compounded in larger projects and larger teams. Both problems have haunted us since the 90s. Both problems get fixed by standardizing—through coding guidelines—how selectors should be ordered.
The answer in this case is not as trivial as sorting alphabetically (although we could play with the idea—the cognitive ease of alphabetical selector sorting may make it worth trying). But we can take a path similar to how the HTML spec roughly groups elements, so that we first define sections, and then grouping elements, text elements, etc. (That’s also the approach of at least one draft, the author’s.)
The point is that ideal selector sorting doesn’t just occur naturally and automatically. We can benefit from putting more thought into this problem.
Declaration repetition
Our third hangover from the 90s is that there is and has always been an insane amount of repetition in our style sheets. According to one analysis of more than 200 websites, a median of 66% of all declarations are redundant, and the repetition rate goes as high as 92%—meaning that, in this study at least, the typical website uses each declaration at least three times and some up to ten times.
As shown by a list of some sample sites I compiled, declaration repetition has indeed been bad from the start and has even increased slightly over the years.
Yes, there are reasons for repetition: notably for different target media (we may repeat ourselves for screen, print, or different viewport sizes) and, occasionally, for the cascade. That is why a repetition rate of 10–20% seems to be acceptable. But the degree of repetition we observe right now is not acceptable—it’s an unoptimized mess that goes mostly unnoticed.
What’s the solution here? One possibility is to use declarations just once. We’ve seen with a sample optimization of Yandex’s large-scale site that this can lead to slightly more unwieldy style sheets, but we also know that in many other cases it does make them smaller and more compact.
This approach of using declarations just once has at least three benefits:
It reduces repetition to a more acceptable amount.
It reduces the pseudo need for variables.
Excluding outliers like Yandex, it reduces file size and payload (10–20% according to my own experience—we looked at the effects years ago at Google).
No matter what practice we as a field come up with—whether to use declarations just once or follow a different path—the current level of “natural repetition” we face on sample websites is too high. We shouldn’t need to remind ourselves not to repeat ourselves if we repeat code up to nine times, and it’s getting outright pathetic—again excuse the strong language—if then we’re also the ones to scream for constants and variables and other features only because we’ve never stopped to question this 90s-style coding.
The unnatural, more modern way of writing CSS
Targeting these three areas would help us move to a more modern way of writing style sheets, one that has a straightforward but powerful way to sort declarations, includes a plan for ordering selectors, and minimizes declaration repetition.
In this article, we’ve outlined some options for us to adhere to this more modern way:
Sort declarations alphabetically.
Use an existing order system or standardize and follow a new selector order system.
Try to use declarations just once.
Get assistance through tools.
And yet there’s still great potential to improve in all of these areas. The potential, then, is what we should close with. While I’ve emphasized our “no changes since the 90s” way of writing CSS, and stressed the need for robust practices, we need more proposals, studies, and conversations around what practices are most beneficial. Beneficial in terms of writing better, more consistent CSS, but also in terms of balancing our sense of craft (our mastery of our profession) with a high degree of efficiency (automating when it’s appropriate). Striving to achieve this balance will help ensure that developers twenty years from now won’t have to write rants about hangovers from the 2010s.
http://ift.tt/2H6YyWz
0 notes
dustinwootenne · 7 years ago
Text
We Write CSS Like We Did in the 90s, and Yes, It’s Silly
As web developers, we marvel at technology. We enjoy the many tools that help with our work: multipurpose editors, frameworks, libraries, polyfills and shims, content management systems, preprocessors, build and deployment tools, development consoles, production monitors—the list goes on.
Our delight in these tools is so strong that no one questions whether a small website actually requires any of them. Tool obesity is the new WYSIWYG—the web developers who can’t do without their frameworks and preprocessors are no better than our peers from the 1990s who couldn’t do without FrontPage or Dreamweaver. It is true that these tools have improved our lives as developers in many ways. At the same time, they have perhaps also prevented us from improving our basic skills.
I want to talk about one of those skills: the craft of writing CSS. Not of using CSS preprocessors or postprocessors, but of writing CSS itself. Why? Because CSS is second in importance only to HTML in web development, and because no one needs processors to build a site or app.
Most of all, I want to talk about this because when it comes to writing CSS, it often seems that we have learned nothing since the 1990s. We still write CSS the natural way, with no advances in sorting declarations or selectors and no improvements in writing DRY CSS.
Instead, many developers argue fiercely about each of these topics. Others simply dig in their heels and refuse to change. And a third cohort protests even the discussion of these topics.
I don’t care that developers do this. But I do care about our craft. And I care that we, as a profession, are ignoring simple ways to improve our work.
Let’s talk about this more after the code break.
Here’s unsorted, unoptimized CSS from Amazon in 2003.
.serif { font-family: times, serif; font-size: small; } .sans { font-family: verdana, arial, helvetica, sans-serif; font-size: small; } .small { font-family: verdana, arial, helvetica, sans-serif; font-size: x-small; } .h1 { font-family: verdana, arial, helvetica, sans-serif; color: #CC6600; font-size: small; } .h3color { font-family: verdana, arial, helvetica, sans-serif; color: #CC6600; font-size: x-small; } .tiny { font-family: verdana, arial, helvetica, sans-serif; font-size: xx-small; } .listprice { font-family: arial, verdana, sans-serif; text-decoration: line-through; font-size: x-small; } .price { font-family: verdana, arial, helvetica, sans-serif; color: #990000; font-size: x-small; } .attention { background-color: #FFFFD5; }
And here’s CSS from contemporary Amazon:
.a-box { display: block; border-radius: 4px; border: 1px #ddd solid; background-color: #fff; } .a-box .a-box-inner { border-radius: 4px; position: relative; padding: 14px 18px; } .a-box-thumbnail { display: inline-block; } .a-box-thumbnail .a-box-inner { padding: 0 !important; } .a-box-thumbnail .a-box-inner img { border-radius: 4px; } .a-box-title { overflow: hidden; } .a-box-title .a-box-inner { overflow: hidden; padding: 12px 18px 11px; background: #f0f0f0; }
Just as in 2003, the CSS is unsorted and unoptimized. Did we learn anything over the past 15 years? Is this really the best CSS we can write?
Let’s look at three areas where I believe we can easily improve the way we do our work: declaration sorting, selector sorting, and declaration repetition.
Declaration sorting
The 90s web developer, if he or she wrote CSS, wrote CSS as it occurred to them. Without sense or order—with no direction whatsoever. The same was true of last decade’s developer. The same is true of today’s developer, whether novice or expert.
.foo { font: arial, sans-serif; background: #abc; margin: 1em; text-align: center; letter-spacing: 1px; -x-yaddayadda: yes; }
The only difference between now and then: today’s expert developer uses eight variables, because “that’s how you do it” (even with one-pagers) and because at some point in their life they may need them. In twenty-something years of web development we have somehow not managed to make our CSS consistent and easier to work on by establishing the (or even a) common sense standard to sort declarations.
(If this sounds harsh, it’s because it’s true. Developers condemn selectors, shorthands, !important, and other useful aspects of CSS rather than concede that they don’t even know how to sort their declarations.)
In reality, the issue is dead simple: Declarations should be sorted alphabetically. Period.
Why?
For one, sorting makes collaborating easier.
Untrained developers can do it. Non-English speakers (such as this author) can do it. I wouldn’t be surprised to learn that even houseplants can do it.
For another reason, alphabetical sorting can be automated. What’s that? Yes, one can use or write little scripts (such as CSS Declaration Sorter) to sort declarations.
Given the ease of sorting, and its benefits, the current state of affairs borders on the ridiculous, making it tempting to ignore our peers who don’t sort declarations, and to ban from our lives those who argue that it’s easier—or even logical—not to sort alphabetically but instead to sort based on 1) box dimensions, 2) colors, 3) grid- or flexbox-iness, 4) mood, 5) what they ate for breakfast, or some equally random basis.
With this issue settled (if somewhat provocatively), on to our second problem from the 90s.
Selector sorting
The situation concerning selectors is quite similar. Almost since 1994, developers have written selectors and rules as they occurred to them. Perhaps they’ve moved them around (“Oh, that belongs with the nav”). Perhaps they’ve refactored their style sheets (“Oh, strange that site styles appear amidst notification styles”). But standardizing the order—no.
Let’s take a step back and assume that order does matter, not just for aesthetics as one might think, but for collaboration. As an example, think of the letters below as selectors. Which list would be easiest to work with?
c, b · a · a, b · c, d · d, c, a · e · a c · b · a, b · a · c, d · a, c, d · a · e a, b · a, c, d · a · b, c · c, d · e
The fact that one selector (a) was a duplicate that only got discovered and merged in the last row perhaps gives away my preference. But then, if you wanted to add d, e to the list, wouldn’t the order of the third row make placing the new selector easier than placing it in either of the first two rows?
This example gets at the two issues caused by not sorting selectors:
No one knows where to add new selectors, creating a black hole in the workflow.
There’s a higher chance of both selector repetition and duplication of rules with the same selectors.
Both problems get compounded in larger projects and larger teams. Both problems have haunted us since the 90s. Both problems get fixed by standardizing—through coding guidelines—how selectors should be ordered.
The answer in this case is not as trivial as sorting alphabetically (although we could play with the idea—the cognitive ease of alphabetical selector sorting may make it worth trying). But we can take a path similar to how the HTML spec roughly groups elements, so that we first define sections, and then grouping elements, text elements, etc. (That’s also the approach of at least one draft, the author’s.)
The point is that ideal selector sorting doesn’t just occur naturally and automatically. We can benefit from putting more thought into this problem.
Declaration repetition
Our third hangover from the 90s is that there is and has always been an insane amount of repetition in our style sheets. According to one analysis of more than 200 websites, a median of 66% of all declarations are redundant, and the repetition rate goes as high as 92%—meaning that, in this study at least, the typical website uses each declaration at least three times and some up to ten times.
As shown by a list of some sample sites I compiled, declaration repetition has indeed been bad from the start and has even increased slightly over the years.
Yes, there are reasons for repetition: notably for different target media (we may repeat ourselves for screen, print, or different viewport sizes) and, occasionally, for the cascade. That is why a repetition rate of 10–20% seems to be acceptable. But the degree of repetition we observe right now is not acceptable—it’s an unoptimized mess that goes mostly unnoticed.
What’s the solution here? One possibility is to use declarations just once. We’ve seen with a sample optimization of Yandex’s large-scale site that this can lead to slightly more unwieldy style sheets, but we also know that in many other cases it does make them smaller and more compact.
This approach of using declarations just once has at least three benefits:
It reduces repetition to a more acceptable amount.
It reduces the pseudo need for variables.
Excluding outliers like Yandex, it reduces file size and payload (10–20% according to my own experience—we looked at the effects years ago at Google).
No matter what practice we as a field come up with—whether to use declarations just once or follow a different path—the current level of “natural repetition” we face on sample websites is too high. We shouldn’t need to remind ourselves not to repeat ourselves if we repeat code up to nine times, and it’s getting outright pathetic—again excuse the strong language—if then we’re also the ones to scream for constants and variables and other features only because we’ve never stopped to question this 90s-style coding.
The unnatural, more modern way of writing CSS
Targeting these three areas would help us move to a more modern way of writing style sheets, one that has a straightforward but powerful way to sort declarations, includes a plan for ordering selectors, and minimizes declaration repetition.
In this article, we’ve outlined some options for us to adhere to this more modern way:
Sort declarations alphabetically.
Use an existing order system or standardize and follow a new selector order system.
Try to use declarations just once.
Get assistance through tools.
And yet there’s still great potential to improve in all of these areas. The potential, then, is what we should close with. While I’ve emphasized our “no changes since the 90s” way of writing CSS, and stressed the need for robust practices, we need more proposals, studies, and conversations around what practices are most beneficial. Beneficial in terms of writing better, more consistent CSS, but also in terms of balancing our sense of craft (our mastery of our profession) with a high degree of efficiency (automating when it’s appropriate). Striving to achieve this balance will help ensure that developers twenty years from now won’t have to write rants about hangovers from the 2010s.
http://ift.tt/2H6YyWz
0 notes
euro3plast-fr · 8 years ago
Text
How ecommerce can increase conversions with AMP
An easy, visual guide to help you implement AMP for ecommerce to increase conversions
E-commerce is all about creating an amazing shopping experience online for the visitor with the intention of getting them to click, convert, and become a customer.
With changes in consumer shopping behaviors, online brands have had to adjust how they market to prospective customers, as well as the user experience, to ensure an enjoyable experience.
The largest change has come from the adoption of mobile technology.   There are more than 4.9 billion people globally utilizing smartphones, representing around 66% of the world’s population.
And as of January 2017, mobile phones accounted for 50% of internet traffic. That’s a 30% increase from last year alone.
That growth has triggered a need for more streamlined mobile shopping experiences, but not all brands made the jump right away. Without mobile-optimized sites, mobile users were experiencing high site loading times and having difficulty getting the information and items they wanted while on their phone.
That’s where Google stepped in.
In 2015, Google launched its Accelerated Mobile Pages (AMP) framework to create web pages that load much faster on mobile devices. It was created as an open source initiative that would allow publishers and online brands the ability to ramp up the load speed and reduce wait times for online users.
This kind of optimization was already attainable with the right developers on hand, but not all brands have the resources capable of intensive remodeling of their sites in order to tend to the mobile experience.
Why AMP is Important
With AMP, it all comes down to speed.
Search engines like Google survive by the positive experiences of the user who can find the information they want/need quickly, without long delays. It’s in their best interest to make sure the user has the best experience.
That’s why site speed was added as a ranking factor. If your site takes too long to load, and your customers are bouncing, you’ll likely see that negatively impact your organic search visibility.
For online brands, you not only want to protect your organic search rank by creating a fast-loading experience, embracing AMP also improves conversions.
Check out the figures from this infographic shared by Kissmetrics:
The full data on the infographic reveals a few key things.
The big one is that roughly 44% of mobile users expect a site to load as fast as a desktop experience or faster. When that performance drops and you don’t meet expectations—guess what?
Prospective customers bail and may not come back.
What’s worse is that for every delay of just one second in your load time you take a 7% hit in your conversation rates because visitors start bailing.
If the average rate of cart abandonment is about 68%, imagine how that would be climbing if a large portion of your audience is on mobile and your site loads so slow they get impatient and leave.
How Accelerated Mobile Pages Are Implemented in E-Commerce
The visitors on your site come from any number of landing pages, from your homepage to product and categories, and even blog posts. While it’s important to optimize the visitor’s shopping experience, it isn’t necessary to implement AMP on every page.
Instead, look at the visitor flow through your site so you can visualize your customer journey or funnel and employ AMP at key points through the process.
This is necessary because AMP depends on simplified JavaScript and CSS and will limit or restrict some other CSS and JavaScript, such as no iframes and a lack of support for JavaScript library such as those used for loading reviews.
The simplified framework of AMP is what allows pages to load quickly. Paul Shapiro lays out the three elements of this framework in his post for Search Engine Land:
AMP HTML: A subset of HTML, this markup language has some custom tags and properties and many restrictions. But if you are familiar with regular HTML, you should not have difficulty adapting existing pages to AMP HTML. For more details on how it differs from basic HTML, check out AMP Project’s list of required markup that your AMP HTML page “must” have.
AMP JS: A JavaScript framework for mobile pages. For the most part, it manages resource handling and asynchronous loading. It should be noted that third-party JavaScript is not permitted with AMP.
AMP CDN: An optional Content Delivery Network, it will take your AMP-enabled pages, cache them, and automatically make some performance optimizations.
If you use a content management system such a WordPress and Magento, or e-commerce platforms like Shopify, you can find third-party plugins.
There’s an official WordPress plugin for AMP available on GitHub that you would upload just like any other WordPress plugin.
  Key Benefits and AMP Element Implementation in E-Commerce
With the limitations of AMP, you won’t be able to use it where you have things like form elements and third-party JavaScript, but there are still plenty of opportunities for utilizing AMP in e-commerce throughout the customer’s shopping experience—just not in the checkout.
If you’re still not sure how or where to use AMP on your e-commerce site or how it could benefit you, here are some examples of AMP implementation.
Reduced Bounce Rates To Site Pages
Remember the bit above about how slow load times can make visitors bail on the experience? That impacts your bounce rate which is one of many ranking factors. One of the major benefits of AMP is reducing that bounce rate since mobile users are going to spend more time on your site, and view more content.
So that secondary benefit of improving load times is a bump in visibility. Your site will rank better than similar sites without AMP implementation.
Look at the two versions of this page to see how content is trimmed for efficient loading:
Improved Click-Through Rates in SERPs
One way Google lets users know about an optimized mobile experience is through the use of the AMP symbol. When a site has implemented AMP, the algorithm will display this symbol within the search results.
This symbol can help your content stand out in the search results, and once more consumers begin to recognize that AMP content loads faster they’ll be more likely to continue looking for that content in the search results.
Media Rich Page Optimization
Customers are most likely to land on your homepage and your category pages, but product landing pages or product detail pages are also a possibility just like any other page on your site.
If you’re linking to or grabbing referral traffic on media-rich pages you can implement AMP on these pages to improve image load time as well as how video is handled on mobile. Like images, there is a custom AMP tag for locally hosted videos in HTML5 called amp-video.
However, if you’re using videos hosted on YouTube like many online brands due then you would use a separate component called amp-youtube.
For other image-handling needs, AMP also has support for slideshows using amp-carousel as well as lightbox support with the amp-image-lightbox tag.
These can greatly improve the load time for homepages and category pages that often contain the most content and act as the most common landing pages for visitors.
Handling Detail Rich Pages
Any extra content takes time to load, even if it’s just text. If you have detail-rich product pages or information pages you can use the amp-accordion element to condense information until a visitor calls for it when it expanding the accordion or section.
Not only with this speed up load time but it improves the visitor experience by allowing them to only load or ‘jump to’ the content they’re specifically interested in.
CSS selectors can be even used to style the accordion element.
Customized Shopping with AMP
Conversion rate optimization should always be a priority for e-commerce brands, but not at the expense of the user experience, load times, etc. One always benefits the other. Thankfully, no sacrifice has to be made.
The amp-access element can be used to customize the content shown to users based on the status of the user, such as if they’re logged in or not. This allows you to personalize the shopping experience (which can improve conversions) while also trimming the load time for mobile users.
Conversion Optimization and User Experience Testing is Supported
With conversion in mind, you won’t have to sweat the simplification off CSS and JavaScript when working to improve conversion rates. The amp-experiment element is used to conduct user experience experiments such as A/B testing and multivariate testing.
This is a great way to see how individual page optimizations and AMP implementation are performing with your mobile users, so you know if your efforts are having a positive or negative impact.
Maintain Tracking Without Negatively Impacting Load Time
Any scripts that must be loaded can slow down the mobile experience, including tracking scripts. Running multiple analytics tracking scripts can compound this. The AMP analytics element streamlines tracking by taking the “measure one, report to many” approach.
There are two ways to implement tracking:
The amp-pixel element is a simple tag that allows you to count page views and track users with a number of customizable variables.
The amp-analytics extended component is the more in-depth analytics you might be more familiar with but requires a little setup to complete. It has built-in support for Google Analytics though for easy reporting once you have it in place. This is the best approach to track and measure user behavior and the performance of your content to continue improving the user experience.
AMP provides a basic demo of how some activities can be tracked.
Conclusion
While AMP does have some limitations that can make some tracking difficult, it’s highly recommended at key points in the buyer’s journey of your e-commerce site to optimize load times.
When you can improve the shopping experience and improve performance you will, without a doubt, improve the conversion rates of your online store.
Thanks to Emil Kristensen for sharing their advice and opinion in this post. Emil is the CMO and co-founder of Sleeknote, a company that helps ecommerce business owners capture and convert more leads without hurting the user experience.
from Blog – Smart Insights http://www.smartinsights.com/ecommerce/ecommerce-strategy/ecommerce-can-increase-conversions-amp-implement/
0 notes
jacksonfdam · 8 years ago
Text
OOCSS, ACSS, BEM, SMACSS
The way we write CSS has changed a lot in last few years, and the abbreviation jungle gets deeper and deeper. Heres a list of links to influential articles and quick summaries of these techniques.
I think there have bee happening big things in how we write CSS, for a reason I suppose. The will to make CSS more modular is strong (to make CSS so that it’s easier to control without breaking everything when you change a small thing).
Object Oriented CSS (OOCSS)
In a nutshell:
Keep the structure and skin separate
Keep the visuality separate, so you can reuse the visual classes. For instance, you wouldn’t anymore add gradient to a .button element, but define a general gradient somewhere and then just extend the gradient to the .button
Separate container and content
“rarely use location-dependent styles.” Roughly, this means that do not cascade, go straight into object, give them a class and reference that in your CSS. Don’t do this:
ul li.list-item {    ... }
Go straight into the element:
.list-item {    ... }
More reading on the subject:
Official OCSS documentation on GitHub
Nice read about OCSS in Smashing Magazine
Atomic approach
Science joke time:
Why can’t you trust atoms? Cause they make up everything.
Now, Atomic can mean a few things:
Atomic design principle coined by Brad Frost on his article “Atomic Design”.
Atomic CSS (ACSS), popularized by @thierrykoblentz on an article “Challenging CSS Best Practices”.
The atomic approach can also be applied to project file structuring: The “Other” Interface: Atomic Design With Sass.
Like the name suggest, all these methodologies pull analogy from science, Atoms being the building blocks of everything.
Atomic Design
In a nutshell:
Atoms
Molecules
Organisms
Templates
Pages
An HTML element, e.g. an input
A set of HTML elements, a search for example including a label, input and a button
A set of Molecules, like a header of a site. This site has in the header Organism: Site title, Beta remark, navigation and search
A wireframe of the wholes site, containing all the Organisms, layout starts to appear
The whole thing together, the most complex compound of all, the actual site with all it’s images and everything
More reading: Atomic Design.
On a related note, but not the same thing, Atomic CSS. Thanks @thierrykoblentz for the correction.
Atomic CSS (ACSS)
This beautiful and somewhat controversial article trashes everything you’ve know about CSS (pretty much). Premise being: only use reusable classes like:
.mt-20 {    margin-top: 20px; } /* Or */ .fl {    float: left; }
Just one declaration per selector. Essentially, putting the styling back to the markup, like we used to do in the early nineties. Sounds really crazy, but it’s actually quite liberating. You can reuse classes now, and what could be better than reusing classes? Maybe a full body massage and a cold pint of lager.
Here’s a simple example, an excerpt from this article. Take the below markup where the pneeds to be inlined with the a:
<p>    The way we write CSS has changed a lot in last few years, and the abbreviation [...] </p> <a href="/article/">    More→ </a>
No style applies to the p element (expect for general paragraph style), but now I want to display the p inline with the more anchor. I would have to painstakingly go to my CSS file and create a new rule for the p, a rule that is only specific for that element. Bloat, I’m thinking. So I might as well use a previously defined utility class:
.di {    display: inline; }
And add it in:
<p class="di">    The way we write CSS has changed a lot in last few years, and the abbreviation [...] </p> <a href="/article/">    More→ </a>
Nice, no bloat no problem.
Downside of this is media queries, because now all styling is in markup, you can’t affect the layout anymore with media queries, can’t remove a float for instance when on phone. The original article comments have a bit about this.
Only way around this is to send a different markup for every device, which is exactly the non media query way of doing things (which is probably really fine, I just don’t really know that much about it). Or to use a JavaScript solution like Responsive Elements, which adds classes to the elements depending on the viewport width.
This approach is good for really big sites, it’s not as beneficial for smaller sites. Have a look at the my.yahoo.com with your devtools and you’ll see it in action.
I’m using utility classes on every project pretty much, but just not on full throttle, it’s not the driving main system ever. Mostly because I want to use media queries.
Atomic file organization
The “Other” Interface: Atomic Design With Sass article takes the Atomic thinking and applies it to file organization, it also introduces Quarks (this is what atoms are made of).
Here’s a little bash command to barf out the file structure if you want to try it out in a project:
mkdir -p atomic-structuring/{utilities,quarks,atoms,molecules} && cd atomic-structuring && touch utilities/{_base-spacing.scss,_clearfix.scss,_reset.scss} && touch quarks/{_lists.scss,_paragraphs.scss,_tables.scss,_links.scss} && touch atoms/{_media.scss,_flag.scss,_button.scss,_grids.scss} && touch molecules/{_banner.scss,_custom-post.scss,_footer-nav.scss,_heading-group.scss}
It gives you the following tree:
atomic-structuring/ ├── atoms │   ├── _button.scss │   ├── _flag.scss │   ├── _grids.scss │   └── _media.scss ├── molecules │   ├── _banner.scss │   ├── _custom-post.scss │   ├── _footer-nav.scss │   └── _heading-group.scss ├── quarks │   ├── _links.scss │   ├── _lists.scss │   ├── _paragraphs.scss │   └── _tables.scss └── utilities    ├── _base-spacing.scss    ├── _clearfix.scss    └── _reset.scss
You probably get the hang of the technique, now you’ve got a hierarchical structure for the code. It might take a bit of getting use to.
Block, Element, Modifier (BEM)
In a nutshell:
Basically, It’s a way to name your classes (I guess it’s more than that, but this is the easily extrapolated thing in it)
It’s easy for anyone to understand BEM code, cause of the strict rules (also easier for you to write when you have a system)
Code example:
/* This is the Block */ .block {} /* This is an element, that helps to form the block as a whole */ .block__element {} /* This modifies the element or a block*/ .block--modifier {}
Let’s start with a wrong example, this is bad:
<header class="block">    <h1 class="block__elem1">        <a class="block__elem1__elem2" href="/">clubmate.fi</a>    </h1> </header>
Don’t go so deep block__elem1__elem2, don’t try to mimic the DOM tree.
The following is better:
<header class="block">    <h1 class="block__elem1">        <a class="block__elem2" href="/">clubmate.fi</a>    </h1> </header>
This excellent SO answer nails it down pretty succinctly:
Nested html-elements is a DOM-tree. The names of the classes you write is a BEM-tree. Feel the difference!
DOM-tree:
<ul>  <li>    <a>      <span></span>    </a>  </li> </ul> .ul {} .ul > li {} .ul > li > a {} .ul > li > a > span {}
BEM-tree:
<ul class="menu">  <li class="menu__item">    <a class="menu__link">      <span class="menu__text"></span>    </a>  </li> </ul> .menu {} .menu__item {} .menu__link {} .menu__text {}
Thanks to Igor Zenich for that explanation.
Here’s a little real world example:
<!-- Block --> <header class="col-header">    <!-- Block element -->    <h1 class="col-header__heading">        <a class="col-header__link" href="/">clubmate.fi</a>    </h1>    <!-- Block element -->    <span class="col-header__beta">(beta)</span>    <!-- New Block -->    <nav class="nav">        <!-- Block element -->        <a class="nav__item" href="/">Home</a>        <!-- Block element -->        <a class="nav__item" href="/archives">Archives</a>        <!-- Element and a modifier -->        <a class="nav__item nav__item--uplink" href="#header">↑</a>    </nav> </header>
Drill into the Yandex site with your devtools to see it in action.
I was so happy to start using this, finally a system, an order into class naming that I had always been lacking. It kind of freed a lot of resources in your brain, as puny thing as element naming can still occupy a lot of brainpower. The ancient, and very true, quote fits here like fist to an eye:
There are only two hard things in Computer Science: cache invalidation and naming things. —Phil Karlton
BEM tries to address the naming.
More reading:
The BEM site: bem.info
An easy to understand article about BEM in csswizardy.com
Great SO answer by Igor Zenich
SMACSS—Scalable and Modular Architecture for CSS
SMACSS (pronounced “smacks”) is more style guide than rigid framework.
This is pretty much says the same thing as the before mentioned methods, but in a different wrapper. You can read more about it at the SMACSS website. Most of the content is free to read, but you can also buy the book if you prefer.
I think SMACSS is more vague as a concept than the others, it’s just a set of tutorials on how to write good CSS. That’s perfect!
Also a great read is the Smashing Mag article Decoupling HTML from CSS.
Which one should I use then?
Use whatever you feel comfortable, or mix them, take the best bit’s and make it your own. It’s just CSS, you’re not a surgeon or ambulance driver, It’s not so serious (go tell that to your idiot boss, I know, you get the point). For a small site it doesn’t even matter so much. But for bigger sites it’s elementary, otherwise codebase becomes impossible to maintain.
I personally like the OOCSS and and the atomic in it that I can throw a class in that only has one declaration in it.
Source: http://clubmate.fi/oocss-acss-bem-smacss-what-are-they-what-should-i-use/
0 notes
rwahowa · 8 years ago
Text
18 Parts of CSS - HTML and CSS Tutorial for beginners
Check this out https://bizanosa.com/18-parts-css/
18 Parts of CSS - HTML and CSS Tutorial for beginners
Watch this video on YouTube
18 Parts of CSS
In this post let us look at the various parts of CSS. We are going to do this by analyzing the sample CSS code below:
body background-color: #fff; color: #000;
  Join the FULL HTML and CSS Tutorial Here >>
  Explanation of the code
In the above styles, the first part (background-color: #fff;) will  make the background color of the body/page white.
The second part (color: #000;)  will make the color of the text on the page , black.
You will learn more about all these later. Or you may go ahead and watch the full HTML and CSS tutorial here.
  Rule
The full style block is a rule.
body background-color: #fff; color: #000;
      Style Declaration
Style declaration is the actual styles that affect a CSS element (called selector)
From our example above it will be:
/** * This is a comment */ background-color: #fff; color: #000;
  Selector
Selects what needs to be styled. It may be a class, an identity (id) or a HTML tag .
From our example the selector is body .
You will learn about selectors later on. You will see how to combine different selectors.
  Property  and value
Property refers to the first part of the style element .
From our example above, examples are :
background-color
color
  The value refers to the second part of a style element.
From our example above, examples are :
#fff
#000
  They form the property value pairs. And they must be terminated by a semicolon ( ; ) as shown in the examples above.  The value and the property are separated by a colon ( : )
background-color: #fff ;
  You will learn more about all these . You will learn about CSS selectors in details, where we’ll talk about different types of selectors. You will learn how to use compound selectors to dig down into your HTML elements, you will also learn about pseudo selectors and so much more.
  To learn more about HTML and CSS right away, click on the button below:
  Join the FULL HTML and CSS Tutorial Here >>
0 notes
suzanneshannon · 5 years ago
Text
Styling in the Shadow DOM With CSS Shadow Parts 
Safari 13.1 just shipped support for CSS Shadow Parts. That means the ::part() selector is now supported in Chrome, Edge, Opera, Safari, and Firefox. We’ll see why it’s useful, but first a recap on shadow DOM encapsulation…
The benefits of shadow DOM encapsulation
I work at giffgaff where we have a wide variety of CSS code that has been written by many different people in many different ways over the years. Let’s consider how this might be problematic. 
Naming collisions
Naming collisions between classes can easily crop up in CSS. One developer might create a class name like .price. Another developer (or even the same one) might use the same class name, without knowing it.
CSS won’t alert you to any error here. Now, any HTML elements with this class will receive the styling intended for two completely different things.
Shadow DOM fixes this problem. CSS-in-JS libraries, like Emotion and styled-components, also solve this issue in a different way by generating random class names, like .bwzfXH. That certainly does help avoid conflicts! However, CSS-in-JS doesn’t prevent anybody from breaking your component in other ways. For example…
Base styles and CSS resets
Styles can be applied using HTML element selectors like <button> and <div>. These styles could break a component. Shadow DOM is the only thing that offers (almost) full encapsulation — you can rest assured that your component will look the same, even in a messy  !important  strewn codebase because each component is encapsulated.
/* This will have no effect on buttons inside shadow DOM */ button { background-color: lime !important; }
I wouldn’t say it’s good practice to style elements this way, but it happens. Even it does, those styles will have no effect on the shadow DOM.
It’s worth noting that inheritable styles like color, font and line-height are still inherited in a shadow DOM. To prevent that, use all: initial  or, preferably, all: revert once it has better browser support.
Let’s look at a common example of CSS applied directly to HTML elements. Consider this code from Eric Meyer’s reset: 
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed,  figure, figcaption, footer, header, hgroup,  menu, nav, output, ruby, section, summary, time, mark, audio, video {   margin: 0;   padding: 0;   border: 0;   font-size: 100%;   font: inherit;   vertical-align: baseline; }
What if the component we’re working with makes use of the user agent’s default values for margin and padding? This reset might cause it to appear broken since those defaults are effectively wiped out.
Shadow DOM is a way to avoid these problems. Shadow DOM allows us to feel fully confident that a component will render as expected, regardless of what codebase it ends up in. Equally, none of the code meant only for a component can inadvertently affect anything else — all without resorting to onerous class naming conventions. Shadow DOM offers a level of encapsulation that can’t be achieved any other way.
Encapsulation is great, but we also want our components to be themeable and customizable. That’s been made far easier with the ::part selector. 
Styling shadow DOM with ::part()
Until now, the only way for CSS to modify the styling of a custom element from outside of the shadow DOM was to use CSS custom properties. In a strict design system where you only want to allow limited changes, that might be ideal. If you want your component to be more versatile, it creates a problem. Every CSS property you want to offer up for styling needs to be defined using a custom property. Just the sound of that seems tedious.
The situation is compounded further if we want to style a component differently based on pseudo-classes, like :hover. Basically, we end up with loads of custom properties. Let’s look at an example from Ionic, an open source set of web components. Just look at all the custom properties defined on the Ionic button component.
Go ahead, I’ll wait.
I counted 23 custom properties. Needless to say, that’s less than ideal.
Here’s an example using ::part() to style the element instead. 
CodePen Embed Fallback
In this Pen, I’m simply changing the color, border and background-color properties, but I could use whatever I want without being constrained by what custom properties have been defined. Notice that I can also style different states of the part using pseudo-classes, like :hover and :focus.
The entire component in this button example is being exposed for styling, but if your web component consists of multiple HTML elements, you can expose only selected parts of the component to this sort of styling — hence the name ::part. This stops users of the component from styling any arbitrary element inside the shadow tree. It is up the the component author to expose the parts of the component they explicitly want to. Other parts of the component can be kept visually uniform or make use of custom properties for a more minimal customizability. 
So, how do we set this up for our own components? Let’s look at using ::part to make certain elements of a web component eligible for styling. All we do is add a part attribute on the element we want to be exposed.
<div part="box">...</div>   <button>Click me</button>
In this example the div is customizable with the full gamut of CSS — any CSS property can be changed. The button, however, is locked down — it cannot be visually changed by anybody except the component author.
CodePen Embed Fallback
And the same way an HTML element can have multiple classes, an element can have multiple part names: 
<div part="box thing">...</div>
So that’s what we get with ::part: by exposing “parts” of an element we can provide some flexibility in how a web component is used while exercising protection in other areas. Whether it’s your design system, a component library, or what have you, the fact that CSS Shadow Parts are becoming mainstream gives us yet another exciting tool to work with.
The post Styling in the Shadow DOM With CSS Shadow Parts  appeared first on CSS-Tricks.
Styling in the Shadow DOM With CSS Shadow Parts  published first on https://deskbysnafu.tumblr.com/
0 notes