Gaming
Entertainment
Music
Sports
Business
Technology
News
Design
Fitness
Science
Histoy
Travel
Animals
DIY
Fun
Style
Photography
Lifestyle
Food
2018-04-25T20:23:33.517Z
0
{"feed":"CSS-Tricks","feedTitle":"CSS-Tricks","feedLink":"/feed/CSS-Tricks","catTitle":"Design","catLink":"/cat/design"}

React components can, and often do, have state. State can be anything, but think of things like whether a user is logged in or not and displaying the correct username based on which account is active. Or an array of blog posts. Or if a modal is open or not and which tab within it is active.

React components with state render UI based on that state. When the state of components changes, so does the component UI.

That makes understanding when and how to change the state of your component important. At the end of this tutorial, you should know how setState works, and be able to avoid common pitfalls that many of us hit when when learning React.

Workings of `setState()`

setState() is the only legitimate way to update state after the initial state setup. Let’s say we have a search component and want to display the search term a user submits.

Here’s the setup:

import React, { Component } from 'react'

class Search extends Component {
  constructor(props) {
    super(props)

    state = {
      searchTerm: ''
    }
  }
}

We’re passing an empty string as a value and, to update the state of searchTerm, we have to call setState().

setState({ searchTerm: event.target.value })

Here, we’re passing an object to setState(). The object contains the part of the state we want to update which, in this case, is the value of searchTerm. React takes...

Una Kravets shows how to make layouts in CSS Grid with flexbox fallbacks for browsers that don’t support those grid properties just yet. Una writes:

CSS grid is AMAZING! However, if you need to support users of IE11 and below, or Edge 15 and below, grid won't really work as you expect...This site is a solution for you so you can start to progressively enhance without fear!

The site is a provides examples using common layouts and component patterns, including code snippets. For example:

See the Pen Grid To Flex -- Example 1 by Una Kravets (@una) on CodePen.

Direct Link to ArticlePermalink

The post Grid to Flex appeared first on CSS-Tricks.

JAMstack sites are often seen as being static. A more accurate mental model for them would be that they are sites which have the ability to be hosted statically. The difference might seem semantic, but thanks to the rise of many tools and services which simplify running a build and deploying to static hosting infrastructure, such sites can feel much fresher and dynamic than you might imagine, while still capable of being served from static hosting infrastructure, with all the benefits that brings.

A feature often used as an example of why a site cannot be hosted statically is comments. A comments engine needs to handle submissions, allow for moderation, and is by its very nature, "dynamic".

Thanks to the growing ecosystem of tools available for JAMstack sites, there are solutions to this. Let's looks at an example which you could use on your own site, which:

  • Does not depend on...

This is an extract from chapter 11 of Ashley Davis’s book Data Wrangling with JavaScript now available on the Manning Early Access Program. I absolutely love this idea as there is so much data visualization stuff on the web that relies on fully functioning client side JavaScript and potentially more API calls. It’s not nearly as robust, accessible, or syndicatable as it could be. If you bring that data visualization back to the server, you can bring progressive enhancement to the party. All example code and data can be found on GitHub.

When doing exploratory coding or data analysis in Node.js it is very useful to be able to render a visualization from our data. If we were working in browser-based JavaScript we could choose any one of the many charting, graphics, and visualization libraries. Unfortunately, under Node.js, we don’t have any viable options, so how otherwise can we achieve this?

We could try something like faking the DOM under Node.js, but I found a better way. We can make our browser-based visualization libraries work for us under Node.js using a headless browser. This is a browser that has no user interface. You can think of it as a browser that is invisible.

I use Nightmare under Node.js to capture visualizations to PNG and PDF files and it works really well!

The headless browser

When we think of a web-browser we usually think of the graphical software that we interact with on a day to day basis...

Some of the most inspiring examples I’ve seen of front end development have involved some sort of page transitions that look slick, like they do in mobile apps. However, even though the imagination for these types of interactions seem to abound, their presence on actual sites that I visit do not. There are a number of ways to accomplish these types of movement!

Here’s what we’ll be building:

Demo Site GitHub Repo

We’ll build out the simplest possible distallation of these concepts so that you can apply them to any application, and then I’ll also provide the code for this more complex app if you’d like to dive in.

Today we’ll be discussing how to create them with Vue and Nuxt. There are a lot of moving parts in page transitions and animations (lol I kill me), but don’t worry! Anything we don’t have time to cover in the article, we’ll link off to with other resources.

Why?

The web has come under critique in recent years for appearing "dated" in comparison to native iOS and Android app experiences. Transitioning between two states can reduce cognitive load for your user, as when someone is scanning a page, they have to create a mental map of everything that's contained on it. When we move from page to page, the user has to remap that entire space. If an element is repeated on several pages, but altered slightly, it...

