Front End Web Development

The Dark Side of the Grid

Css Tricks - Sun, 03/10/2019 - 12:51pm

Manuel Matuzovic makes the point that in order to use CSS grid in some fairly simple markup scenarios, we might be tempted to flatten our HTML to make sure all the elements we need to can participate on the grid. What we need is subgrid and non-buggy display: contents;, so I'd like to think in a year or so we'll be past this.

Direct Link to ArticlePermalink

The post The Dark Side of the Grid appeared first on CSS-Tricks.

HTML, CSS and JS in an ADD, OCD, Bi-Polar, Dyslexic and Autistic World

Css Tricks - Fri, 03/08/2019 - 5:20am

Hey CSS-Tricksters! A lot of folks tweeted, emailed, commented and even courier pigeoned (OK, maybe not that) stories about their personal journeys learning web development after we published "The Great Divide" essay. One of those stories was from Tim Smith and, it was so interesting, that we invited him to share it with the broader community. So, please help us welcome him as he elaborates on his unique personal experience and how it feels to be in his shoes as a front-ender.

Hi folks, my name is Tim Smith

I have ADD, OCD, Bi-Polar, Dyslexia… and not to mention that I am on the Autism spectrum. This combination (apart from causing me to feel a lot of personal shame) makes coding very hard — especially learning how to code, which I am trying to do. Things get mixed up in my head and appear backwards to the point that I find it nearly impossible to focus any longer than 15-20 minutes at a time. Perhaps I will expand on this in another post. Even now as I write this, I feel pulled to rate each song on YouTube Music and attempt to correct every mistake I make. And since I keep switching “write" with “right," this becomes infuriating and discouraging, to say the least.

I do not read well, so learning from books is the least effective way for me to learn (sorry O’Reilly). Online tutorials are OK, but I tend to sell myself short by being lazy with copy and paste for the code examples. If I force myself to hand-type the examples, I get the benefit of muscle memory but drown in the words of the tutorial and eventually lose interest altogether.

Video tutorials are my ideal learning method. There’s no reading involved and no way for me to copy and paste my way out of things. Having to stop and start the videos in order to type the code is maddening, but well worth it. YouTube is a great place for video tutorials if you have the patience to wade through them… which I don’t.

I found Chris Coyier in the early 2000s. The treasure trove of articles, guides, and videos contained here on CSS-Tricks has been a major benefit for me and actually progressed my ability to learn code. Later, I found Wes Bos. He, too, has been a leading contributor to my web learning. Wes unlocked many of the things I struggled with, namely React and the new features of ES6.

Together, I’d say Chris and Wes are responsible for at least 80% of my collective front-end knowledge. (Personal aside: Chris and Wes, you two are my heroes and secret mentors.) Both Chris and Wes have a way of giving me the information that's relevant to what I'm learning in a way that is fun and entertaining as well as straightforward and precise. They don’t just present the code; they explain the why and history behind each topic. Wes is a little better at this, but the sheer number of videos Chris has created has kept me busy for years and will continue to into the future.

Simply writing code is another effective way for me to learn. I like to geek-out and setup development servers for various web languages and libraries and play around. I have learned a lot about MacOS and Linux (mostly Ubuntu) while also learning the basics of many web languages and libraries: PHP (for WordPress themes), Python, React, Vue and many others. I learned to embrace the command line and avoid GUIs when possible. Nothing against GUIs; I simply find the command line more precise (and just between you and me, way cooler to brag about to non-coders).

I still do use the command line — or at least I would if I still had a laptop or desktop to work on. I am actually writing this on an iPad Mini 2. However, I have found another great way to write and share code without the need to set up servers and complicated environments: CodePen. I joined an early beta way back when and it was love at first sight. I can now write code, share it and get feedback all in one place (here’s my profile). Every time I get a fun idea or find a fun kata, I fire up Codepen and just start coding. No tricky dev setup. There are other apps that do this but CodePen is unique because of the social aspect and the ability to easily embed code samples on forums.

So, that’s a little about me. What I want to get into is how I learn HTML and CSS because it’s probably somewhat similar to yours, but different than how you might have gone about it.

Breaking into HTML

I learned HTML in a few different ways. At first, I would look at the source code of popular web sites. In the early nineties, when I started to learn HTML many, if not most, web browsers had the ability to show the source code of a website. I saw all of the tags, how they were used and the basic structure of the sites. I was able to reverse-engineer them. I had not learned CSS at the time, so my first websites were single column and very boring.

Quick aside: Without CSS, all websites are perfectly responsive and look great on any device or screen size. We break them with CSS, then need to fix them... ponder that a bit.

Thanks to source code, I began reading articles on the web and studied constantly. I found the DreamInCode forum which serves as a forum for all code disciplines and languages — similar to StackOverflow because, like StackOverflow, the people were arrogant and rude to newbies, at least in my experience. Still, I was able to see how people approached various HTML concepts and problems and this was the springboard upon which I launched my learning adventure. I received blunt, often harsh feedback on my code examples. As hard as it is to hear hard criticism, it benefitted me as it taught me the right and — even more importantly, the wrong — way to approach and write HTML.

Like most things, writing and mastering HTML is all about trial and error. I had to create hundreds of horrible websites (if you could call them that) before it “clicked" for me. But that’s better than nothing, as we’ve all heard it said before:

Just build websites!
— Chris Coyier

It was not long after that I was introduced to CSS, and then the real journey began...

Along came CSS

The easiest way for me to describe CSS is this: It’s the code that makes your HTML look nice." I had to adopt a KISS attitude as I learned CSS because I found that I was overthinking it. CSS is simple if you let it be. Let’s have a look:

See the Pen
Thing
by Tim Smith (@WebRuin)
on CodePen.

This is about as simple as CSS is. Name your block in HTML (e.g. <div class="Tim">...</div>), then target that name in a CSS file with properties to describe the block, like colors, borders, font treatments among much, much more.

At first, I would spend all my time trying to memorize as many CSS properties as I could. I would “Alta Vista" (remember that?!) around for what sort of things others were doing with CSS and how they were doing it. This was fun and informative but only served to confuse me to no end. Trying to reverse-engineer CSS as I did with HTML only got me so far. My memory for stuff like this is poor, at best. I had to step back, take a deep breath (literally and figuratively) and find a new approach.

My thought process typically goes something like this:

  1. Do I want the words to be black? If so, do nothing
  2. What about the background color? The default white is boring so... give it a background color.
  3. How big do I want the element to be? Don’t overthink this as far as measurement units go, because pixels are fine and, well, height and width seem pretty logical to me.

And so on. Simple questions with simple property names. My point is you can do some amazing things with simple CSS. It was that simplicity that made me want to learn and apply everything I found. But, at the same time, I was so overwhelmed that I almost quit web development for good. It’s an awkward conflict: the simplicity and elegance are welcoming and fun but the myriad possibilities are dizzying and impossible to retain.

What worked for me was taking an incremental approach to learn CSS. By starting small and slowly adding more as I truly learned and understood the properties. I found I could have fun and be creative at a comfortable pace without putting too much pressure on myself.

I won’t lie. I am not a designer. Given a blank canvas, I will freeze or come up with a mediocre design that’s derivative of a mish-mash of other designs I like. That said, I am great at coding a design that someone with actual design skills can put together (like this).

I fell in love with CSS for one reason: it is the perfect balance of logic and design. A lot of coding is like this. Code can be beautiful, but CSS is the bee’s knees for me!

JavaScript is hard! But I’m trying.

HTML and CSS came relatively easily to me. I stumbled a bit on CSS Grid and some of the more advanced stuff, but it just clicked for me. As I alluded to earlier, I am a visual learner. Both HTML and CSS are inherently visual languages, and they give me the instant gratification my ADD needs. Both are straightforward and commonsensical to me.

In contrast, Javascript is something I find to be very, very difficult. It is a logic-based language which would ordinarily be my cup of tea; nevertheless, I have found it challenging to “click" with. Despite a few epiphanies while learning it, JavaScript seems to elude me beyond the basics. I have completed Wes Bos’ JavaScript30 course along with many other tutorials. They make sense in the moment it’s being explained to me, but even still, when presented with a “blank canvas" so to speak, I forget most of the concepts and either write the same ol’ stuff over and over or simply give up.

Surprisingly, React came much more naturally to me. I think it has to do with its modularity and my love for blocks, LEGOs, and puzzles. I have learned it well enough that I have been able to be creative with it and have started writing an app with it: a crowd-sourced urban bathroom locator. I have written and rewritten the start of the app with various Flux libraries and backend data libraries. I invariably give up only to start again, like the famous definition of insanity. I just keep thinking I will figure it out and/or find someone to do the hard parts for me.

My roadblock with React is JavaScript, of course. That may not make sense, but remember my stance on blocks. I know React is JavaScript. To me, though, it is quite different than vanilla JavaScript. Closures, pure functions, arrow functions, let vs. const vs. var, the enormous set of built-in methods, not to mention imported libraries, classes, and of course, my nemesis, Big O (how I loath Big-O)... my head is spinning even as I write this.

I want so badly to be, at the very least, decent at Javascript so I keep trying. Hundreds of tutorials, code schools like freeCodeCamp.org, Treehouse, Khan Academy, and yes, even muscling through many books (I love JavaScript: The Good Parts).

I have no trouble learning the syntax. The hangup, I think, lays in a lack of computer science knowledge and this inability to think mathematically. Algorithms make sense in concept, but their practical application simply blows my mind.

For mental health reasons, it was necessary for me to step away from my web development career in 2005. I was able to get back into it around 2010 when I worked for a few startups, but I never truly got back in. Javascript is my Achilles heel. I was lucky to find a few jobs that were truly light on JavaScript so I could focus on HTML and CSS — the things I thought added up to front-end development — but inevitably, I was expected to write JavaScript beyond basic interface enhancements and the jobs fell apart. So I either quit or was fired.

The ongoing search for work

Looking for work in recent times has been a nightmare! We now live in a world dominated by JavaScript and it seems no one wants a front-end developer whose strengths lie in HTML, CSS with an intermediate knowledge of Javascript — especially those without a degree in Computer Science. I can’t even find a job posting for this on any major job site.

