Tech News

Frontity is React for WordPress

Css Tricks - Thu, 07/09/2020 - 4:50am

Some developers just prefer working in React. I don’t blame them really, because I like React too. Maybe that’s what they learned first. I’ve been using it long enough there is just some comfort to it. But mostly it is the strong component model that I like. There is just something nice about a codebase where things are constructed from components with clear jobs and responsibilities.

It’s not terribly common to see WordPress sites built with React though. The standard way to use WordPress is through themes that are essentially styles and PHP files that handle the templating. Frontity is changing that though. Frontity is a React-powered framework that digests your WordPress site’s API and builds the entire front end in React with all the powerful tools you’ve come to expect from that type of environment.

OMG, Now That’s a Fast Setup

This is how I was able to get started. At the command line, I did:

npx frontity create my-app

Then I went into the folder it created and did:

npx frontity dev

That instantly spins up a site for you to start working with.

To make it feel more real for me, I did went into frontity.settings.js and changed the source API to point at CSS-Tricks:

{ name: "@frontity/wp-source", state: { source: { api: "https://css-tricks.com/wp-json", }, }, },

And now look at what I get:

That’s wild. For some projects, that’s straight up ready to deploy.

Check out their intro video which steps through this exact thing Getting to Work

My first instinct with things like this is to get my hands into the styling right away. The theme that installs by default is the Mars theme and they have a nice guide to help wrap your mind around how it works. The theme uses Emotion for styling, so the components have styles you can mess with right in them. I found the <HeadContainer> component in index.js and immediately did the background: red change!

const HeadContainer = styled.div` display: flex; align-items: center; flex-direction: column; background-color: red; `;

It hot-module-reloaded that sucker instantly:

Is this one of those client-side only technologies?

That’s what I thought to myself. I mean, one of the advantages of using WordPress as-is is that you get the server rendering for free. That means no SEO worries (we know client-side rendered sites can take a week or more to be crawled for every change). That means resiliency and speed.

Frontity does do server side rendering! It uses Isomorphic rendering, meaning you need a Node server to render the pages, but that means the browser will get fully formed HTML for pages!

It’s a perfect match for Vercel, basically.

Similarly to how easy a new site is to scaffold and run in development, all you have to do to prep it for production is:

npx frontity build

Then run the Node server:

npx frontity serve

Cool.

I also really like that there is community around all this. If you need help, you’ll get it.

This is a best-of-all-worlds scenario.

I’m always very happy building sites with WordPress, and doubly so now that we have the block editor to use. I really like having an editor experience that helps me write and craft the kind of pages I want to create.

But I also like working with component-based architectures that have fast, easy-to-use, hot refreshing local development environments. Once you work in this kind of dev environment, it’s hard to use anything else! Beautiful DX.

And I also also want to make damn sure the sites I deploy to production are fast, robust, resilient, accessible, and SEO friendly.

I’d get all that with a Frontity site.

Another thing I like here is that Automattic themselves is on board with all this. Not just in spirit, but they are literally big investors. I think they are very smart to see this as an important part of the WordPress ecosystem. Building with WordPress doesn’t mean not building with React, especially with Frontity doing so much of the heavy lifting.

The post Frontity is React for WordPress appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

A little bit of plain Javascript can do a lot

Css Tricks - Wed, 07/08/2020 - 11:29am

Julia Evans:

I decided to implement almost all of the UI by just adding & removing CSS classes, and using CSS transitions if I want to animate a transition.

An awful lot of the JavaScript on sites (that aren’t otherwise entirely constructed from JavaScript) is click the thing, toggle the class — which is why jQuery was so good and libraries like Alpine.js are finding happy developer audiences.

I once did a screencast called “Hey designers, if you only know one thing about JavaScript, this is what I would recommend which was basically: learn to toggle classes. From that:

Sometimes, to start a journey into learning something huge and complex, you need to learn something small and simple. JavaScript is huge and complex, but you can baby step into it by learning small and simple things. If you’re a web designer, I think there is one thing in particular that you can learn that is extremely empowering.

This is the thing I want you to learn: When you click on some element, change a class on some element.

Direct Link to ArticlePermalink

The post A little bit of plain Javascript can do a lot appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

How to Make a List Component with Emotion

Css Tricks - Wed, 07/08/2020 - 4:46am

I’ve been doing a bit of refactoring this week at Sentry and I noticed that we didn’t have a generic List component that we could use across projects and features. So, I started one, but here’s the rub: we style things at Sentry using Emotion, which I have only passing experience with and is described in the docs as…

[…] a library designed for writing css styles with JavaScript. It provides powerful and predictable style composition in addition to a great developer experience with features such as source maps, labels, and testing utilities. Both string and object styles are supported.

If you’ve never heard of Emotion, the general idea is this: when we’re working on big codebases with lots of components, we want to ensure that we can control the cascade of our CSS. So, let’s say you have an .active class in one file and you want to make sure that doesn’t impact the styles of a completely separate component in another file that also has a class of.active.

Emotion tackles this problem by adding custom strings to your classnames so they don’t conflict with other components. Here’s an example of the HTML it might output:

<div class="css-1tfy8g7-List e13k4qzl9"></div>

Pretty neat, huh? There’s lots of other tools and workflows out there though that do something very similar, such as CSS Modules.

To get started making the component, we first need to install Emotion into our project. I’m not going to walkthrough that stuff because it’s going to be different depending on your environment and setup. But once that’s complete we can go ahead and create a new component like this:

import React from 'react'; import styled from '@emotion/styled'; export const List = styled('ul')` list-style: none; padding: 0; `;

This looks pretty weird to me because, not only are we writing styles for the <ul> element, but we’re defining that the component should render a <ul>, too. Combining both the markup and the styles in one place feels odd but I do like how simple it is. It just sort of messes with my mental model and the separation of concerns between HTML, CSS, and JavaScript.