Implementing responsive email design can be a bit of a drag. Building responsive emails isn’t simple at all, it is like taking a time machine back to 2001 when we were all coding website layouts in tables using Dreamweaver and Fireworks.

But there's hope! We have tools available that can make building email much easier and more like coding a modern site. Let’s take a look at a couple of different frameworks that set out to simplify things for us.

First, the Situation

You have to be compatible with lots of old email clients, many of which don’t even support the most basic web standards (floats, anyone?). You also have to deal with all sorts of webmail clients which, for security or technical reasons, have made their own opinionated choices about how to display your precious email.

Furthermore, now emails are read from different devices, with very different viewports and requirements.

The best solution, as is often the case, would be to keep things simple and stick to basic one-column designs, using multiple columns only for menus or simple interface elements of known width. You can produce great, effective designs using only one column, after all.

However end-users and clients, who are used to the “normal” browser-based web, may hold their email-viewing experience to the same high standards they do for viewing web pages in terms of graphics and responsiveness. Therefore, complex designs are expected: multiple columns, different behaviors on mobile devices as opposed to desktops, lots of images, etc., all of which have...

If you have been in the React ecosystem for a while, there is a possibility that you have heard about Higher Order Components. Let’s look at a simple implementation while also trying to explain the core idea. From here you should get a good idea of how they work and even put them to use.

Why Higher-Order Components?

As you build React applications, you will run into situations where you want to share the same functionality across multiple components.

For example: you need to manage the state of currently logged in users in your application. Instead of managing that state across all of the components that need that state, you could create a higher-order component to separate the logged in user state into a container component, then pass that state to the components that will make use of it.

The components that receive state from the higher-order component will function as presentational components. State gets passed to them and they conditionally render...

This is an interesting read on the current state of scrollbars and how to control their behavior across operating systems and browsers. The post also highlights a bunch of stuff I didn’t know about, like Element.scrollIntoView() and the scroll-behavior CSS property.

My favorite part of all though? It has to be this bit:

In the modern web, relying heavily on custom JavaScript to achieve identical behavior for all clients is no longer justified: the whole idea of “cross-browser compatibility” is becoming a thing of the past with more CSS properties and DOM API methods making their way into standard browser implementations.

In our opinion, Progressive Enhancement is the best approach to follow when implementing non-trivial scrolling in your web projects.

Make sure you can provide the best possible minimal, but universally supported UX, and then improve with modern browser features in mind.

Speaking of the cross-browser behavior of scrollbars, Louis Hoebregts also has a new post that notes how Edge does not include the scrollbar when dealing with vw units the way other browsers do and he provides a nice way of handling it with CSS custom properties.

Direct Link to ArticlePermalink

The post Scroll to the Future appeared first on CSS-Tricks.

(This is a sponsored post.)

Huge thanks to Kinsta for sponsoring CSS-Tricks this week! We're big fans of WordPress around here, and know some of you out there are too. So this might come of interest: Kinsta is WordPress hosting that runs on Google Cloud Platform. And in fact, it's officially recommended by Google Cloud for fully-managed WordPress hosting.

What does that matter? Well, when you go with a cloud host you're entering a new realm of reliability. For example, your site is run in its own isolated container, including all the software required to run it. Familiar stuff like PHP, MySQL, and Nginx. Those resources are 100% private and not shared between anyone else - not even other sites of yours.

Spinning up a site is incredibly easy from their nice dashboard

You aren't on your own here. Yes, you're using powerful low-level infrastructure from Google Cloud Platform, but you get site management comfort from the Kinsta dashboard:

VuePress is a new tool from Vue creator Even You that spins up Vue projects that are more on the side of websites based on content and markup than progressive web applications and does it with a few strokes of the command line.

We talk a lot about Vue around here, from a five-part series on getting started with it to a detailed implementation of a serverless checkout cart

But, like anything new, even the basics of getting started can feel overwhelming and complex. A tool like VuePress can really lower the barrier to entry for many who (like me) are still wrapping our heads around the basics and tinkering with the concepts.

There are alternatives, of course! For example, Nuxt is already primed for this sort of thing and also makes it easy to spin up a Vue project. Sarah wrote up a nice intro to Nuxt and it's worth checking out, particularly if your project is a progressive web application.

The post VuePress Static Site Generator appeared first on CSS-Tricks.

Earlier this month on the Animation at Work Slack, we had a discussion about finding a way to let users pan inside an SVG.

I made this demo below to show how I'd approach this question:

See the Pen Demo - SVG Panning by Louis Hoebregts (@Mamboleoo) on CodePen.

Here are the four steps to make the above demo work:

  1. Get mouse and touch events from the user
  2. Calculate the mouse offsets from its origin
  3. Save the new viewBox coordinates
  4. Handle dynamic viewport

Let's check those steps one by one more thoroughly.

1. Mouse & Touch Events

To get the mouse or touch position, we first need to add event listeners on our SVG. We can use the Pointer Events to handle all kind of pointers (mouse/touch/stylus/...) but those events are not yet supported by all browsers. We will need to add some fallback to make sure all users will be able to drag the SVG.

// We select the SVG into the page
var svg = document.querySelector('svg');

// If browser supports pointer events
if (window.PointerEvent) {
  svg.addEventListener('pointerdown', onPointerDown); // Pointer is pressed
  svg.addEventListener('pointerup', onPointerUp); // Releasing the pointer
  svg.addEventListener('pointerleave', onPointerUp); // Pointer gets out of the SVG area
  svg.addEventListener('pointermove', onPointerMove); // Pointer is moving
} else {
  // Add all mouse events listeners fallback
  svg.addEventListener('mousedown', onPointerDown); // Pressing the mouse
  svg.addEventListener('mouseup', onPointerUp); // Releasing the mouse
  svg.addEventListener('mouseleave', onPointerUp); // Mouse...

Y'all know about font-display? It's pretty great. It's a CSS property that you can use within @font-face blocks to control how, visually, that font loads. Font loading is really pretty damn complicated. Here's a guide from Zach Leatherman to prove it, which includes over 10 font loading strategies, including strategies that involve critical inline CSS of subsets of fonts combined with loading the rest of the fonts later through JavaScript. It ain't no walk in the park.

Using font-display is kinda like a walk in the park though. It's just a single line of CSS. It doesn't solve everything that Zach's more exotic demos do, but it can go a long way with that one line. It's notable to bring up right now, as support has improved a lot lately. It's now in Firefox 58+, Chrome 60+, Safari 11.1+, iOS 11.3+, and Chrome on Android 64+. Pretty good.

What do you get from it? The ability to control FOUT and FOIT as is right for your project, two things that both kinda suck in regards to font loading. We've got a couple posts on it around here:

Reminder:

FOUT = Flash of Unstyled Text
FOIT = Flash of Invisible Text

Neither is great. In a perfect world, our custom fonts just show up immediately. But since that's not a practical possibility,...

Let's say I told you we can get the results below with just one HTML element and five CSS properties for each. No SVG, no images (save for the background on the root that's there just to make clear that our one HTML element has some transparent parts), no JavaScript. What would you think that involves?

Well, this article is going to explain just how to do this and then also show how to make things fun by adding in some animation.

CSS-ing the Gradient Rays

The HTML is just one <div>.

<div class='rays'></div>

In the CSS, we need to set the dimensions of this element and we need to give it a background so that we can see it. We also make it circular using border-radius:

.rays {
  width: 80vmin; height: 80vmin;
  border-radius: 50%;
  background: linear-gradient(#b53, #f90);
}

And... we've already used up four out of five properties to get the result below:

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

So what's the fifth? mask with a...

The team at Kapwing has collected a lot of images from the Internet Archive’s Wayback Machine and presented a history of how the homepage of popular websites like Google and the New York Times have changed over time. It’s super interesting.

I particularly love how Amazon has evolved from a super high information dense webpage that sort of looks like a blog to basically a giant carousel that takes over the whole screen.

Direct Link to ArticlePermalink

The post Museum of Websites appeared first on CSS-Tricks.

There is no shortage of videos out there where you can watch people code with an educational vibe. A golden age, one might say. Here are a few that I've watched and really enjoyed lately:

The post Some Recent Live Coding Favorites appeared first on CSS-Tricks.

We just hit you with a slab of observations about CSS Grid in a new post by Manuel Matuzo. Grid has been blowing our minds since it was formally introduced and Jen Simmons is connecting it (among other new features) to what she sees as a larger phenomenon in the evolution of layouts in web design.

From Jeremy Keith's notes on Jen's talk, "Everything You Know About Web Design Just Changed " at An Event Apart Seattle 2018:

This may be the sixth such point in the history of the web. One of those points where everything changes and we swap out our techniques ... let’s talk about layout. What’s next? Intrinsic Web Design.

Why a new name? Why bother? Well, it was helpful to debate fluid vs. fixed, or table-based layouts: having words really helps. Over the past few years, Jen has needed a term for “responsive web design +”.

That "+" is the intrinsic nature of the web. Should you use flexible image sizes or fixed images sizes? Why not both and let the context decide? CSS Grid plays a role in this because it introduced new methods for layouts to respond to the intrinsic context of the element, such as the fr unit and the minmax() function. We don't necessarily need media queries to make a layout responsive. And, similarly, we can choose to use a fixed layout that goes into a fluid one.

Last year, I assembled A Collection of Interesting Facts about CSS Grid Layout after giving a workshop. This year, I worked on another workshop and I've learned some more exciting facts about the layout spec we all so love.

Of course, I'm not going to keep my knowledge to myself. I'm happy to share my findings once again with you, the CSS-Tricks community.

Understanding how the `grid` shortcut works

Sometimes, reading and understanding parts of the grid—or actually any other—spec can be very hard.

For example, it took me quite a while to understand how to use the grid shorthand properly. The specification states that the valid values are:

<‘grid-template’> | <‘grid-template-rows’> / [ auto-flow && dense? ] <‘grid-auto-columns’>? | [ auto-flow && dense? ] <‘grid-autwo-rows’>? / <‘grid-template-columns’>

You can make sense of it if you take your time or if you're experienced in reading specs. I tried several combinations and all of them failed. What eventually helped me was a note in the spec:

Note that you can only specify the explicit or the implicit grid properties in a single grid declaration.

Rachel Andrew has a series of posts that help explain how to read a specification, using CSS Grid as an example.

So, we can specify a multitude of things using the grid shorthand, but just not all of them at once. Here are some examples.

Using `grid` in favor of `grid-template`

The grid-template property is a shorthand for setting grid-template-columns, grid-template-rows, and grid-template-areas in a single declaration. We can...

Brian Barrett:

Tired of Twitter? Facebook fatigued? It's time to head back to RSS.

I'm an RSS reader lover, so I hate to admit it, but RSS ain't going mainstream. It was too nerdy 20 years ago and it's too nerdy now. RSS is still incredibly useful technology, but I can't see it taking off alone.

For RSS to take off, it needs some kind of abstraction. Like Flipboard, where you can get started reading stuff right away and feeding it RSS isn't something you need to handle manually. Apple News is kinda like that. I'm a little love/hate with Apple News though. I like reading stuff in it, but I've stopped publishing in it because it became too much work to get right and have it look good. It's like managing a second site, unlike RSS which just brainlessly works when your CMS supports it. A little-known feature of Apple News was that it used to be able to function as an RSS reader, but they removed that a couple of years ago. Boooooo.

Podcasts have the right abstraction. People listen through apps that combine discoverability (or at least searchability) with the place you actually subscribe and listen. Ironically, RSS-based.

Digg has been a bit like Flipboard or Apple News: a combination of a very nice RSS reader but also curated content. They've just nuked their reader seemingly out of nowhere though, so clearly something wasn't going well there. There have been so many nukings of RSS readers, it...

(This is a sponsored post.)

Huge thanks to Wufoo for sponsoring CSS-Tricks this week! Like it says in the sidebar on this very site, we’ve been using Wufoo for literally over a decade. It’s the easiest and most powerful way to build web forms on the web.

Here’s something brand new from the Wufoo team: now in addition to payment providers like PayPal and Stripe, you can choose Worldpay.

This will be a huge upgrade for international users, and really any users with international customers. It’s already incredibly easy to create forms that take payments with Wufoo, now you can do it in local currencies like the £ Pound, € Euro, Canadian $ Dollar, Norwegian Krone, Swedish Krona, and more. And not just take payments in them, but be paid yourself in that currency. Nice.

Direct Link to ArticlePermalink

The post Wufoo and Worldpay appeared first on

Eric Bidelman introduces the CSS Typed Object Model. It looks like it's going to make dealing with getting and setting style values through JavaScript easier and less error-prone. Less stringy, more number-y when appropriate.

Like if we wanted to know the padding of an element, classically we'd do:

var el = document.querySelector("#thing");
var style = window.getComputedStyle(el);
console.log(style.padding);

And we'd get "20px" as a string or whatever it is.

One of these new API's lets us pull it off like this:

console.log(
  el.computedStyleMap().get('padding').value,
  el.computedStyleMap().get('padding').unit
);

And we get 20 as a real number and "px" as a string.

There is also attributeStyleMap with getters and setters, as well as functions for each of the values (e.g. CSS.px() CSS.vw()).

Eric counts the benefits:

  1. Few bugs.
  2. Arithmetic operations & unit conversion.
  3. Value clamping & rounding.
  4. Better performance.
  5. Error handling.
  6. Naming matches CSS exactly.

Direct Link to ArticlePermalink

The post Working With the new CSS Typed Object Model appeared first on CSS-Tricks.