I have had the honor of interviewing with recruiters at Facebook, Google, and Apple but I could not get past the first round of phone screening. I was asked questions that I felt have little-to-nothing to do with what I understand front-end development to be. There were no questions about CSS best practices and even nothing about semantic HTML or the proper use of ARIA attributes. All they seemed to care about was Big O and efficient loops. Even interviews with smaller companies were like this. Have services like Wix and the like taken all the core front-end jobs away?

Despite all the challenges I have faced, I feel I have mastered HTML and CSS and have a baseline grasp on JavaScript. I am very proud of that. While I dream of getting a job at a large company like Facebook, Google, or Apple, I really just hope to find a role where my HTML and CSS skills will shine and I can gain real-world experience with JavaScript as a junior developer with the benefit of mentoring somewhere, like the San Francisco Bay Area where I currently live.

We all have different learning styles and paces, so don't give up before you have tried every possible way to learn what you are trying to do. And, if you come up with a new way, please share so we can all broaden our individual and collective knowledge.

I hope this article has reached at least one other developer like me! Thank you to all my predecessors. Happy coding!

The post HTML, CSS and JS in an ADD, OCD, Bi-Polar, Dyslexic and Autistic World appeared first on CSS-Tricks.

Styling Based on Scroll Position

Css Tricks - Thu, 03/07/2019 - 5:26am