In another component, we can import this <List> and use it like this:

import List from 'components/list'; <List>This is a list item.</List>

The styles we added to our list component will then be turned into a classname, like .oefioaueg, and then added to the <ul> element we defined in the component.

But we’re not done yet! With the list design, I needed to be able to render a <ul> and an <ol> with the same component. I also needed a version that allows me to place an icon within each list item. Just like this:

The cool (and also kind of weird) thing about Emotion is that we can use the as attribute to select which HTML element we’d like to render when we import our component. We can use this attribute to create our <ol> variant without having to make a custom type property or something. And that happens to look just like this:

<List>This will render a ul.</List> <List as="ol">This will render an ol.</List>

That’s not just weird to me, right? It’s super neat, however, because it means that we don’t have to do any bizarro logic in the component itself just to change the markup.

It was at this point that I started to jot down what the perfect API for this component might look like though because then we can work our way back from there. This is what I imagined:

<List> <ListItem>Item 1</ListItem> <ListItem>Item 2</ListItem> <ListItem>Item 3</ListItem> </List> <List> <ListItem icon={<IconBusiness color="orange400" size="sm" />}>Item 1</ListItem> <ListItem icon={<IconBusiness color="orange400" size="sm" />}>Item 2</ListItem> <ListItem icon={<IconBusiness color="orange400" size="sm" />}>Item 3</ListItem> </List> <List as="ol"> <ListItem>Item 1</ListItem> <ListItem>Item 2</ListItem> <ListItem>Item 3</ListItem> </List>

So after making this sketch I knew we’d need two components, along with the ability to nest icon subcomponents within the <ListItem>. We can start like this:

import React from 'react'; import styled from '@emotion/styled'; export const List = styled('ul')` list-style: none; padding: 0; margin-bottom: 20px; ol& { counter-reset: numberedList; } `;

That peculiar ol& syntax is how we tell emotion that these styles only apply to an element when it’s rendered as an <ol>. It’s often a good idea to just add a background: red; to this element to make sure your component is rendering things correctly.

Next up is our subcomponent, the <ListItem>. It’s important to note that at Sentry we also use TypeScript, so before we define our <ListItem> component, we’ll need to set our props up first:

type ListItemProps = { icon?: React.ReactNode; children?: string | React.ReactNode; className?: string; };

Now we can add our <IconWrapper> component that will size an <Icon> component within the ListItem. If you remember from the example above, I wanted it to look something like this:

<List> <ListItem icon={<IconBusiness color="orange400" size="sm" />}>Item 1</ListItem> <ListItem icon={<IconBusiness color="orange400" size="sm" />}>Item 2</ListItem> <ListItem icon={<IconBusiness color="orange400" size="sm" />}>Item 3</ListItem> </List>

That IconBusiness component is a preexisting component and we want to wrap it in a span so that we can style it. Thankfully, we’ll need just a tiny bit of CSS to align the icon properly with the text and the <IconWrapper> can handle all of that for us:

type ListItemProps = { icon?: React.ReactNode; children?: string | React.ReactNode; className?: string; }; const IconWrapper = styled('span')` display: flex; margin-right: 15px; height: 16px; align-items: center; `;

Once we’ve done this we can finally add our <ListItem> component beneath these two, although it is considerably more complex. We’ll need to add the props, then we can render the <IconWrapper> above when the icon prop exists, and render the icon component that’s passed into it as well. I’ve also added all the styles below so you can see how I’m styling each of these variants:

export const ListItem = styled(({icon, className, children}: ListItemProps) => ( <li className={className}> {icon && ( <IconWrapper> {icon} </IconWrapper> )} {children} </li> ))<ListItemProps>` display: flex; align-items: center; position: relative; padding-left: 34px; margin-bottom: 20px; /* Tiny circle and icon positioning */ &:before, & > ${IconWrapper} { position: absolute; left: 0; } ul & { color: #aaa; /* This pseudo is the tiny circle for ul items */ &:before { content: ''; width: 6px; height: 6px; border-radius: 50%; margin-right: 15px; border: 1px solid #aaa; background-color: transparent; left: 5px; top: 10px; } /* Icon styles */ ${p => p.icon && ` span { top: 4px; } /* Removes tiny circle pseudo if icon is present */ &:before { content: none; } `} } /* When the list is rendered as an <ol> */ ol & { &:before { counter-increment: numberedList; content: counter(numberedList); top: 3px; display: flex; align-items: center; justify-content: center; text-align: center; width: 18px; height: 18px; font-size: 10px; font-weight: 600; border: 1px solid #aaa; border-radius: 50%; background-color: transparent; margin-right: 20px; } } `;

And there you have it! A relatively simple <List> component built with Emotion. Although, after going through this exercise I’m still not sure that I like the syntax. I reckon it sort of makes the simple stuff really simple but the medium-sized components much more complicated than they should be. Plus, it could be pretty darn confusing to a newcomer and that worries me a bit.

But everything is a learning experience, I guess. Either way, I’m glad I had the opportunity to work on this tiny component because it taught me a few good things about TypeScript, React, and trying to make our styles somewhat readable.

The post How to Make a List Component with Emotion appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

How to delete all node_modules directories from your computer

Css Tricks - Wed, 07/08/2020 - 4:46am

Nice tip from Chris Ferdinandi:

My node_modules directories contained 50mb of stuff on the small side, and over 200mb of files in some cases. Over a few dozen projects, that really adds up!

Two dozen projects with 200 MB worth of node_modules? That’s nearly 5 GB of space for a bunch of stuff you’ve probably forgotten is even there, isn’t doing anything, and if you need again is a single command away. I feel like there should almost be a reaper app for these folders, deleting them if they haven’t been touched in a few weeks.

Nuke ’em:

# Mac/Linux find . -name "node_modules" -type d -prune -print | xargs du -chs # Windows FOR /d /r . %d in (node_modules) DO @IF EXIST "%d" echo %d"

Direct Link to ArticlePermalink

The post How to delete all node_modules directories from your computer appeared first on CSS-Tricks.

Displaying the Current Step with CSS Counters

Css Tricks - Tue, 07/07/2020 - 12:33pm

Say you have five buttons. Each button is a step. If you click on the fourth button, you’re on step 4 of 5, and you want to display that.

This kind of counting and displaying could be hard-coded, but that’s no fun. JavaScript could do this job as well. But CSS? Hmmmm. Can it? CSS has counters, so we can certainly count the number of buttons. But how do we calculate only up to a certain button? Turns out it can be done.

Thanks to Jan Enning for emailing in about this trick, it’s very clever!

HTML

It doesn’t have to be buttons; it just needs to be some sibling elements we can count. But we’ll go ahead and use buttons here:

<div class="steps"> <button class="active">Shop</button> <button>Cart</button> <button>Shipping</button> <button>Checkout</button> <button>Thank You</button> <div class="message"></div> </div>

The empty .message div there will be where we output our step messaging with CSS content.

CSS

The trick is that we’re actually going to use three counters:

  1. A total count of all the buttons
  2. A count of the current step
  3. A count of how many remaining steps are after the current step
.steps { counter-reset: currentStep 0 remainder 0 totalStep 0; }

Now let’s actually do the counting. To count all buttons is straightforward:

button { counter-increment: totalStep; }

Next, we need another thing to count that will also count the buttons. We can use a pseudo-element that’s only purpose is to count buttons:

button::before { content: ""; counter-increment: currentStep; }

The trick is to stop counting that pseudo-element on all the elements after the active element. If we’re using an .active class that looks like this:

button.active ~ button::before { /* prevents currentStep from being incremented! */ counter-increment: remainder; }

We’re counting the remainder there, which might also be useful, but because we’re only incrementing the remainder, that means we’re not counting the currentStep counter. Fancy, fancy.

Then we can use the counters to output our messaging:

message::before { content: "Step: " counter(currentStep) " / " counter(totalStep); }

Here it is!

CodePen Embed Fallback

There is a little JavaScript there so you can play with moving the active state on the button, but the counting and messaging is all CSS.

The post Displaying the Current Step with CSS Counters appeared first on CSS-Tricks.

WooCommerce on CSS-Tricks

Css Tricks - Tue, 07/07/2020 - 4:44am

I always get all excited when I accomplish something, but I get extra excited when I get it done and think, “well, that was easy.” As much as I enjoy fiddling with technology, I enjoy reaping the benefit of well set-up technology even more. That’s why I still get so excited about WordPress — I feel so powerful being able to accomplish big things without a huge amount of time and effort.

I had that exact feeling this past month when I was getting WooCommerce set up here on CSS-Tricks (again).

Lemme show you how I’ve got it set up, because I bet there are plenty of you who could do the same thing and make even more use of this setup than what I’m doing!

WooCommerce Powered Membership

Let’s say you want to have a membership site. Perhaps you have a fitness website and you make training videos and you build a membership paywall for pages that display those videos and training regiments. Or perhaps you have a cooking website, and paid members have access to additional features, like saved shopping lists.

Having a system for paid members is a foundational concept for making money online, and is typically no small task. Fortunately, WooCommerce makes quick work of it. Aside from the (free) WooCommerce plugin, you’ll need the ($199) WooCommerce Memberships plugin.

If you’re eying up some paid plugins for WooCommerce, you might circle July 21st on your calendar. That’s WooCommerce Day and there are going to be some big sales.

Once you have that installed, you’ll see a Memberships tab within your WooCommerce area in the WordPress admin. In there is a Membership Plans area where you can set up your plans. We have a very simple one-plan setup: CSS-Tricks Member.

You could have a whole variety of plans if you like (e.g. bronze, silver, gold).

These plans don’t do anything all by themselves just yet —they are just user roles, and the access control stuff comes later. You could make these plans such that only admins can add people to them, that anybody can register for them for free, or that they require the purchase of a product to join. That last one is the useful one for an eCommerce setup!

As a side note, you’ll probably want to limit the time length of the membership. You could make it unlimited, but it’s probably smarter to start with memberships that expire after a set time so you aren’t promising things for life.

Since I’m selling memberships, I’ve tied the Membership Plan to the sale of a product: MVP Supporter.

Buy this product, activate subscription, activate membership

The way to get access to that membership plan is to purchase this product. You’ll also always be able to manually add people to plans as an admin.

This product could have been a one-off charge, which supports the idea of an unlimited length membership, but like most memberships in the world, I wanted to set it up as a recurring billing product. That means we need a little additional setup.

Subscriptions to Memberships

I found this a tiny bit confusing. You might assume a membership plugin would support the idea of recurring billing for that membership, but it doesn’t do that out of the box. We need a second plugin for that: WooCommerce Subscriptions.

The subscription plugin is another $199, making this setup just shy of $400. That’s it for upfront costs though — you only need to renew the licenses next year if you need support and updates (I would). I find that cost to be more than fair for a system that works this efficiently, but you’ll have to do the business math for yourself.

Once you have that plugin installed, any product you create has the possibility of being a subscription product.

Here at CSS-Tricks, we’re charging $20/year for the membership. When someone signs up, they’ll be re-charged the next year at $20. That matches the length of the membership plan, which is an important step. Nothing forces you to do that but it would be weird to place a charge on a different date from the actual renewal.

Membership-Only Access to Posts

Wwe’ve done the two biggest parts of setup:

  1. Created a Membership Plan
  2. Created a product people can buy that subscribes them to that plan

Now for the part that actually gives the members some benefit! I am planning to sell access to a “book” that’s hosted on this site. The book is actually just a collection of posts. They are Custom Post Types we’ve set up called “Chapters.” In the editor for the chapter, below the content, there will be a Memberships area you can use for locking the chapter to a Membership Plan.:

This is in the post editor, underneath the post content.

Again, this example uses a Custom Post Type, but it could be any page or post type at all! It’s literally the flip of a switch to put something behind the membership wall.

There are two “faces” of a post with a content restriction:

  1. What members see: the content
  2. What non-members see: an excerpt and message on how to unlock the content

I think that’s a nice system. It shows people exactly what they could be reading if they were a member and shows them exactly how they can become a member.

Now there is some custom CSS happening here, but not much! I just use the default features, see what gets output onto the page, and there is always a sensible class name to hook onto to do styling — just how it should work.

Doing Things Programmatically for Members

In our case, the primary benefit to being a member is probably gaining access to the book, but it doesn’t have to stop there. I think giving as much as possible to a paying member is generally a good idea. And since advertising is the primary business model on this site, it seems fair to remove those ads if you have a paid supporter membership.

There are all kinds of APIs for these plugins to hook into whatever you need, but I like to keep things as simple as I can. For example, in any template, I can check to see if you’re a member or not.

<?php if ( !wc_memberships_is_user_active_member() ) { ?> <div> <!-- Show an ad if you're not a member. --> </div> <?php } ?>

I also do this before I run any other of the site’s JavaScript, so I can know in the JavaScript if a user is a member or not.

<?php if ( wc_memberships_is_user_active_member() ) { ?> <script> window.activeMember = true; </script> <?php } ?>

Some of the ads on this site are JavaScript-powered, so I can wrap the call for them in a !window.activeMember logic to not request them at all.

On-Demand Printing & Fulfillment

Memberships and subscriptions are just two of the things I’m doing with WooCommerce. The other is selling physical products, which is something I’ve dabbled in over the years. In fact, we used to hand-fulfill each and every order by taking products to the post office! We’ve also partnered with fulfillment companies in the past, but we still had to physically print up a bunch of inventory ahead of time.

Things have come a long way since then and there are lots of companies that print on demand! One such company (and I have no affiliation with them) is Printify. They sell all kinds of stuff, including what you’d expect from a printing company: t-shirts, hoodies, mugs… and the best part for me is that it connects directly to WooCommerce.

So far, we’ve stocked the store with posters! On the Printify side, I pick the product, upload the art, choose some options, and that’s that!

The last step in the process is to “Publish product to your WooCommerce store” which has worked perfectly for me so far. I trust that it works, as it must be forming the connection between Printify and WooCommerce such that Printify receives the order and fulfills it when they come in.

From there, the products appear on my site and I can edit or customize them from WordPress if I need to (like the copy and such):

Products in my WooCommerce admin

I can check orders at any time and watch as they are ordered, produced, prepped, and shipped:

Order dashboard on Printify

I ordered some posters myself, of course, so I could try it out before putting it in front of other people. The poster came in a nice triangular tube thing in perfect condition on thick bright white paper. I hung it right up next to my office computer:

Mobile App

If you’re like me and get excited to look at how your little store is doing and get notifications for sales, there is a mobile app.

I haven’t had the need to update order statuses or manage reviews and the like, but that’s all in there too.

There is a lot of technology at work here!

But my actual time commitment has been minimal. I’ve spent longer writing this blog post than I have setting up all of this eCommerce stuff. I’m just an integrator here. I’m not inventing anything — just taking advantage of some best-in-class software to make my ideas happen.

The post WooCommerce on CSS-Tricks appeared first on CSS-Tricks.

Improving Chromium’s browser compatibility in 2020

Css Tricks - Tue, 07/07/2020 - 4:44am

This is exactly what I love to hear from any browser vendor:

When it comes to browser compatibility, there are still too many missing features and edge-case bugs. But it doesn’t have to be this way. Things can and will get better, if browser vendors can understand what is causing the most pain, and take action to address the causes. In Chrome we’re doing our best to listen, and we’re doing our best to address what we’re hearing. We hope it helps, and we’re looking forward to a more compatible 2021.

I love the nod to that super clever div that looks different in every browser. This is a solid list from Stephen McGruer. My favorite:

Like Flexbox, CSS Grid is an important component of modern layout. Looking at the early survey results it seems like the story for CSS Grid support in Chromium is fairly good (we have our friends from Igalia to thank for that!). There is one clear exception – Chromium still doesn’t support subgrid.

Hopefully, it won’t be an exception for much longer. It’s still early days, but I’m excited to share that a team at Microsoft Edge are working on rearchitecting Chromium’s Grid support to use the new LayoutNG engine – and as part of this are intending to add subgrid support!

Not that anyone should relax, but I think right now is probably the best level of browser compatibility we’ve ever seen.

Direct Link to ArticlePermalink

The post Improving Chromium’s browser compatibility in 2020 appeared first on CSS-Tricks.

Bootstrap 5

Css Tricks - Mon, 07/06/2020 - 12:49pm

It’s always notable when the world biggest CSS framework goes up a major version (it’s in alpha now).

It has dropped jQuery and IE, started using some CSS custom properties, gone fully customized with form elements, started to embrace utility classes, and includes a massive icon set you can use via SVG sprite. Sweet.

Direct Link to ArticlePermalink

The post Bootstrap 5 appeared first on CSS-Tricks.

WordPress Contributors Seek Sponsorship for Improving Gutenberg Developer Docs

Css Tricks - Mon, 07/06/2020 - 4:52am

A couple of WordPress contributors are currently looking for folks to sponsor them to work on the documentation for the WordPress block editor (often referred to as “Gutenberg”) and this is your chance to support them.

If you’ve developed blocks for the WordPress block editor — or at least have tried to — then you have likely struggled to find any meaningful documentation. Heck, just look at two recent posts here at CSS-Tricks where Dmitry Mayorov explains block variations and Leonardo Losoviz adds a welcome guide to the block editor. They both lament the lack of documentation and describe how they had to work around it. Chris has even experimented with different build approaches, from create-gluten-block to wp-cli to ACF Blocks. It’s sortuva Wild West out there and documented standards with examples would be a huge win, both for WordPress and for developers.

Now, I don’t think it’s worth getting into a debate into why the documentation doesn’t already exist a year since the block editor was released. There are lots of reasons for that and none of them help move things forward.

We flipped the switch to enable the WordPress block editor here at CSS-Tricks earlier this year and haven’t looked back. Where several of us on the team would write drafts in Dropbox Paper, Google Docs, or even a code editor, I think we’ve all started writing directly in WordPress because, well, it’s just so gosh-darned nice. I know I’m looking forward to contributing whatever I can to help this make this tool more accessible to developers — that’s the best way to spark new ideas and innovations for the future of blocks.

Direct Link to ArticlePermalink

The post WordPress Contributors Seek Sponsorship for Improving Gutenberg Developer Docs appeared first on CSS-Tricks.

Posters! (for CSS Flexbox and CSS Grid)

Css Tricks - Mon, 07/06/2020 - 4:29am

Any time I chat with a fellow web person and CSS-Tricks comes up in conversation, there is a good chance they’ll say: oh yeah, that guide on CSS flexbox, I use that all the time!

Indeed that page, and it’s cousin the CSS grid guide, are among our top trafficked pages. I try to take extra care with them making sure the information on them is current, useful, and the page loads speedily and properly. A while back, in a round of updates I was doing on the guides, I reached out to Lynn Fisher, who always does incredible work on everything, to see if she’d be up for re-doing the illustrations on the guides. Miraculously, she agreed, and we have the much more charismatic illustrations that live on the guides today.

In a second miracle, I asked Lynn again if she’d be up for making physical paper poster designs of the guides, and see agreed again! And so they live!

Here they are:

You better believe I have it right next to me in my office:

They are $25 each which includes shipping anywhere in the world.

Buy the Flexbox Poster Buy the Grid Poster

The post Posters! (for CSS Flexbox and CSS Grid) appeared first on CSS-Tricks.

USA.css

Css Tricks - Sun, 07/05/2020 - 12:29pm

Lots of fun with gradients from Bennett Feely: stars, stripes, banners, bursts… I love being able to use nice patterns with either no image requests at all, or very little SVG.

Reminder: Bennett does all sorts of cool stuff. I’ve probably used Clippy about a million times.

Direct Link to ArticlePermalink

The post USA.css appeared first on CSS-Tricks.

The Thirteenth Fourth

Css Tricks - Sat, 07/04/2020 - 1:06pm

Well boy howdy. The 13th birthday of CSS-Tricks has rolled around. A proper teenager now, howabouthat? I always take the opportunity to do a bit of a state of the union address at this time, so let’s get to it!

Design

Technically, we’re still on v17 of the site design. This was the first design that I hired first-class help to do, and I’m still loving it, so I haven’t had much of an itch to do massive changes to it. Although it is quite different¹ today than it was on launch day.

For example…

Maybe next year we’ll do something different again. My list is starting to grow for some behind-the-scenes tech stuff I wanna re-jigger, and sometimes that goes hand in hand with redesign work.

Closed Forums

The forums on this site have been a mental weight on me for literally years. Earlier this year I finally turned them off. They are still there, and probably always will be (so the URLs are maintained), but nobody can post new threads or replies.

It was a painful move. Even as I did it, there was still some regular daily activity there and I’m sure it didn’t feel good to those people to have a place they have invested time in shut down. Here’s why I did it:

  • Nobody here, including me, checked in on the forums with any regularity. Unmoderated public forums on the internet are not acceptable to me.
  • The spam volume was going up. There were periods where most posts, even after the automatic spam blocking I get from Akismet, where spam that required manual removal. Even if we had a dedicated forums employee, that’s no fun, and since we didn’t, it was just a random job for me and I don’t need a time sink like that.
  • The forums represent a certain level of technical debt. They need to be updated. Their design needs to be functional in the context of this site. At one point I ripped out all custom styles and left it be the default theme, which was a good step toward reducing technical debt, but in the end it wasn’t enough.

I can handle some work and some technical debt, of course. But when you combine those things with the fact that the forums don’t contribute much to what I consider to be the success of the site. They don’t exactly drive page views or advertising demand. There isn’t really money to hire help specifically for the forums. But that’s a small part of it. I want this site to help people. I think we can do that best if we focus on publishing with as little divided attention as possible. I think there are places on the internet that are better for forum-like discourse.

Now that they’ve been off a number of months, I can report that the lifting of the mental weight feels very good to me and there has been little if any major negatives.

Social

Here’s another mental weight I lifted: I stopped hand-managing the Twitter account (@css). I still think it’s good that we have a Twitter account (and that we have that cool handle), but I just don’t spend any time on it directly like I used to.

In the past, I’d queue up special articles with commentary and graphics and stuff and make sure the days were full with a spread of what I thought would be interesting tweets about web design and development. That’s fine and all, but it began to feel like a job without a paycheck.

We don’t get (or seem to drive) a lot of traffic from Twitter. Google Analytics shows social media accounts for less than 1% of our traffic. Investing time in “growing” Twitter just doesn’t have enough of an upside for me. Not to mention the obvious: Twitter can be terribly toxic and mentally draining.

So now, all our posts to Twitter are automated through the Jetpack social media connection (we really use Jetpack for tons of stuff). We hit publish on the site and the article is auto-tweeted. So if you use Twitter like an RSS feed of sorts (just show me the news!), you got it.

The result? Our follower count goes up at the same rate it always did. Engagement there is the same, or higher, than it ever was. What a relief. Do ten times less work for the same benefit.

When I have the urge to share a link with commentary I use the same system we’ve always had here: I write it up as a link blog post instead. Now we’re getting even more benefit: long-term content building, which is good for the thing that we actually have on our side: SEO.

Someday we could improve things by hand-writing the auto-tweet text with a bit more joie de vivre, crediting the author more clearly, and, #stretchgoal, a custom or fancy-generated social media graphic.

Opened Up Design Possibilities

One aspect of this site that I’ve been happy with is the opportunity to do custom design on content. Here are some examples of that infrastructure.

On any given blog post, we can pick a template. Some of those templates are very specific. For example, my essay The Great Divide is a template all to itself.

In the code base, I have a PHP template and a CSS file that are entirely dedicated to that post. I think that’s a fine way to handle a post you want to give extra attention to, although the existence of those two files is a bit of technical debt.

I learned something in the creation of that particular essay: what I really need to open up the art direction/design possibility on a post is a simple, stripped-down template to start from. So that’s what we call a “Fancy Post” now, another template choice for any particular post. Fancy Posts have a hero image and a centered column for the content of the post. From there, we can use custom CSS to style things right within WordPress itself.

For example, my recent post on DX is styled as a Fancy Post with Custom CSS applied right within the block editor.

The Block Editor itself is a huge deal for us. That was one of my goals for the year, and we’ve really exceeded how far we’d get with it. I think writing and editing posts in the block editor is a million miles ahead of the old editor.

The hardest challenge was (and still is really) getting the block transforms set up for legacy content. But once you have the power to build and customize blocks, that alone opens up a ton of design possibility within posts that is too big of a pain in the butt and too heavy on technical debt otherwise.

Another door we opened for design possibilities is a classic one: using categories. A sort of freebie you get in WordPress is the ability to create templates for all sorts of things that just sort of automatically work if they are named correctly. So for example I have a file called category-2019-end-of-year-thoughts.php and that fully gives me control over making landing pages for groups of posts, like our end-of-year thoughts homepage. Not to mention our “Guide Collection” pages which are another way to programmatically build collections of pages.

That’s a lot of tools to do custom work with, and I’m really happy with that. It feels like we’ve given ourselves lots of potential with these tools, and only started taking advantage of it.

Speaking of which, another aspect of custom design we have available is the new book format…

eCommerce

We’re using WooCommerce here on the site now again. I just got done singing the praises of the Block Editor and how useful that has been… WooCommerce is in the same boat. I feel like I’m getting all this powerful functionality with very little effort, at a low cost, and with little technical debt. It makes me very happy to have this site on WordPress and using so much of suite of functionality that offers.

So for one thing, I can sell products with it, and we have products now! Lynn Fisher designed a poster for our CSS Flexbox guide and designed a poster for our CSS Grid guide, which you can now buy and ship anywhere in the world for $25 each. Look, with the Block Editor I can put a block for a poster right here in this post:

CSS Flexbox Poster

Find yourself constantly looking up the properties and values for CSS flexbox? Why not pin this beautiful poster up to the wall of your office so you can just glance over at it?

$25.00 Shop now

Another thing we’re using WooCommerce for is to sell our new book, The Greatest CSS Tricks Vol. I. If we actually made it into a proper eBook format, WooCommerce could absolutely deliver those files digitally to you, but we haven’t done that yet. We’ve take another path, which is publishing the book as chapters here on the site behind a membership paywall we’re calling MVP supporters. The book is just one of the benefits of that.

WooCommerce helps:

  • Build a membership system and sell memberships. Membership can lock certain pages to members-only as has programmatic hooks I can use for things like removing ads.
  • Sell subscriptions to those memberships, with recurring billing.
  • Sell one-off products

And I’m just scratching the surface of course. WooCommerce can do anything eCommerce wise.

Analytics

They are fine. Ha! That’s how much I worry about our general site analytics. I like to check in on them from time to time to make sure we’re not tanking or anything scary, but we never are (knock on wood). We’re in the vicinity of 8m page views a month, and year-over-year traffic is a bit of a dance.

Sponsors

THANK YOU THANK YOU THANK YOU

That’s what I have to say to all our sponsors. We’re so damn lucky to work with a lineup of sponsors that I wholeheartedly endorse as well as literally use their products. We have different sponsors all the time, but these are the biggest and those who have been with us the longest.

  • Automattic: Thanks for building great software for the WordPress ecosystem. This site is made possible by a heaping helping of that software.
  • Netlify: Thanks for bringing the Jamstack world to life. I’m also a big fan of this way of building websites, and think that Jamstack should be the foundation for most websites. Beyond that, you’ve redefined modern developer experience.
  • Flywheel: Thank you for hosting this website, being a high-quality host I can trust and who has been helpful to me countless times. This is what high-quality WordPress hosting looks like.
  • Frontend Masters: Thank you for being an education partner that does things right and helps me have the best possible answer for people when they are searching a more structured formal education about doing web work: go try Frontend Masters.

If you’re trying to reach front-end developers with your products, that’s literally how I make a living and can help.

My Other Projects

CodePen is no spring chicken either, being over 8 years old itself. I repeat myself a lot with this particular aspect of talking about CodePen: we’ve got a ton of ideas, a ton of work to do, and we can’t wait to show you the CodePen of tomorrow. 2020 for CodePen has been a lot different than the last 2-3 years of CodePen. Some technical choices we’ve made have been starting to pay off. The team is vibing very well and absolutely tearing through work faster than I would have thought possible a few years ago, and we haven’t even unlocked some of the biggest doors yet. I know that’s vague, but we talk in more detail about stuff on CodePen Radio.

ShopTalk, as ever, is going strong. That’s 420 episodes this week, friends. Dave has me convinced that our format as it is, is good. We aren’t an instruction manual. You don’t listen to any particular episode because we’re going to teach you some specific subject that we’ve explicitly listed out. It’s more like water cooler talk between real world developers who develop totally different things in totally different situations, but agree on more than we disagree. We might evolve what ShopTalk show is over time, but this format will live on because there is value in discussion in this format.

Life

My wife Miranda and I are still in Bend, Oregon and our Daughter Ruby is two and a half. She’s taking a nap and I’m looking at the monitor as I type.

We have the virus here like everywhere else. It’s sad to think that we’re this far into it and our local hospital is pleading with people to be careful this holiday weekend because they are very near capacity and can’t take much more. Here’s hoping we can get past this painful period. Stay safe and stay cool, friends, thanks for reading.

  1. I always feel bad when I make design changes away from an actual professional designer’s work. Is the site design better today than Kylie‘s original? Uhm probably not (sorry for wrecking it Kylie!), but sometimes I just have an itch to fiddle with things and give things a fresh look. But the biggest driver of change is the evolving needs of the site and my desire to manage things with as little technical debt as possible, and sometimes simplifying design things helps me get there.

The post The Thirteenth Fourth appeared first on CSS-Tricks.

Fluid Images in a Variable Proportion Layout

Css Tricks - Fri, 07/03/2020 - 4:36am

Creating fluid images when they stand alone in a layout is easy enough nowadays. However, with more sophisticated interfaces we often have to place images inside responsive elements, like this card:

For now, let’s say this image is not semantic content, but only decoration. That’s a good use for background-image. And because in this context the image contains an object, we can’t allow any parts to be cropped out when it’s responsive, so we’d pick background-size: contain.

Here’s where it starts to get tricky: on mobile devices, this card shifts direction and becomes vertical, with the image on top. We can make that happen with any sort of CSS layout technique, and probably best handled with CSS grid or flexbox.

But as we test for smaller screens, because of the contain property, this is what we get:

Hey, get back up there!

That’s not very nice. The image resizes to maintain its aspect ratio without cutting off any details, and if the image is important content and should not be cropped, we can’t change background-size to cover.

At this point, our next attempt might be familiar to you: placing the image inline, instead the background. 

On desktop, this works fine:

It’s not bad on mobile either:

But on smaller screens, because of all the fixed sizes, the image’s proportions get distorted.

Hmm, those strawberries are not as appetizing when stretched.

We could spend hours fiddling with the image, the card, the flex properties, going back and forth. Or, we could…

Separate main content from the background

This is the base for obtaining much more flexibility and resilience when it comes to responsive images. It might not be possible 100% of the time but, in many cases, it can be achieved with a little effort on the design side of things, especially if this approach is planned beforehand.

For our next iteration, we’re placing our strawberries image on a transparent background and setting what was the blue color in the raster image with CSS instead. Go ahead and play with viewport sizes in this demo by adjusting the size of the sample space!

CodePen Embed Fallback

Looking deeper at the styles, notice that we’ve also added padding to the div that holds the image, so the strawberries don’t come too close to the edges. We have full control of how close or distant we want them to be, through this padding.

Note how we’re also using negative margins to compensate for the padding on our outer card wrapper, otherwise we’d get white space all around the image.

Use the object-fit property for inline images

As much as the previous demo works, we can still improve the approach. Up to now, we’ve assumed that the image was un-semantical content — but with this layout, it’s also likely that the image illustration could be more than decoration.

If that’s the case, we definitely don’t want the image to get cut off because that would essentially amount to data loss. It’s semantically better to put the image inline instead of a background to prevent that, and we can use the object-fit property to make it happen.

CodePen Embed Fallback

We’ve extracted the strawberries from the background and it’s now an inline <img> element, but we kept the background color in that same image div. 

Finally, combining the object-fit: contain with a 100% width makes it possible to resize the window and keep the aspect ratio of the strawberries. The caveat of this approach, however, is that we need to set a fixed height for the image on the desktop version — otherwise it’s going to follow the proportion of the set width (and reducing it will alter the layout). That might make things too constrained if we need to generate these cards with a variable amount of text that breaks into several lines.

Coming soon: aspect-ratio

The solution for the concern above might be just around the corner with the upcoming aspect-ratio property. This will enable setting a fixed ratio for an element, like this:

.el {   aspect-ratio: 16 / 9; }

This means we’ll be able to eliminate fixed height and replace it with our calculated aspect ratio. For example, the dimensions in the desktop breakpoint of our last example looked like this:

.image { /* ... */   height: 184px;   width: 318px; }

With aspect-ratio, we could remove the height declaration and do the math to get the closest ratio that amounts to 184:

.image {   /* ... */   width: 318px; /*  Base width */   height: unset; /* Resets the height that was set outside the media query */   aspect-ratio: 159 / 92; /* Amounts close to a 184px height */ }

The upcoming property is better explored in this article, if you want to learn more about it.

In the end, there are multiple ways to achieve reliably responsive images in a variable proportion layout. However, the trick to make this job easier — and better — does not necessarily lie with CSS; it can be as simple as adapting your images, whether that’s by separating the foreground from background (like we did) or selecting specific images that will still work if a fair portion of the edges get cropped.

The post Fluid Images in a Variable Proportion Layout appeared first on CSS-Tricks.

Settling down in a Jamstack world

Css Tricks - Fri, 07/03/2020 - 4:35am

One of the things I like about Jamstack is that it’s just a philosophy. It’s not particularly prescriptive about how you go about it. To me, the only real requirement is that it’s based on static (CDN-backed) hosting. You can use whatever tooling you like. Those tools, though, tend to be somewhat new, and new sometimes comes with issues. Some pragmatism from Sean C Davis here:

I have two problems with solving problems using the newest, best tool every time a problem arises.

1. It’s simply not productive. Introducing new processes and tools takes time. Mastery and efficiency are built over time. If we’re trying to run a profitable business, we shouldn’t start from scratch every time.

2. We can’t know everything, all the time. With the rapidity at which we’re seeing new tools, there’s simply no way of knowing the best tool for the job because there’s no way to know all the tools available.

The trick is to settle into some tools you’ve proved that work and then keep using them to increase that level of expertise.

The post Settling down in a Jamstack world appeared first on CSS-Tricks.

6 Laws Of Psychology For Good UX Design

Usability Geek - Fri, 07/03/2020 - 12:17am
Every user interacting with your web design is a human — at least until the singularity arrives — which means each one of them is subject to certain psychological principles. Over decades of...
Categories: Web Standards

Some Performance Links

Css Tricks - Thu, 07/02/2020 - 2:53pm

Just had a couple of good performance links burning a hole in my pocket, so blogging them like a good little blogger.

Web Performance Recipes With Puppeteer

Puppeteer is an Node library for spinning up a copy of Chrome “headlessly” (i.e. no UI) and controlling it. People use it for stuff like taking a screenshot of a website or running integration tests. You can even run it in a Lambda.

Another use case is running synthetic (i.e. not based on real-users) performance tests, like some of these new Web Core Vitals

Addy Osmani lists out a bunch of these “recipes” for measuring certain performance things in Puppeteer. These would be super useful as part of a build process alongside other tests. Did the unit tests pass? Did the integration tests pass? Did the accessibility tests pass? Did the performance metrics tests pass?

BrowserStack SpeedLab

BrowserStack released a thing to measure your site and give you a performance score.

You get the tests back super quick which is cool. I can see how tools like this are good for starting conversations with teams about improving performance.

But… that number seems a little weird. They don’t exactly document how it’s calculated, but it seems to be based on stuff like Time to First Byte (TTFB) and the page load event, which aren’t particularly useful performance metrics.

It’s not bad that this tool exists or anything, but I don’t think it’s for practitioners doing performance work.

5 Common Mistakes Teams Make When Tracking Performance

Karolina Szczur from Calibre documents some common team struggles like, for example, having a team be able to identify real issues from variability noise.

Many people from different backgrounds can view performance dashboards. Not knowing what constitutes a meaningful change that needs investigation can result in false positives, lack of trust in monitoring and cycles spent looking for reasons for performance regressions or upgrades that aren’t there.

Are your JavaScript long tasks frustrating users?

50ms. That’s how long until any particular JavaScript task starts affecting user experience. Might as well track and (ideally) fix them.

When the browser’s main thread hits max CPU for more than 50ms, a user starts to notice that their clicks are delayed and that scrolling the page has become janky and unresponsive. Batteries drain faster. People rage click or go elsewhere.

The post Some Performance Links appeared first on CSS-Tricks.

Refreshing Sidebar for 2020

Css Tricks - Thu, 07/02/2020 - 2:53pm

The new design for Sidebar is lovely. I like how it goes even deeper with the sticky elements than the last design.

But even more notably, Sacha Greif has been posting five links per day to Sidebar since 2012. That’s a remarkable achievement.

Direct Link to ArticlePermalink

The post Refreshing Sidebar for 2020 appeared first on CSS-Tricks.

How-to guide for creating edge-to-edge color bars that work with a grid

Css Tricks - Wed, 07/01/2020 - 10:11am

Hard-stop gradients are one of my favorite CSS tricks. Here, Marcel Moreau combines that idea with CSS grid to solve an issue that’s otherwise a pain in the butt. Say you have like a 300px right sidebar on a desktop layout with a unique background color. Easy enough. But then say you want that background color to stretch to the right edge of the browser window even though the grid itself is width-constrained. Tricker.

CodePen Embed Fallback

Direct Link to ArticlePermalink

The post How-to guide for creating edge-to-edge color bars that work with a grid appeared first on CSS-Tricks.

New in Chrome: CSS Overview

Css Tricks - Tue, 06/30/2020 - 1:59pm

Here’s a fancy new experimental feature in Chrome! Now, we can get an overview of the CSS used on a site, from how many colors there are to the number of unused declarations… even down to the total number of defined media queries.

Again, this is an experimental feature. Not only does that mean it’s still in progress, but it means you’ll have to enable it to start using it in DevTools.

  • Open up DevTools (Command+Option+I on Mac; Control+Shift+I on Windows)
  • Head over to DevTool Settings (? or Function+F1 on Mac; ? or F1 on Windows)
  • Click open the Experiments section
  • Enable the CSS Overview option

And, oh hey, look at that! We get a new “CSS Overview” tab in the DevTools menu tray when the settings are closed. Make sure it’s not hidden in the overflow menu if you’re not seeing it.

Lovely color palette you got there, Mr. Coyier. &#x1f60d;

Notice that the report is broken out into a number of sections, including Colors, Font info, Unused declarations and Media queries. That’s a lot of information available in a small amount of space right at our fingertips.

This is pretty nifty though, huh? I love that tools like this are starting to move into the browser. Think about how this can help us not only as front-enders but also how we collaborate with designers. Like, a designer can crack this open and start checking our work to make sure everything from the color palette to the font stack are all in tact.

The post New in Chrome: CSS Overview appeared first on CSS-Tricks.

Global and Component Style Settings with CSS Variables

Css Tricks - Tue, 06/30/2020 - 1:58pm

The title of this Sara Soueidan article speaks to me. I’m a big fan of the idea that some CSS is best applied globally, and some CSS is best applied scoped to a component. I’m less interested in how that is done and more interested in just seeing that conceptual approach used in some fashion.

Sara details an approach where components don’t have too much styling by default, but have CSS custom properties applied to them that are ready to take values should you choose to set them.

For each pattern, I’ve found myself modifying the same properties whenever I needed to use it — like the font, colors (text, background, border), box shadow, spacing, etc. So I figured it would be useful and time-saving if I created variables for those properties, define those variables in the ‘root’ of the component, and ‘pass in’ the values for these variables when I use the pattern as I need. This way I can customize or theme the component by changing the property values in one rule set, instead of having to jump between multiple ones to do so.

Direct Link to ArticlePermalink

The post Global and Component Style Settings with CSS Variables appeared first on CSS-Tricks.

Syndicate content
©2003 - Present Akamai Design & Development.