Rik Schennink documents a system for being able to write CSS selectors that style a page when it has scrolled to a certain point. If you're like me, you're already on the lookout for document.addEventListener('scroll' ... and being terrified about performance. Rik gets to that right away by both debouncing the function as well as marking the event as passive.

The end result is a data-scroll attribute on the <html> element that can be used in the CSS. Meaning if you're scrolled to 640px down the page, you have <html data-scroll="640"> and could write a selector like:

html:not([data-scroll='0']) { body { padding-top: 3em; } header { position: fixed; } }

See the Pen
Writing Dumb JS &#x1f9df;‍♂️ and Smart CSS &#x1f469;‍&#x1f52c;
by Rik Schennink (@rikschennink)
on CodePen.

Unfortunately, we don't have greater than (>) less than (<) selectors in CSS for things like numbered attributes, so the CSS styling potential is fairly limited here. You might ultimately need to update the JavaScript function such that it applies other classes or data attributes based on your math. But you'll already be set up for good performance here.

"Apply styles when the user has scrolled away from the top" is a legit use case. It makes me think of a once function (like we have in jQuery) where any scroll event would only be triggered once and then not again. They scrolled! So, by definition, they aren't at the top anymore! But that doesn't deal with when they scroll back to the top.

I find it generally more useful to use IntersectionObserver for styling things based on scroll position. With it, you can do things like, "has this element been scrolled into view or beyond," which is generically useful and can be used for scrolled-away-from-top stuff too.

Here's an example that adds or removes a class if a user has scrolled past a hidden pixel positioned at 500px down the page.

See the Pen
Fixed Header with IntersectionObserver
by Chris Coyier (@chriscoyier)
on CodePen.

That's performant as well, avoiding any scroll event handlers at all.

And speaking of IntersectionObserver, check out "Trust is Good, Observation is Better—Intersection Observer v2".

The post Styling Based on Scroll Position appeared first on CSS-Tricks.

8 Little Videos About the Firefox Shape Path Editor

Css Tricks - Thu, 03/07/2019 - 5:18am

It sometimes takes a quick 35 seconds for a concept to really sink in. Mikael Ainalem delivers that here, in the case that you haven't quite grokked the concepts behind path-based CSS properties like clip-path and shape-outside.

Here are two of my favorites. The first demonstrates animating text into view using a polygon as a clip.

The second shows how the editor can help morph one shape into another.

Direct Link to ArticlePermalink

The post 8 Little Videos About the Firefox Shape Path Editor appeared first on CSS-Tricks.

Level up your JavaScript error monitoring

Css Tricks - Thu, 03/07/2019 - 5:17am

(This is a sponsored post.)

Automatically detect and diagnose JavaScript errors impacting your users with Bugsnag. Get comprehensive diagnostic reports, know immediately which errors are worth fixing, and debug in a fraction of the time.

Bugsnag detects every single error and prioritizes errors with the greatest impact on your users. Get support for 50+ platforms and integrate with the development and productivity tools your team already uses.

Bugsnag is used by the world's top engineering teams including Airbnb, Slack, Pinterest, Lyft, Square, Yelp, Shopify, Docker, and Cisco. Start your free trial today.

Direct Link to ArticlePermalink

The post Level up your JavaScript error monitoring appeared first on CSS-Tricks.

Using React Loadable for Code Splitting by Components and Routes

Css Tricks - Wed, 03/06/2019 - 2:07pm

In a bid to have web applications serve needs for different types of users, it’s likely that more code is required than it would be for one type of user so the app can handle and adapt to different scenarios and use cases, which lead to new features and functionalities. When this happens, it’s reasonable to expect the performance of an app to dwindle as the codebase grows.

Code splitting is a technique where an application only loads the code it needs at the moment, and nothing more. For example, when a user navigates to a homepage, there is probably no need to load the code that powers a backend dashboard. With code splitting, we can ensure that the code for the homepage is the only code that loads, and that the cruft stays out for more optimal loading.

Code splitting is possible in a React application using React Loadable. It provides a higher-order component that can be set up to dynamically import specific components at specific times.

Component splitting

There are situations when we might want to conditionally render a component based on a user event, say when a user logs in to an account. A common way of handling this is to make use of state — the component gets rendered depending on the logged in state of the app. We call this component splitting.

Let’s see how that will look in code.

See the Pen
React-Loadable
by Kingsley Silas Chijioke (@kinsomicrote)
on CodePen.

As a basic example, say we want to conditionally render a component that contains an <h2> heading with “Hello.” Like this:

const Hello = () => { return ( <React.Fragment> <h2>Hello</h2> </React.Fragment> ) }

We can have an openHello state in the App component with an initial value of false. Then we can have a button used to toggle the state, either display the component or hide it. We’ll throw that into a handleHello method, which looks like this:

class App extends React.Component { state = { openHello: false } handleHello = () => { this.setState({ openHello: !this.state.openHello }) } render() { return ( <div className="App"> <button onClick={this.handleHello}> Toggle Component </button> { this.state.openHello ? <Hello /> : null } </div> ); } }

Take a quick peek in DevTools and take note the Network tab:

Now, let’s refactor to make use of LoadableHello. Instead of importing the component straight up, we will do the import using Loadable. We’ll start by installing the react-loadable package:

## yarn, npm or however you roll yarn add react-loadable

Now that’s been added to our project, we need to import it into the app:

import Loadable from 'react-loadable';

We’ll use Loadable to create a “loading” component which will look like this:

const LoadableHello = Loadable({ loader: () => import('./Hello'), loading() { return <div>Loading...</div> } })

We pass a function as a value to loader which returns the Hello component we created earlier, and we make use of import() to dynamically import it. The fallback UI we want to render before the component is imported is returned by loading(). In this example, we are returning a div element, though we can also put a component in there instead if we want.

Now, instead of inputting the Hello component directly in the App component, we’ll put LoadableHello to the task so that the conditional statement will look like this:

{ this.state.openHello ? <LoadableHello /> : null }

Check this out — now our Hello component loads into the DOM only when the state is toggled by the button:

And that’s component splitting: the ability to load one component to load another asynchronously!

Route-based splitting

Alright, so we saw how Loadable can be used to load components via other components. Another way to go about it is us ing route-based splitting. The difference here is that components are loaded according to the current route.

So, say a user is on the homepage of an app and clicks onto a Hello view with a route of /hello. The components that belong on that route would be the only ones that load. It’s a fairly common way of handling splitting in many apps and generally works well, especially in less complex applications.

Here’s a basic example of defined routes in an app. In this case, we have two routes: (1) Home (/) and (2) Hello (/hello).

class App extends Component { render() { return ( <div className="App"> <BrowserRouter> <div> <Link to="/">Home</Link> <Link to="/hello">Hello</Link> <Switch> <Route exact path="/" component={Home} /> <Route path="/hello" component={Hello} /> </Switch> </div> </BrowserRouter> </div> ); } }

As it stands, all components will render when a use switches paths, even though we want to render the one Hello component based on that path. Sure, it’s not a huge deal if we’re talking a few components, but it certainly could be as more components are added and the application grows in size.

Using Loadable, we can import only the component we want by creating a loadable component for each:

const LoadableHello = Loadable({ loader: () => import('./Hello'), loading() { return <div>Loading...</div> } }) const LoadableHome = Loadable({ loader: () => import('./Home'), loading() { return <div>Loading...</div> } }) class App extends Component { render() { return ( <div className="App"> <BrowserRouter> <div> <Link to="/">Home</Link> <Link to="/hello">Hello</Link> <Switch> <Route exact path="/" component={LoadableHome} /> <Route path="/hello" component={LoadableHello} /> </Switch> </div> </BrowserRouter> </div> ); } }

Now, we serve the right code at the right time. Thanks, Loadable!

What about errors and delays?

If the imported component will load fast, there is no need to flash a “loading” component. Thankfully, Loadable has the ability to delay the loading component from showing. This is helpful to prevent it from displaying too early where it feels silly and instead show it after a notable period of time has passed where we would expect to have seen it loaded.

To do that, our sample Loadable component will look like this;

const LoadableHello = Loadable({ loader: () => import('./Hello'), loading: Loader, delay: 300 })

Here, we are passing the Hello component as a value to loading, which is imported via loader. By default, delay is set to 200ms, but we’ve set ours a little later to 300ms.

Now let’s add a condition to the Loader component that tells it to display the loader only after the 300ms delay we set has passed:

const Loader = (props) => { if (props.pastDelay) { return <h2>Loading...</h2> } else { return null } }

So the Loader component will only show if the Hello component does not show after 300ms.

react-loader also gives us an error prop which we can use to return errors that are encountered. And, because it is a prop, we can let it spit out whatever we want.

const Loader = (props) => { if (props.error) { return <div>Oh no, something went wrong!</div>; } else if (props.delay) { return <h2>Loading...</h2> } else { return null; } }

Note that we’re actually combining the delay and error handling together! If there’s an error off the bat, we’ll display some messaging. If there’s no error, but 300ms have passed, then we’ll show a loader. Otherwise, load up the Hello component, please!

That’s a wrap

Isn’t it great that we have more freedom and flexibility in how we load and display code these days? Code splitting — either by component or by route — is the sort of thing React was designed to do. React allows us to write modular components that contain isolated code and we can serve them whenever and wherever we want and allow them to interact with the DOM and other components. Very cool!

Hopefully this gives you a good feel for code splitting as a concept. As you get your hands dirty and start using it, it’s worth checking out more in-depth posts to get a deeper understanding of the concept.

The post Using React Loadable for Code Splitting by Components and Routes appeared first on CSS-Tricks.

Native Video on the Web

Css Tricks - Wed, 03/06/2019 - 11:33am

TIL about the HLS video format:

HLS stands for HTTP Live Streaming. It’s an adaptive bitrate streaming protocol developed by Apple. One of those sentences to casually drop at any party. Äh. Back on track: HLS allows you to specify a playlist with multiple video sources in different resolutions. Based on available bandwidth these video sources can be switched and allow adaptive playback.

This is an interesting journey where the engineering team behind Kitchen Stories wanted to switch away from the Vimeo player (160 kB), but still use Vimeo as a video host because they provide direct video links with a Pro plan. Instead, they are using the native <video> element, a library for handling HLS, and a wrapper element to give them a little bonus UX.

This video stuff is hard to keep up with! There is another new format called AV1 that is apparently a big deal as YouTube and Netflix are both embracing it. Andrey Sitnik wrote about it here:

Even though AV1 codec is still considered experimental, you can already leverage its high-quality, low-bitrate features for a sizable chunk for your web audience (users with current versions of Chrome and Firefox). Of course, you would not want to leave users for other browsers hanging, but the attributes for <video> and <source> tags make implementing this logic easy, and in pure HTML, you don’t need to go at length to detect user agents with JavaScript.

That doesn't even mention HLS, but I suppose that's because HSL is a streaming protocol, which still needs to stream in some sort of format.

Direct Link to ArticlePermalink

The post Native Video on the Web appeared first on CSS-Tricks.

CSS Algorithms

Css Tricks - Wed, 03/06/2019 - 9:13am

I wouldn't say the term "CSS algorithm" has widespread usage yet, but I think Lara Schenck might be onto something. She defines it as:

a well-defined declaration or set of declarations that produces a specific styling output

So a CSS algorithm isn't really a component where there is some parent element and whatever it needs inside, but a CSS algorithm could involve components. A CSS algorithm isn't just some tricky key/value pair or calculated output — but it could certainly involve those things.

The way I understand it is that they are little mini systems. In a recent post, she describes a situation involving essentially two fixed header bars and needing to deal with them in different situations. In this example, the page can be in different states (e.g. a logged-in state has a position: fixed; bar), and that affects not only the header but the content area as well. Dealing with all that together is a CSS algorithm. It's probably the way we all work in CSS already, but now have a term to describe it. This particular example involves some CSS custom properties, a state-based class, two selectors, and a media query. Classic front-end developer stuff.

Lara is better at explaining what she means though. You should read her initial blog post, main blog post, collection of examples, and talk on the subject.

She'll be at PPK's CSS Day in June (hey, it's on our conferences list!), and the idea has clearly stirred up some thoughts from him.

Direct Link to ArticlePermalink

The post CSS Algorithms appeared first on CSS-Tricks.

Extracting Text from Content Using HTML Slot, HTML Template and Shadow DOM

Css Tricks - Wed, 03/06/2019 - 6:04am

Chapter names in books, quotes from a speech, keywords in an article, stats on a report — these are all types of content that could be helpful to isolate and turn into a high-level summary of what's important.

For example, have you seen the way Business Insider provides an article's key points before getting into the content?

That’s the sort of thing we're going to do, but try to extract the high points directly from the article using HTML Slot, HTML Template and Shadow DOM.

These three titular specifications are typically used as part of Web Components — fully functioning custom element modules meant to be reused in webpages.

Now, what we aim to do, i.e. text extraction, doesn’t need custom elements, but it can make use of those three technologies.

There is a more rudimentary approach to do this. For example, we could extract text and show the extracted text on a page with some basic script without utilizing slot and template. So why use them if we can go with something more familiar?

The reason is that using these technologies permits us a preset markup code (also optionally, style or script) for our extracted text in HTML. We’ll see that as we proceed with this article.

Now, as a very watered-down definition of the technologies we’ll be using, I’d say:

  • A template is a set of markup that can be reused in a page.
  • A slot is a placeholder spot for a designated element from the page.
  • A shadow DOM is a DOM tree that doesn’t really exist on the page till we add it using script.

We’ll see them in a little more depth once we get into coding. For now, what we’re going to make is an article that follows with a list of key points from the text. And, you probably guessed it, those key points are extracted from the article text and compiled into the key points section.

See the Pen
Text Extraction with HTML Slot and HTML Template
by Preethi Sam (@rpsthecoder)
on CodePen.

The key points are displayed as a list with a design in between the points. So, let’s first create a template for that list and designate a place for the list to go.

<article><!-- Article content --></article> <!-- Section where the extracted keypoints will be displayed --> <section id='keyPointsSection'> <h2>Key Points:</h2> <ul><!-- Extracted key points will go in here --></ul> </section> <!-- Template for the key points list --> <template id='keyPointsTemplate'> <li><slot name='keyPoints'></slot></li> <li style="text-align: center;">&#x2919;&mdash;&#x291a;</li> </template>

What we’ve got is a semantic <section> with a <ul> where the list of key points will go. Then we have a <template> for the list items that has two <li> elements: one with a <slot> placeholder for the key points from the article and another with a centered design.

The layout is arbitrary. What’s important is placing a <slot> where the extracted key points will go. Whatever’s inside the <template> will not be rendered on the page until we add it to the page using script.

Further, the markup inside <template> can be styled using inline styles, or CSS enclosed by <style>:

<template id='keyPointsTemplate'> <li><slot name='keyPoints'></slot></li> <li style="text-align: center;">&#x2919;&mdash;&#x291a;</li> <style> li{/* Some style */} </style> </template>

The fun part! Let’s pick the key points from the article. Notice the value of the name attribute for the <slot> inside the <template> (keyPoints) because we’ll need that.

<article> <h1>Bears</h1> <p>Bears are carnivoran mammals of the family Ursidae. <span><span slot='keyPoints'>They are classified as caniforms, or doglike carnivorans</span></span>. Although only eight species of bears <!-- more content --> and partially in the Southern Hemisphere. <span><span slot='keyPoints'>Bears are found on the continents of North America, South America, Europe, and Asia</span></span>.<!-- more content --></p> <p>While the polar bear is mostly carnivorous, <!-- more content -->. Bears use shelters, such as caves and logs, as their dens; <span><span slot='keyPoints'>Most species occupy their dens during the winter for a long period of hibernation</span></span>, up to 100 days.</p> <!-- More paragraphs --> </article>

The key points are wrapped in a <span> carrying a slot attribute value ("keyPoints") matching the name of the <slot> placeholder inside the <template>.

Notice, too, that I’ve added another outer <span> wrapping the key points.

The reason is that slot names are usually unique and are not repeated, because one <slot> matches one element using one slot name. If there’re more than one element with the same slot name, the <slot> placeholder will be replaced by all those elements consecutively, ending in the last element being the final content at the placeholder.

So, if we matched that one single <slot> inside the <template> against all of the <span> elements with the same slot attribute value (our key points) in a paragraph or the whole article, we’d end up with only the last key point present in the paragraph or the article in place of the <slot>.

That’s not what we need. We need to show all the key points. So, we’re wrapping the key points with an outer <span> to match each of those individual key points separately with the <slot>. This is much more obvious by looking at the script, so let’s do that.

const keyPointsTemplate = document.querySelector('#keyPointsTemplate').content; const keyPointsSection = document.querySelector('#keyPointsSection > ul'); /* Loop through elements with 'slot' attribute */ document.querySelectorAll('[slot]').forEach((slot)=>{ let span = slot.parentNode.cloneNode(true); span.attachShadow({ mode: 'closed' }).appendChild(keyPointsTemplate.cloneNode(true)); keyPointsSection.appendChild(span); });

First, we loop through every <span> with a slot attribute and get a copy of its parent (the outer <span>). Note that we could also loop through the outer <span> directly if we’d like, by giving them a common class value.

The outer <span> copy is then attached with a shadow tree (span.attachShadow) made up of a clone of the template’s content (keyPointsTemplate.cloneNode(true)).

This "attachment" causes the <slot> inside the template’s list item in the shadow tree to absorb the inner <span> carrying its matching slot name, i.e. our key point.

The slotted key point is then added to the key points section at the end of the page (keyPointsSection.appendChild(span)).

This happens with all the key points in the course of the loop.

That’s really about it. We’ve snagged all of the key points in the article, made copies of them, then dropped the copies into the list template so that all of the key points are grouped together providing a nice little CliffsNotes-like summary of the article.

Here's that demo once again:

See the Pen
Text Extraction with HTML Slot and HTML Template
by Preethi Sam (@rpsthecoder)
on CodePen.

What do you think of this technique? Is it something that would be useful in long-form content, like blog posts, news articles, or even Wikipedia entries? What other use cases can you think of?

The post Extracting Text from Content Using HTML Slot, HTML Template and Shadow DOM appeared first on CSS-Tricks.

The Client/Server Rendering Spectrum

Css Tricks - Wed, 03/06/2019 - 5:52am

I've definitely been guilty of thinking about rendering on the web as a two-horse race. There is Server-Side Rendering (SSR, like this WordPress site is doing) and Client-Side Rendering (CSR, like a typical React app). Both are full of advantages and disadvantages. But, of course, the conversation is more nuanced. Just because an app is SSR doesn't mean it doesn't do dynamic JavaScript-powered things. And just because an app is CSR doesn't mean it can't leverage any SSR at all.

It's a spectrum! Jason Miller and Addy Osmani paint that picture nicely in Rendering on the Web.

My favorite part of the article is the infographic table they post at the end of it. Unfortunately, it's a PNG. So I took a few minutes and <table>-ized it, in case that's useful to anyone.

See the Pen
The Client/Server Rendering Spectrum
by Chris Coyier (@chriscoyier)
on CodePen.

Direct Link to ArticlePermalink

The post The Client/Server Rendering Spectrum appeared first on CSS-Tricks.

Refactoring Tunnels

Css Tricks - Wed, 03/06/2019 - 5:51am

We’ve been writing a lot about refactoring CSS lately, from how to take a slow and methodical approach to getting some quick wins. As a result, I’ve been reading a ton about this topic and somehow stumbled upon this post by Harry Roberts about refactoring and how to mitigate the potential risks that come with it:

Refactoring can be scary. On a sufficiently large or legacy application, there can be so much fundamentally wrong with the codebase that many refactoring tasks will run very deep throughout the whole project. This puts a lot of pressure on developers, especially considering that this is their chance to "get it right this time". This can feel debilitating: "Where do I start?" "How long is this going to take?" "How will I know if I’m doing the right thing?"

Harry then comes up with this metaphor of a refactoring tunnel where it’s really easy to find yourself stuck in the middle of a refactor and without any way out of it. He argues that we should focus on small, manageable pieces instead of trying to tackle everything at once:

Resist the temptation to refactor anything that runs right the way throughout the project. Instead, identify smaller and more manageable tasks: tasks that have a much smaller surface area, and therefore a much shorter Refactoring Tunnel.

These tasks can still aim toward a larger and more total goal but can be realised in much safer and shorter timeframes. Want to move all of your classes from BEM to BEM(IT)? Sure, but maybe just implement it on the nav first.

This way feels considerably slower, for sure, but there’s so much less risk involved.

Direct Link to ArticlePermalink

The post Refactoring Tunnels appeared first on CSS-Tricks.

Algorithms in CSS

QuirksBlog - Tue, 03/05/2019 - 7:02am

I am likely going to write a “CSS for JavaScripters” book, and therefore I need to figure out how to explain CSS to JavaScripters. This series of article snippets are a sort of try-out — pre-drafts I’d like to get feedback on in order to figure out if I’m on the right track.

Today we’ll discuss the writing of CSS algorithms, inspired by Lara Schenck’s excellent article on that topic, which states that not only CSS is a programming language, but you can write algorithms in it.

What follows are my words; not hers — I have different points to make, and give different examples. If you want to hear Lara’s own words on CSS algorithms, drop by at CSS Day, 13th and 14th of June, Amsterdam, where she will speak.

CSS as a programming language

Is CSS a programming language? That's a hard question. In a Twitter poll I conducted in February 2019, 47% of the 3,000 or so participants said that CSS is a prorgamming language, while 53% said it is not.

So there’s no agreement on this — it all depends on your definition of a programming language. If a programming language must be imperative, then no, CSS isn't. If a programming language is anything that gives computers instructions to do anything, then yes, CSS is.

But there’s a more important question: does it matter? Does the fact that CSS is, or is not, a programming language make it easier for you to learn? Let’s discuss CSS algorithm design, which presupposes CSS is in fact a programming language, and see if it helps.

Algorithms in CSS

Saying you write algorithms in CSS is a psychological trick that can put you, and, more importantly, your co-workers, in the right frame of mind for approaching tricky CSS problems.

You should think before you start coding; that’s just as true in CSS as it is in JavaScript. If, for instance, you need a certain layout it is worthwhile to make a quick sketch and decide on your overall approach. Will you use grid, flexbox, floats, or even absolute positioning? (The last two options are not really recommended, by the way.) Will you mix approaches; for instance grid for the overall layout, but flexbox for the naviation bar?

Thinking about these issues before you start coding will save you a lot of work in the long run, just like thinking about the structure of your JavaScript app before you write it helps you create it more quickly.

Now if you slap the name “algorithm design” on this process you achieve several goals. You are able to explain to programmers why you’re doodling boxes in boxes while making cryptic notes about grid gaps and flex bases. You invite those that are new to CSS to share your exploration of a layout problem, and can quickly introduce them to the pros and cons of grids and flexbox. (And remember: the best way to really learn something is to explain it to someone else.)

Naming things

Most importantly, naming things gives you power over them: if a bunch of disconnected doodles and notes become an algorithm design, you grant them the much higher status of a computer problem. And engineers exist to solve tricky computer problems, don’t they? Here, let me show you why I think flexbox is the right approach in this situation ... and before you know it your co-workers will become as engrossed as you are in the details of this exciting new algorithm.

Once the doodling-and-thinking phase that we now call algorithm design is over, you should whip up some proof-of-concept code (it’s OK if it’s ugly), show that your approach will work (or that it won’t, which is also useful data), then test your ugly code in several contexts, and finally iterate until the code is cleaner and more understandable to others.

You’re doing just the same as when you would write a tricky JavaScript module, in other words. Go from design via prototyping and testing to optimsation — and the fact that you use a different programming language doesn’t matter. Meanwhile the magic word “algorithm” will make sure that everyone understands you’re doing some real programming here.

Cool, huh? The power names have!

The Bottleneck of the Web

Css Tricks - Tue, 03/05/2019 - 5:37am

Steve Souders, "JavaScript Dominates Browser CPU":

Ten years ago the network was the main bottleneck. Today, the main bottleneck is JavaScript. The amount of JavaScript on pages is growing rapidly (nearly 5x in the last 7 years). In order to keep pages rendering and feeling fast, we need to focus on JavaScript CPU time to reduce blocking the browser main thread.

Alex Russell, describing a prototype of "Never-Slow Mode" in Chrome:

... blocks large scripts, sets budgets for certain resource types (script, font, css, images), turns off document.write(), clobbers sync XHR, enables client-hints pervasively, and buffers resources without Content-Length set.

Craig Hockenberry, posting an idea to the WebKit bug tracker:

Without limits, there is no incentive for a JavaScript developer to keep their codebase small and dependencies minimal. It's easy to add another framework, and that framework adds another framework, and the next thing you know you're loading tens of megabytes of data just to display a couple hundred kilobytes of content. ...

The situation I'm envisioning is that a site can show me any advertising they want as long as they keep the overall size under a fixed amount, say one megabyte per page. If they work hard to make their site efficient, I'm happy to provide my eyeballs.

It's easy to point a finger at frameworks and third-party scripts for large amounts of JavaScript. If you're interested in hearing more about the size of frameworks, you might enjoy me and Dave discussing it with Jason Miller.

And speaking of third-parties, Patrick Hulce created Third Party Web: "This document is a summary of which third-party scripts are most responsible for excessive JavaScript execution on the web today."

Sometimes name-and-shame is an effective tactic to spark change.

Addy Osmani writes about an ESLint rule that prohibits particular packages, of which you could use to prevent usage of known-to-be-huge packages. So if someone tries to load the entirety of lodash or moment.js, it can be stopped at the linting level.

Tim Kadlec ties the threads together very well in "Limiting JavaScript?" If your gut reaction on this is that JavaScript is being unfairly targeted as a villain, Tim acknowledges that:

One common worry I saw voiced was “if JavaScript, why not other resources too?”. It’s true; JavaScript does get picked on a lot though it’s not without reason. Byte for byte, JavaScript is the most significant detriment to performance on the web, so it does make sense to put some focus on reducing the amount we use.

However, the point is valid. JavaScript may be the biggest culprit more often than not, but it’s not the only one.

The post The Bottleneck of the Web appeared first on CSS-Tricks.

Why I Write CSS in JavaScript

Css Tricks - Tue, 03/05/2019 - 5:36am

I'm never going to tell you that writing your CSS in CSS (or some syntactic preprocessor) is a bad idea. I think you can be perfectly productive and performant without any tooling at all. But, I also think writing CSS in JavaScript is a good idea for component-based styles in codebases that build all their components with JavaScript anyway.

In this article, Max Stoiber focuses on why to write CSS in JavaScript rather than how to do it. There is one reason that resonates strongly with me, and that's confidence. This is what styling confidence means to me.

  • Anyone on a team can work on styling a component without any fear of unintended side effects.
  • There is no pressure to come up with perfect names that will work now and forever.
  • There is no worry about the styles needing to be extremely re-usable or that they play friendly with anything else. These styles will only be used when needed and not any other time.
  • There is an obvious standard to where styles are placed in the codebase.
  • CSS in JavaScript isn't the only answer to those things, but as Max connects to other posts on the topic, it can lead to situations where good choices happen naturally.

    There are some reasons why I don't buy into it. Performance is one of them, like choosing CSS-in-JS is some automatic performance win. Part of the problem (and I'm guilty of doing it right here) is that CSS-in-JS is a wide scope of solutions. I've generally found there is no big performance wins in CSS-in-JS (more likely the opposite), but that's irrelevant if we're talking about something like CSS modules with the styles extracted and linked up like any other CSS.

    Direct Link to ArticlePermalink

    The post Why I Write CSS in JavaScript appeared first on CSS-Tricks.

    CSS Triangles, Multiple Ways

    Css Tricks - Mon, 03/04/2019 - 2:35pm

    I like Adam Laki's Quick Tip: CSS Triangles because it covers that ubiquitous fact about front-end techniques: there are always many ways to do the same thing. In this case, drawing a triangle can be done:

    • with border and a collapsed element
    • with clip-path: polygon()
    • with transform: rotate() and overflow: hidden
    • with glyphs like ?

    I'd say that the way I've typically done triangles the most over the years is with the border trick, but I think my favorite way now is using clip-path. Code like this is fairly clear, understandable, and maintainable to me: clip-path: polygon(50% 0, 0 100%, 100% 100%); Brain: Middle top! Bottom right! Bottom left! Triangle!

    My 2nd Place method goes to an option that didn't make Adam's list: inline <svg>! This kind of thing is nearly just as brain-friendly: <polygon points="0,0 100,0 50,100"/>.

    Direct Link to ArticlePermalink

    The post CSS Triangles, Multiple Ways appeared first on CSS-Tricks.

    Learning to Learn

    Css Tricks - Mon, 03/04/2019 - 5:19am

    There’s been a lot of talk recently about whether or not you need a degree to be in tech (spoiler: you don’t). But please don’t take this to mean you don’t need any kind of education to be in tech, because by not getting a degree, you’re opting to replace the imposed learning structure of an academy with learning on your own.

    Academic background or not, technical education doesn’t stop once you get a job. On the contrary: nothing in tech stays in one place, and the single most valuable skill you can possess to remain employable over time is learning how to learn.

    Identifying holes

    You’re all ready to go, ready to challenge yourself, learn what you can, and grow. But where do you start? Sometimes people rely on a more formal education simply because someone is there, guiding your path.

    When you’re learning on your own, this part can sometimes be tough — you don’t know what you don’t know. If you’re starting from scratch, learning web development or computer science, here are some resources that might help:

    There are also times when you know what you need to learn, but you have to level up. In this case, I have some strategies on how to organize yourself in the next section.

    Possible strategies

    You absolutely do not to be as formal in your approach to learning as I am. I used to be a college professor, and so I still organize my own learning as though I’m teaching. I even still use a paper planner designed for teachers. I’ll show you how I do it in case it’s helpful. A few years back I taught myself ES2015/ES6, so I'll use that as an example. Structure like this is good for some and not good for others, so do what works for you.

    If there’s an API I’m trying to learn, I’ll go to the main documentation page (if there is one), and list each of the things I’m trying to learn. Then I’ll divide the sections into what I think are manageable chunks, and spread the sections over my schedule, usually shooting for about a half hour a day. I do this with the understanding that some days I won’t find the time, and others, I’ll dig in for longer. Typically I aim for at least 2.5 hours of learning a week, because that pace seems reasonable to me.

    The list of ES2015 features I used when I was learning

    Then I take all of those features, write them out, and estimate how much time I'll need for each one. Here’s an example where I wrote out all the things I needed to learn. The yellow numbers on the side are my time estimates in half hour units.

    You can also do this with course materials from an online workshop, writing down the sections and breaking them into chunks to go over every day. I really enjoy Frontend Masters for long form learning like this, as well as Egghead and courses by Wes Bos.

    At this point, I'll break those pieces down and schedule them. The teacher planner allows me to divide my days into the different themes I'm focusing on and put a little in each day. You can see in the first screenshot that I was learning a bit, mentoring a bit, and writing and building what I was learning each day. This kind of input/output really helped me solidify the concepts as I was digging into ES2015/ES6.

    I try not to schedule too far out because I'm bound to drop something here and there, or I might dive further one day than I was planning to. I keep the schedules flexible enough to adjust for these inevitable inconsistencies. This also allows me to not get too demotivated. If I feel I'm off-track, the next week is another opportunity to get back on.

    Again, you don't have to be as formal as I am, and there are so many ways to be effective. Find what works for you. I would make a small suggestion that you're taking a look at the table of contents for those API docs now and again, mostly because then you're aware of any gaps in your knowledge that you're not filling.

    Setting aside time

    Setting aside time can be challenging with all of our busy schedules, but it's critical. If you look at your week, how much time do you have? Learning won’t happen unless you purposefully devote time for it. It needn’t be a ton of time. If you’re a more habit-driven kind of person, you can set up a daily schedule. If you’re the kind of person who learns better head down and you have an existing job, then you might have to give up some Sunday afternoons, or possibly some time after work now and again. Most of us need a bit of both. ☺️

    If you’re socially motivated, you might want to find a study buddy. Is there someone at work who has similar goals? Maybe going to coding meetups can help keep you on track. Emma Wedekind also builds Coding Coach, where you can have guided mentorship sessions.

    Practice

    At the end of the day, it's going to come down to practice. If you read about Cognitive Load Theory (I highly recommend the book Cognitive Load Theory if you want to learn about this), you'll see that the old "practice makes perfect" adage has some bite to it.

    Information Processing Model (how we learn) - Richard Atkinson and Richard Shiffrin's cognitive load theory, 1968.

    I also really like this quote from Zed Shaw’s Learn Python the Hard Way.

    Do Not Copy-Paste
    You must type each of these exercises in, manually. If you copy and paste, you might as well just not even do them. The point of these exercises is to train your hands, your brain, and your mind in how to read, write, and see code. If you copy-paste, you are cheating yourself out of the effectiveness of the lessons.

    I also love this quote from Art and Fear, and bring it up frequently as it's been a guiding light for me:

    The ceramics teacher announced on opening day that he was dividing the class into two groups. All those on the left side of the studio, he said, would be graded solely on the quantity of work they produced, all those on the right solely on its quality. His procedure was simple: on the final day of class he would bring in his bathroom scales and weigh the work of the "quantity" group: fifty pounds of pots rated an "A", forty pounds a "B", and so on. Those being graded on "quality", however, needed to produce only one pot —albeit a perfect one —to get an "A". Well, came grading time and a curious fact emerged: the works of highest quality were all produced by the group being graded for quantity. It seems that while the "quantity" group was busily churning out piles of work—and learning from their mistakes —the "quality" group had sat theorizing about perfection, and in the end had little more to show for their efforts than grandiose theories and a pile of dead clay.

    Learning modalities

    Truly there are many different learning modalities, and combining them can even be helpful. Sometimes I will sit and practice refactoring code from other languages into JavaScript (this is a pretty old project now), or reverse engineer things to learn. I like reverse engineering because people tend to problem-solve in different ways. This allows me to peek inside other people’s heads and see how they approach things. I even have a private collection on CodePen where I collect other people's work that I think can benefit me and my learning.

    Personally, I think there’s nothing more motivating than building. You can actually learn a metric ton just by building things.

    Storytime: Many years ago, I was at a conference with a few people who worked on the SVG spec, including the inventor of SVG himself. I was completely unknown at the time, but had been churning out tons of SVG animations that were wildly unpopular for a few years. We got on the subject of a certain behavior that was in the spec. I mentioned, that yes, it should work that way but unfortunately Firefox had x behavior and Chrome had y.

    No one in the group knew this, and it was the first time I realized that all those silly playful things I was building were actually educating me; that I knew practical, real-life edge cases even though I hadn’t sought them out in a formal manner. I was so excited! I didn’t plan to become an SVG expert — it snuck up on me as I enjoyed myself, building things to relieve stress and play.

    This is good news! You can learn so much by creating things you think are fun. I like to learn for a bit, and then practice what I learned by making something, just to make sure I solidify the concepts.

    You may find you learn the most by teaching. If you do have a person you can mentor, it can actually benefit you, too. Writing technical posts or helping with documentation can help you learn something concretely as well.

    Cognitive Load Theory

    The book I cited earlier, Cognitive Load Theory, has this great section breaking down learning modalities and what they require. A central theme to the book is discussing moving information from a source into our own minds, and that there are certain capabilities and limitations affected by design characteristics of the learning structure and our own cognition.

    • Intrinsic load is created by the difficulty of the materials.
    • Extraneous load is created by the design characteristics of the type of education and materials.
    • Germane load is the amount of invested mental effort.

    The chart below explores effects of different ways that we learn, and what the primary cognitive load would be of the three listed above.

    From Cognitive Load Theory

    This kind of meta-understanding of what it takes to learn might be helpful to you in that you might find you have less cognitive load in one learning modality versus another. You may also find that you can cut yourself some slack when one topic with more germane load takes you longer to understand than another that's mostly memorization.

    Know that learning styles do affect our ability to comprehend things, and reducing barriers for yourself is key. Do you keep studying at a cafe where there's a lot of noise and distraction? Consider that your lack of focus might have more to do with the setting than your ability to process the materials.

    One more note on this: learning is hard, and it's humbling. It's exciting too, but please don't feel alone if you struggle, or if you need to repeat something multiple times to really get it. Even after taking care of cognitive leaks, expanding knowledge is not necessarily easy, but does pay off in dividends.

    Lifelong learners

    By choosing to be a developer, you are choosing to learn. This is amazing. Our field not only values our knowledge, but we can stave off boredom because it doesn’t stagnate. My suggestion is to consider these tips a buffet table. There’s so much you can do, so many tools you can use. You don't need to learn everything and no one knows absolutely everything. It can feel overwhelming, but try to view it less like a race to the finish and more like a continuous journey.

    Remember: no one was born knowing any of this. Even the experts you know started at zero. There's nothing stopping you from becoming their peer if that's your goal. Or simply learning enough to get the job done if that's what you need.

    The post Learning to Learn appeared first on CSS-Tricks.

    CSS Remedy

    Css Tricks - Mon, 03/04/2019 - 5:16am

    There is a 15-year history of CSS resets. In fact, a "reset" isn't really the right word. Tantek Çelik's take in 2004 was called "undohtml.css" and it wasn't until a few years later when Eric Meyer called his version a reset, that the word became the default term. When Normalize came around, it called itself a reset alternative, which felt right, because it wasn't trying to obliterate all styles, but instead bring the base styles that browsers provide in their User Agent Stylesheet in line with each other.

    We've taken a romp through this history before in Reboot, Resets, and Reasoning. Every single take on this — let's call them "base" stylesheets — has a bit of a different angle. How much does it try to preserve the UA defaults? How opinionated does it get? How far back does it consider for browser support?

    Along comes CSS Remedy (they say it's not ready for usage), with yet another different spin:

    Sets CSS properties or values to what they would be if the CSSWG were creating the CSS today, from scratch, and didn't have to worry about backwards compatibility.

    Fascinating to think about.

    CSS Remedy re-draws the line for what is opinionated and what isn't. I'd say that something like * { box-sizing: border-box; } is a fairly strong opinion for a base stylesheet to have. No UA stylesheet does this, so it's applying a blanket rule everywhere just because it's desirable. It's definitely desirable! It's just opinionated.

    But not having border-box be the default is considered a CSS mistake. So if CSS Remedy is what a UA stylesheet would be if we were starting from scratch, border-box isn't opinionated; it's the new default.

    Sadly, we probably can never have a fresh UA stylesheet in browsers, because the danger of breaking sites is so high. If Firefox shipped some new modernized UA stylesheet that was tastefully done and appears to be nice, but only until you browse around the billion websites that weren't built to handle the new CSS being applied to them, them people would blame Firefox — and not incorrectly. Gracefully handling legacy code is a massive strength of the web and something that holds us back. It's more the former than the latter, though.

    It's been fun watching Jen think through and gather thoughts on stuff like this though:

    img {
    display: inline;
    vertical-align: baseline; }

    is a dumb default for web development.

    Which would be better?

    img {
    display: inline;
    vertical-align: bottom; }
    (removes mysterious gap)

    or

    img {
    display: block; }
    (blockifies)https://t.co/UyBtRO6SAv

    — Jen Simmons (@jensimmons) February 10, 2019

    I agree! That little space below images has confounded an absolute ton of people. It's easy enough to fix, but it being the fault of vertical-align is a bit silly and a great candidate for fixing in what would be a new UA stylesheet.

    I tossed the in-progress version into the comparison tool:

    See the Pen
    HTML Kitchen-sink
    by Chris Coyier (@chriscoyier)
    on CodePen.

    Direct Link to ArticlePermalink

    The post CSS Remedy appeared first on CSS-Tricks.

    Mask Compositing: The Crash Course

    Css Tricks - Sat, 03/02/2019 - 5:28am

    At the start of 2018, as I was starting to go a bit deeper into CSS gradient masking in order to create interesting visuals one would think are impossible otherwise with just a single element and a tiny bit of CSS, I learned about a property that had previously been completely unknown to me: mask-composite.

    As this is not a widely used property, I couldn't find any comprehensive resources on this topic. So, as I began to use it more and learn more about it (some may remember I've mentioned it before in a couple of other articles), I decided to create such a resource myself and thus this article was born! Here, I'm covering how mask-composite works, why it's useful, what values it can take, what each of them does, where we are in terms of support and what alternatives we have in non-supporting browsers.

    What mask compositing does

    Mask compositing allows us to combine different mask layers into a single one using various operations. Combine them how? Well, pixel by pixel! Let's consider two mask layers. We take each pair of corresponding pixels, apply a certain compositing operation (we'll discuss each possible operation in detail a bit later) on their channels and get a third pixel for the resulting layer.

    How compositing two layers works at a pixel level.

    When compositing two layers, the layer on top is called the source, while the layer underneath is called the destination, which doesn't really make much sense to me because source sounds like an input and destination sounds like an output, but, in this case, they're both inputs and the output is the layer we get as a result of the compositing operation.

    Compositing terminology.

    When we have more than two layers, compositing is done in stages, starting from the bottom.

    In a first stage, the second layer from the bottom is our source and the first layer from the bottom is our destination. These two layers get composited and the result becomes the destination for the second stage, where the third layer from the bottom is the source. Compositing the third layer with the result of compositing the first two gives us the destination for the third stage, where the fourth layer from the bottom is the source.

    Compositing multiple layers.

    And so on, until we get to the final stage, where the topmost layer is composited with the result of compositing all the layers beneath.

    Why mask compositing is useful

    Both CSS and SVG masks have their limitations, their advantages and disadvantages. We can go around the limitations of SVG masks by using CSS masks, but, due to CSS masks working differently from SVG masks, taking the CSS route leaves us unable to achieve certain results without compositing.

    In order to better understand all of this, let's consider the following image of a pawesome Siberian tiger cub:

    The image we want to have masked on our page.

    And let's say we want to get the following masking effect on it:

    Desired result.

    This particular mask keeps the rhombic shapes visible, while the lines separating them get masked and we can see through the image to the element behind.

    We also want this masking effect to be flexible. We don't want to be tied to the image's dimensions or aspect ratio and we want to be able to easily switch (just by changing a % value to a px one) in between a mask that scales with the image and one that doesn't.

    In order to do this, we first need to understand how SVG and CSS masks each work and what we can and cannot do with them.

    SVG masking

    SVG masks are luminance masks by default. This means that the pixels of the masked element corresponding to the white mask pixels are fully opaque, the pixels of the masked element corresponding to black mask pixels are fully transparent and the pixels of the masked element corresponding to mask pixels somewhere in between black and white in terms of luminance (grey, pink, lime) are semitransparent.

    The formula used to get the luminance out of a given RGB value is:
    .2126·R + .7152·G + .0722·B

    For our particular example, this means we need to make the rhombic areas white and the lines separating them black, creating the pattern that can be seen below:

    Black and white rhombic pattern used as an SVG mask.

    In order to get the pattern above, we start with a white SVG rectangle element rect. Then, one might think we need to draw lots of black lines... but we don't! Instead, we only add a path made up of the two diagonals of this rectangle and ensure its stroke is black.

    To create the first diagonal (top left to bottom right), we use a "move to" (M) command to the top left corner, followed by a "line to" (L) command to the bottom right corner.

    To create the second diagonal (top right to bottom left), we use a "move to" (M) command to the top right corner, followed by a "line to" (L) command to the bottom left corner.

    Our code so far is:

    svg(viewBox=[0, 0, w, h].join(' ')) rect(width=w height=h fill='#fff') path(d=`M0 0 L${w} ${h} M${w} 0 L0 ${h}` stroke='#000')

    The result so far doesn't seem to look anything like the rhombic pattern we want to get...

    See the Pen by thebabydino (@thebabydino) on CodePen.

    ... but that's about to change! We increase the thickness (stroke-width) of the black diagonal lines and make them dashed with the gaps between the dashes (7%) bigger than the dashes themselves (1%).

    svg(viewBox=[0, 0, w, h].join(' ')) rect(width=w height=h fill='#fff') path(d=`M0 0 L${w} ${h} M${w} 0 L0 ${h}` stroke='#000' stroke-width='15%' stroke-dasharray='1% 7%')

    Can you now see where this is going?

    See the Pen by thebabydino (@thebabydino) on CodePen.

    If we keep increasing the thickness (stroke-width) of our black diagonal lines to a value like 150%, then they end up covering the entire rectangle and giving us the pattern we've been after!

    See the Pen by thebabydino (@thebabydino) on CodePen.

    Now we can wrap our rect and path elements inside a mask element and apply this mask on whatever element we wish - in our case, the tiger image.

    svg(viewBox=[0, 0, w, h].join(' ')) mask#m rect(width=w height=h fill='#fff') path(d=`M0 0 L${w} ${h} M${w} 0 L0 ${h}` stroke='#000' stroke-width='15%' stroke-dasharray='1% 7%') img(src='image.jpg' width=w) img { mask: url(#m) }

    The above should work. But sadly, things are not perfect in practice. At this point, we only get the expected result in Firefox (live demo). Even worse, not getting the desired masked pattern in Chrome doesn't mean our element stays as it is unmasked - applying this mask makes it disappear altogether! Of course, since Chrome needs the -webkit- prefix for the mask property (when used on HTML elements), not adding the prefix means that it doesn't even try to apply the mask on our element.

    The most straightforward workaround for img elements is to turn them into SVG image elements.

    svg(viewBox=[0, 0, w, h].join(' ') width=w) mask#m rect(width=w height=h fill='#fff') path(d=`M0 0 L${w} ${h} M${w} 0 L0 ${h}` stroke='#000' stroke-width='15%' stroke-dasharray='1% 7%') image(xlink:href=url width=w mask='url(#m)')

    See the Pen by thebabydino (@thebabydino) on CodePen.

    This gives us the result we've been after, but if we want to mask another HTML element, not an img one, things get a bit more complicated as we'd need to include it inside the SVG with foreignObject.

    Even worse, with this solution, we're hardcoding dimensions and this always feels yucky.

    Of course, we can make the mask ridiculously large so that it's unlikely there may be an image it couldn't cover. But that feels just as bad as hardcoding dimensions.

    We can also try tackling the hardcoding issue by switching the maskContentUnits to objectBoundingBox:

    svg(viewBox=[0, 0, w, h].join(' ')) mask#m(maskContentUnits='objectBoundingBox') rect(width=1 height=1 fill='#fff') path(d=`M0 0 L1 1 M1 0 L0 1` stroke='#000' stroke-width=1.5 stroke-dasharray='.01 .07') image(xlink:href=url width='100%' mask='url(#m)')

    But we're still hardcoding the dimensions in the viewBox and, while their actual values don't really matter, their aspect ratio does. Furthermore, our masking pattern is now created within a 1x1 square and then stretched to cover the masked element.

    Shape stretching means shape distortion, which is why is why our rhombic shapes don't look as they did before anymore.

    See the Pen by thebabydino (@thebabydino) on CodePen.

    Ugh.

    We can tweak the start and end points of the two lines making up our path:

    svg(viewBox=[0, 0, w, h].join(' ')) mask#m rect(width=1 height=1 fill='#fff') path(d=`M-.75 0 L1.75 1 M1.75 0 L-.75 1` stroke='#000' stroke-width=1.5 stroke-dasharray='.01 .07') image(xlink:href=url width='100%' mask='url(#m)')

    See the Pen by thebabydino (@thebabydino) on CodePen.

    However, in order to get one particular rhombic pattern, with certain angles for our rhombic shapes, we need to know the image's aspect ratio.

    Sigh. Let's just drop it and see what we can do with CSS.

    CSS masking

    CSS masks are alpha masks by default. This means that the pixels of the masked element corresponding to the fully opaque mask pixels are fully opaque, the pixels of the masked element corresponding to the fully transparent mask pixels are fully transparent and the pixels of the masked element corresponding to semitransparent mask pixels are semitransparent. Basically, each and every pixel of the masked element gets the alpha channel of the corresponding mask pixel.

    For our particular case, this means making the rhombic areas opaque and the lines separating them transparent, so let's how can we do that with CSS gradients!

    In order to get the pattern with white rhombic areas and black separating lines, we can layer two repeating linear gradients:

    See the Pen by thebabydino (@thebabydino) on CodePen.

    repeating-linear-gradient(-60deg, #000 0, #000 5px, transparent 0, transparent 35px), repeating-linear-gradient(60deg, #000 0, #000 5px, #fff 0, #fff 35px)

    This is the pattern that does the job if we have a luminance mask.

    But in the case of an alpha mask, it's not the black pixels that give us full transparency, but the transparent ones. And it's not the white pixels that give us full opacity, but the fully opaque ones - red, black, white... they all do the job! I personally tend to use red or tan as this means only three letters to type and the fewer letters to type, the fewer opportunities for awful typos that can take half an hour to debug.

    So the first idea is to apply the same technique to get opaque rhombic areas and transparent separating lines. But in doing so, we run into a problem: the opaque parts of the second gradient layer cover parts of the first layer we'd like to still keep transparent and the other way around.

    See the Pen by thebabydino (@thebabydino) on CodePen.

    So what we're getting is pretty far from opaque rhombic areas and transparent separating lines.

    My initial idea was to use the pattern with white rhombic areas and black separating lines, combined with setting mask-mode to luminance to solve the problem by making the CSS mask work like an SVG one.

    This property is only supported by Firefox, though there is the non-standard mask-source-type for WebKit browsers. And sadly, support is not even the biggest issue as neither the standard Firefox way, nor the non-standard WebKit way give us the result we're after (live demo).

    Fortunately, mask-composite is here to help! So let's see what values this property can take and what effect they each have.

    mask-composite values and what they do

    First, we decide upon two gradient layers for our mask and the image we want masked.

    The two gradient mask layers we use to illustrate how each value of this property works are as follows:

    --l0: repeating-linear-gradient(90deg, red, red 1em, transparent 0, transparent 4em); --l1: linear-gradient(red, transparent); mask: var(--l1) /* top (source) layer */, var(--l0) /* bottom (destination) layer */

    These two layers can be seen as background gradients in the Pen below (note that the body has a hashed background so that the transparent and semitransparent gradient areas are more obvious):

    See the Pen by thebabydino (@thebabydino) on CodePen.

    The layer on top (--l1) is the source, while the bottom layer (--l0) is the destination.

    We apply the mask on this image of a gorgeous Amur leopard.

    The image we apply the mask on.

    Alright, now that we got that out of the way, let's see what effect each mask-composite value has!

    add

    This is the initial value, which gives us the same effect as not specifying mask-composite at all. What happens in this case is that the gradients are added one on top of the other and the resulting mask is applied.

    Note that, in the case of semitransparent mask layers, the alphas are not simply added, in spite of the value name. Instead, the following formula is used, where ?? is the alpha of the pixel in the source (top) layer and ?? is the alpha of the corresponding pixel in the destination (bottom) layer:

    ?? + ?? – ??·??

    Wherever at least one mask layer is fully opaque (its alpha is 1), the resulting mask is fully opaque and the corresponding pixels of the masked element are shown fully opaque (with an alpha of 1).

    If the source (top) layer is fully opaque, then ?? is 1, and replacing in the formula above, we have:

    1 + ?? - 1·?? = 1 + ?? - ?? = 1

    If the destination (bottom) layer is fully opaque, then ?? is 1, and we have:

    ?? + 1 – ??·1 = ?? + 1 – ?? = 1

    Wherever both mask layers are fully transparent (their alphas are 0), the resulting mask is fully transparent and the corresponding pixels of the masked element are therefore fully transparent (with an alpha of 0) as well.

    0 + 0 – 0·0 = 0 + 0 + 0 = 0

    Below, we can see what this means for the mask layers we're using - what the layer we get as a result of compositing looks like and the final result that applying it on our Amur leopard image produces.

    What using mask-composite: add for two given layers does. subtract

    The name refers to "subtracting" the destination (layer below) out of the source (layer above). Again, this does not refer to simply capped subtraction, but uses the following formula:

    ??·(1 – ??)

    The above formula means that, since anything multiplied with 0 gives us 0, wherever the source (top) layer is fully transparent or wherever the destination (bottom) layer is fully opaque, the resulting mask is also fully transparent and the corresponding pixels of the masked element are also fully transparent.

    If the source (top) layer is fully transparent, replacing its alpha with 0 in our formula gives us:

    0·(1 – ??) = 0

    If the destination (bottom) layer is fully opaque, replacing its alpha with 1 in our formula gives us:

    ??·(1 – 1) = ??·0 = 0

    This means using the previously defined mask and setting mask-composite: subtract, we get the following:

    What using mask-composite: subtract for two given layers does.

    Note that, in this case, the formula isn't symmetrical, so, unless ?? and ?? are equal, we don't get the same thing if we swap the two mask layers (??·(1 – ??) isn't the same as ??·(1 – ??)). This means we have a different visual result if we swap the order of the two layers!

    Using mask-composite: subtract when the two given layers have been swapped. intersect

    In this case, we only see the pixels of the masked element from where the two mask layers intersect. The formula used is the product between the alphas of the two layers:

    ??·??

    What results from the formula above is that, wherever either mask layer is fully transparent (its alpha is 0), the resulting mask is also fully transparent and so are the corresponding pixels of the masked element.

    If the source (top) layer is fully transparent, replacing its alpha with 0 in our formula gives us:

    0·?? = 0

    If the destination (bottom) layer is fully transparent, replacing its alpha with 0 in our formula gives us:

    ??·0 = 0

    Also, wherever both mask layers are fully opaque (their alphas are 1), the resulting mask is fully opaque and so are the corresponding pixels of the masked element. This because, if the alphas of the two layers are both 1, we have:

    1·1 = 1

    In the particular case of our mask, setting mask-composite: intersect means we have:

    What using mask-composite: intersect for two given layers does. exclude

    In this case, each layer is basically excluded from the other, with the formula being:

    ??·(1 – ??) + ??·(1 – ??)

    In practice, this formula means that, wherever both mask layers are fully transparent (their alphas are 0) or fully opaque (their alphas are 1), the resulting mask is fully transparent and the corresponding pixels of the masked element are fully transparent as well.

    If both mask layers are fully transparent, our replacing their alphas with 0 in our formula results in:

    0·(1 – 0) + 0·(1 – 0) = 0·1 + 0·1 = 0 + 0 = 0

    If both mask layers are fully opaque, our replacing their alphas with 1 in our formula results in:

    1·(1 – 1) + 1·(1 – 1) = 1·0 + 1·0 = 0 + 0 = 0

    It also means that, wherever one layer is fully transparent (its alpha is 0), while the other one is fully opaque (its alpha is 1), then the resulting mask is fully opaque and so are the corresponding pixels of the masked element.

    If the source (top) layer is fully transparent, while the destination (bottom) layer is fully opaque, replacing ?? with 0 and ?? with 1 gives us:

    0·(1 – 1) + 1·(1 – 0) = 0·0 + 1·1 = 0 + 1 = 1

    If the source (top) layer is fully opaque, while the destination (bottom) layer is fully transparent, replacing ?? with 1 and ?? with 0 gives us:

    1·(1 – 0) + 0·(1 – 1) = 1·1 + 0·0 = 1 + 0 = 1

    With our mask, setting mask-composite: exclude means we have:

    What using mask-composite: exclude for two given layers does. Applying this to our use case

    We go back to the two gradients we attempted to get the rhombic pattern with:

    --l1: repeating-linear-gradient(-60deg, transparent 0, transparent 5px, tan 0, tan 35px); --l0: repeating-linear-gradient(60deg, transparent 0, transparent 5px, tan 0, tan 35px)

    If we make the completely opaque (tan in this case) parts semitransparent (let's say rgba(tan, .5)), the visual result gives us an indication of how compositing could help here:

    $c: rgba(tan, .5); $sw: 5px; --l1: repeating-linear-gradient(-60deg, transparent 0, transparent #{$sw}, #{$c} 0, #{$c} #{7*$sw}); --l0: repeating-linear-gradient(60deg, transparent 0, transparent #{$sw}, #{$c} 0, #{$c} #{7*$sw})

    See the Pen by thebabydino (@thebabydino) on CodePen.

    The rhombic areas we're after are formed at the intersection between the semitransparent strips. This means using mask-composite: intersect should do the trick!

    $sw: 5px; --l1: repeating-linear-gradient(-60deg, transparent 0, transparent #{$sw}, tan 0, tan #{7*$sw}); --l0: repeating-linear-gradient(60deg, transparent 0, transparent #{$sw}, tan 0, tan #{7*$sw}); mask: var(--l1) intersect, var(--l0)

    Note that we can even include the compositing operation in the shorthand! Which is something I really love, because the fewer chances of wasting at least ten minutes not understanding why masj-composite, msdk-composite, nask-composite, mask-comoisite and the likes don't work, the better!

    Not only does this give us the desired result, but, if now that we've stored the transparent strip width into a variable, changing this value to a % value (let's say $sw: .05%) makes the mask scale with the image!

    If the transparent strip width is a px value, then both the rhombic shapes and the separating lines stay the same size as the image scales up and down with the viewport.

    Masked image at two different viewport widths when the transparent separating lines in between the rhombic shapes have a px-valued width.

    If the transparent strip width is a % value, then both the rhombic shapes and the separating lines are relative in size to the image and therefore scale up and down with it.

    Masked image at two different viewport widths when the transparent separating lines in between the rhombic shapes have a %-valued width.

    Too good to be true? What's the support for this?

    The bad news is that mask-composite is only supported by Firefox at the moment. The good news is we have an alternative for WebKit browsers, so we can extend the support.

    Extending support

    WebKit browsers support (and have supported for a long, long time) a non-standard version of this property, -webkit-mask-composite which needs different values to work. These equivalent values are:

    • source-over for add
    • source-out for subtract
    • source-in for intersect
    • xor for exclude

    So, in order to have a cross-browser version, all we need to is add the WebKit version as well, right?

    Well, sadly, things are not that simple.

    First off, we cannot use this value in the -webkit-mask shorthand, the following does not work:

    -webkit-mask: var(--l1) source-in, var(--l0)

    And if we take the compositing operation out of the shorthand and write the longhand after it, as seen below:

    -webkit-mask: var(--l1), var(--l0); -webkit-mask-composite: source-in; mask: var(--l1) intersect, var(--l0)

    ... the entire image completely disappears!

    And if you think that's weird, check this: using any of the other three operations add/ source-over, subtract/ source-out, exclude/ xor, we get the expected result in WebKit browsers as well as in Firefox. It's only the source-in value that breaks things in WebKit browsers!

    See the Pen by thebabydino (@thebabydino) on CodePen.

    What gives?!

    Why is this particular value breaking things in WebKit?

    When I first came across this, I spent a few good minutes trying to find a typo in source-in, then copy pasted it from a reference, then from a second one in case the first reference got it wrong, then from a third... and then I finally had another idea!

    It appears as if, in the case of the non-standard WebKit alternative, we also have compositing applied between the layer at the bottom and a layer of nothing (considered completely transparent) below it.

    For the other three operations, this makes absolutely no difference. Indeed, adding, subtracting or excluding nothing doesn't change anything. If we are to take the formulas for these three operations and replace ?? with 0, we always get ??:

    • add/ source-over: ?? + 0 – ??·0 = ?? + 0 - 0 = ??
    • subtract/ source-out: ??·(1 – 0) = ??·1 = ??
    • exclude/ xor: ??·(1 – 0) + 0·(1 – ??) = ??·1 + 0 = ??

    However, intersection with nothing is a different story. Intersection with nothing is nothing! This is something that's also illustrated by replacing ?? with 0 in the formula for the intersect/ source-in operation:

    ??·0 = 0

    The alpha of the resulting layer is 0 in this case, so no wonder our image gets completely masked out!

    So the first fix that came to mind was to use another operation (doesn't really matter which of the other three, I picked xor because it has fewer letters and it can be fully selected by double clicking) for compositing the layer at the bottom with this layer of nothing below it:

    -webkit-mask: var(--l1), var(--l0); -webkit-mask-composite: source-in, xor; mask: var(--l1) intersect, var(--l0)

    And yes, this does work!

    You can resize the embed below to see how the mask behaves when it scales with the image and when it doesn't.

    See the Pen by thebabydino (@thebabydino) on CodePen.

    Note that we need to add the non-standard WebKit version before the standard one so that when WebKit browsers finally implement the standard version as well, this overrides the non-standard one.

    Well, that's about it! I hope you've enjoyed this article and learned something new from it.

    A couple more demos

    Before closing, here are two more demos showcasing why mask-composite is cool.

    The first demo shows a bunch of 1 element umbrellas. Each "bite" is created with a radial-gradient() that we exclude from the full circular shape. Chrome has a little rendering issue, but the result looks perfect in Firefox.

    1 element umbrellas using mask-composite (live demo).

    The second demo shows three 1 element loaders (though only the second two use mask-composite). Note that the animation only works in Chrome here as it needs Houdini.

    1 element loaders using mask-composite (live demo).

    How about you - what other use cases can you think of?

    The post Mask Compositing: The Crash Course appeared first on CSS-Tricks.

    Do CSS Custom Properties Beat Sass Loops?

    Css Tricks - Fri, 03/01/2019 - 1:59pm

    I reckon that a lot of our uses of Sass maps can be replaced with CSS Custom properties – but hear me out for a sec.

    When designing components we often need to use the same structure of a component but change its background or text color based on a theme. For example, in an alert, we might need a warning style, an error style, and a success style – each of which might be slightly different, like this:

    There’s a few ways we could tackle building this with CSS, and if you were asking me a couple of years ago, I would’ve tried to solve this problem with Sass maps. First, I would have started with the base alert styles but then I’d make a map that would hold all the data:

    $alertStyles: ( error: ( theme: #fff5f5, icon: 'error.svg', darkTheme: #f78b8b ), success: ( theme: #f0f9ef, icon: 'success.svg', darkTheme: #7ebb7a ), warning: ( theme: #fff9f0, icon: 'warning.svg', darkTheme: #ffc848 ) );

    Then we can loop through that data to change our core alert styles, like this:

    @each $state, $property in $alertStyles { $theme: map-get($property, theme); $darkTheme: map-get($property, darkTheme); $icon: map-get($property, icon); .alert-#{$state} { background-color: $theme; border-color: $darkTheme; &:before { background-color: $darkTheme; background-image: url($icon); } .alert-title { color: $darkTheme; } } }

    Pretty complicated, huh? This would output classes such as .alert-error, .alert-success and .alert-warning, each of which would have a bunch of CSS within them that overrides the default alert styles.

    This would leave us with something that looks like this demo:

    See the Pen
    Alerts – Sass Loops
    by Robin Rendle (@robinrendle)
    on CodePen.

    However! I’ve always found that using Sass maps and looping over all this data can become unwieldy and extraordinarily difficult to read. In recent projects, I’ve stumbled into fantastically complicated uses of maps and slowly closed the file as if I’d stumbled into a crime scene.

    How do we keep the code easy and legible? Well, I think that CSS Custom Properties makes these kinds of loops much easier to read and therefore easier to edit and refactor in the future.

    Let’s take the example above and refactor it so that it uses CSS Custom Properties instead. First we’ll set out core styles for the .alert component like so:

    See the Pen
    Alerts – Custom Variables 1
    by Robin Rendle (@robinrendle)
    on CodePen.

    As we create those base styles, we can setup variables in our .alert class like this:

    .alert { --theme: #ccc; --darkTheme: #777; --icon: ''; background: var(--theme); border: 1px solid var(--darkTheme); /* other styles go here */ &:before { background-image: var(--icon); } }

    We can do a lot more with CSS Custom Properties than changing an interface to a dark mode or theme. I didn’t know until I tried that it's possible to set an image in a custom property like that – I simply assumed it was for hex values.

    Anyway! From there, we can style each custom .alert class like .alert-warning by overriding these properties in .alert:

    .alert-success { --theme: #f0f9ef; --darkTheme: #7ebb7a; --icon: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/14179/success.svg); } .alert-error { --theme: #fff5f5; --darkTheme: #f78b8b; --icon: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/14179/error.svg); } .alert-warning { --theme: #fff9f0; --darkTheme: #ffc848; --icon: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/14179/warning.svg); }

    And that’s about it! We’ll get the exact same visual interface that we had with a Sass loop:

    See the Pen
    Alerts – Custom Variables 2
    by Robin Rendle (@robinrendle)
    on CodePen.

    However! I think there’s an enormous improvement here that’s been made in terms of legibility. It’s much easier to look at this code and to understand it right off the bat. With the Sass loop it almost seems like we are trying to do a lot of clever things in one place – namely, nest classes within other classes and create the class names themselves. Not to mention we then have to go back and forth between the original Sass map and our styles.

    With CSS Custom Properties, all the styles are contained within the original .alert.

    There you have it! I think there’s not much to mention here besides the fact that CSS Custom Properties can make code more legible and maintainable in the future. And I reckon that’s something we should all be a little excited about.

    Although there is one last thing: we should probably be aware of browser support whilst working with Custom Properties although it’s pretty good across the board.

    The post Do CSS Custom Properties Beat Sass Loops? appeared first on CSS-Tricks.

    Should I Use Source Maps in Production?

    Css Tricks - Fri, 03/01/2019 - 11:50am

    It's a valid question. A "source map" is a special file that connects a minified/uglified version of an asset (CSS or JavaScript) to the original authored version. Say you've got a filed called _header.scss that gets imported into global.scss which is compiled to global.css. That final CSS file is what gets loaded in the browser, so for example, when you inspect an element in DevTools, it might tell you that the <nav> is display: flex; because it says so on line 387 in global.css.

    On line 528 of page.css</, we can find out that <code>.meta has position: relative;

    But because that final CSS file is probably minified (all whitespace removed), DevTools is likely to tell us that we'll find the declaration we're looking for on line 1! Unfortunate, and not helpful for development.

    That's where source maps come in. Like I said up top, source maps are special files that connect that final output file the browser is actually using with the authored files that you actually work with and write code in on your file system.

    Typically, source maps are a configuration option from the preprocessor. Here's Babel's options. I believe that with Sass, you don't even have to pass a flag for it in the command or anything because it produces source maps by default.

    So, these source maps are for developers. They are particularly useful for you and your team because they help tremendously for debugging issues as well as day-to-day work. I'm sure I make use of them just about every day. I'd say in general, they are used for local development. You might even .gitignore them or skip them in a deployment process in order to serve and store fewer assets to production. But there's been some recent chatter about making sure they go to production as well.

    David Heinemeier Hansson:

    But source maps have long been seen merely as a local development tool. Not something you ship to production, although people have also been doing that, such that live debugging would be easier. That in itself is a great reason to ship source maps. [...]

    Additional, Rails 6 just committed to shipping source maps by default in production, also thanks to Webpack. You’ll be able to turn that feature off, but I hope you won’t. The web is a better place when we allow others to learn from our work.

    Check out that issue thread for more interesting conversation about shipping source maps to production. The benefits boil down to these two things:

    1. It might help you track down bugs in production more easily
    2. It helps other people learn from your website more easily

    Both are cool. Personally, I'd be opposed to shipping performance-optimized code for learning purposes alone. I wrote about that last year:

    I don't want my source to be human-readable, not for protective reasons, but because I care about web performance more. I want my website to arrive at light speed on a tiny spec of magical network packet dust and blossom into a complete website. Or do whatever computer science deems is the absolute fastest way to send website data between computers. I'm much more worried about the state of web performance than I am about web education. But even if I was very worried about web education, I don't think it's the network's job to deliver teachability.

    Shipping source maps to production is a nice middle ground. There's no hit on performance (source maps don't get loaded unless you have DevTools open, which is, IMO, irrelevant to a real performance discussion) with the benefit of delivering debugging and learning benefits.

    The downsides brought up in recent discussion boil down to:

    1. Sourcemaps require compilation time
    2. It allows people to, I dunno, steal your code or something

    I don't care about #2 (sorry), and #1 seems generally negligible for a small or what we think of as the average site, though I'm afraid I can't speak for mega sites.

    One thing I should add though is that source maps can even be generated for CSS-in-JS tooling, so for those that literally inject styles into the DOM for you, those source maps are injected as well. I've seen major slowdowns in those situations, so I would say definitely do not ship source maps to production if you can't split them out of your main bundles. Otherwise, I'd vote strongly that you do.

    The post Should I Use Source Maps in Production? appeared first on CSS-Tricks.

    Syndicate content
    ©2003 - Present Akamai Design & Development.