Archiwum kategorii: CSS

The Vue Cookbook

Post pobrano z: The Vue Cookbook

I’m extremely excited to announce that the Vue Cookbook is officially in beta! For the past few months, the Vue team has been writing, and editing and accepting PRs from the community to build a new section of our docs called the Cookbook. Each recipe stands on its own, meaning that recipes can focus on one specific aspect of Vue or something that integrates with Vue, and do a small deep dive into that subject. We can then include more complex examples, combining features in interesting ways.

One of my favorite parts of the cookbook is the Alternative Patterns section of each recipe. Usually when people write blog posts or document something, they’re also selling you on the concept that they’re explaining. In the cookbook, we strive to consider that we’re all building different kinds of applications and websites, and thus a variety of choices will be valid, given divergent scenarios. The cookbook spends a little time in each recipe weighing the tradeoffs, and considering when one might need another path.

For advanced features, we assume some ecosystem knowledge. For example, if you want to use single-file components in Webpack, we don’t explain how to configure the non-Vue parts of the Webpack config. In the cookbook, we have the space to explore these ecosystem libraries in more depth—at least to the extent that is universally useful for Vue developers.

This section will continue to be in development! We have more recipes that we’re writing, we’re still accepting PRs, and the more community involvement, the richer a resource it becomes! I hope you enjoy it and find it useful.

Direct Link to ArticlePermalink

The post The Vue Cookbook appeared first on CSS-Tricks.

React State From the Ground Up

Post pobrano z: React State From the Ground Up

As you begin to learn React, you will be faced with understanding what state is. State is hugely important in React, and perhaps a big reason you’ve looked into using React in the first place. Let’s take a stab at understanding what state is and how it works.

What is State?

State, in React, is a plain JavaScript object that allows you keep track of a component’s data. The state of a component can change. A change to the state of a component depends on the functionality of the application. Changes can be based on user response, new messages from server-side, network response, or anything.

Component state is expected to be private to the component and controlled by the same component. To make changes to a component’s state, you have to make them inside the component — the initialization and updating of the component’s state.

Class Components

States is only available to components that are called class components. The main reason why you will want to use class components over their counterpart, functional components, is that class components can have state. Let’s see the difference. Functional components are JavaScript functions, like this:

const App = (props) => {
  return (
    <div>
      { this.props }
    </div>
  )
}

If the functionality you need from your component is as simple as the one above, then a functional component is the perfect fit. A class component will look a lot more complex than that.

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = { username: 'johndoe' }
  }
  render() {
    const { username } = this.state
    return(
      <div>
        { username }
      </div>
    )
  }
}

Above, I am setting the state of the component’s username to a string.

The Constructor

According to the official documentation, the constructor is the right place to initialize state. Initializing state is done by setting this.state to an object, like you can see above. Remember: state is a plain JavaScript object. The initial state of the App component has been set to a state object which contains the key username, and its value johndoe using this.state = { username: 'johndoe' }.

Initializing a component state can get as complex as what you can see here:

constructor(props) {
  super(props)
  this.state = { 
    currentTime: 0,
    status: false, 
    btnOne: false, 
    todoList: [],
    name: 'John Doe'
  }
}

Accessing State

An initialized state can be accessed in the render() method, as I did above.

render() {
  const { username } = this.state
  return(
    <div>
      { username }
    </div>
  )
}

An alternative to the above snippet is:

render() {
  return(
    <div>
      { this.state.username }
    </div>
  )
}

The difference is that I extracted the username from state in the first example, but it can also be written as const status = this.state.username. Thanks to ES6 destructuring, I do not have to go that route. Do not get confused when you see things like this. It is important to know that I am not reassigning state when I did that. The initial setup of state was done in the constructor, and should not be done again – never update your component state directly.

A state can be accessed using this.state.property-name. Do not forget that aside from the point where you initialized your state, the next time you are to make use of this.state is when you want to access the state.

Updating State

The only permissible way to update a component’s state is by using setState(). Let’s see how this works practically.

First, I will start with creating the method that gets called to update the component’s username. This method should receive an argument, and it is expected to use that argument to update the state.

handleInputChange(username) {
  this.setState({username})
}

Once again, you can see that I am passing in an object to setState(). With that done, I will need to pass this function to the event handler that gets called when the value of an input box is changed. The event handler will give the context of the event that was triggered which makes it possible to obtain the value entered in the input box using event.target.value. This is the argument passed to handleInputChange() method. So, the render method should look like this.

render() {
  const { username } = this.state
  return (
    <div>
      <div>
        <input 
          type="text"
          value={this.state.username}
          onChange={event => this.handleInputChange(event.target.value)}
        />
      </div>
      <p>Your username is, {username}</p>
    </div>
  )
}

Each time setState() is called, a request is sent to React to update the DOM using the newly updated state. Having this mindset makes you understand that state update can be delayed.

Your component should look like this;

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = { username: 'johndoe' }
  }
  handleInputChange(username) {
    this.setState({username})
  }
  render() {
    const { username } = this.state
    return (
      <div>
        <div>
          <input 
            type="text"
            value={this.state.username}
            onChange={event => this.handleInputChange(event.target.value)}
          />
        </div>
        <p>Your username is, {username}</p>
      </div>
    )
  }
}

Passing State as Props

A state can be passed as props from a parent to the child component. To see this in action, let’s create a new component for creating a To Do List. This component will have an input field to enter daily tasks and the tasks will be passed as props to the child component.

Try to create the parent component on your own, using the lessons you have learned thus far.

Let’s start with creating the initial state of the component.

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = { todoList: [] }
  }
  render() {
    return()
  }
}

The component’s state has its todoList set to an empty array. In the render() method, I want to return a form for submitting tasks.

render() {
  const { todoList } = this.state
  return (
    <div>
      <h2>Enter your to-do</h2>
      <form onSubmit={this.handleSubmit}>
        <label>Todo Item</label>
        <input
          type="text"
          name="todoitem"
        />
        <button type="submit">Submit</button>
      </form>
    </div >
  )
}

Each time a new item is entered and the submit button is clicked, the method handleSubmit gets called. This method will be used to update the state of the component. The way I want to update it is by using concat to add the new value in the todoList array. Doing so will set the value for todoList inside the setState() method. Here’s how that should look:

handleSubmit = (event) => {
  event.preventDefault()
  const value = (event.target.elements.todoitem.value)
  this.setState(({todoList}) => ({
    todoList: todoList.concat(value)
  }))
}

The event context is obtained each time the submit button is clicked. We use event.preventDefault() to stop the default action of submission which would reload the page. The value entered in the input field is assigned a variable called value, which is then passed an argument when todoList.concat() is called. React updates the state of todoList by adding the new value to the initial empty array. This new array becomes the current state of todoList. When another item is added, the cycle repeats.

A chart illustrating the cycle explained above.

The goal here is to pass the individual item to a child component as props. For this tutorial, we’ll call it the TodoItem component. Add the code snippet below inside the parent div which you have in render() method.

<div>
  <h2>Your todo lists include:</h2>
  { todoList.map(i => <TodoItem item={i} /> )}
</div>

You’re using map to loop through the todoList array, which means the individual item is then passed to the TodoItem component as props. To make use of this, you need to have a TodoItem component that receives props and renders it on the DOM. I will show you how to do this using functional and class components.

Written as a functional component:

const TodoItem = (props) => {
  return (
    <div>
      {props.item}
    </div>
  )
}

For the class component, it would be:

class TodoItem extends React.Component {
  constructor(props) {
    super(props)
  }
  render() {
    const {item} = this.props
    return (
      <div>
        {item}
      </div>
    )
  }
}

If there is no need to manage state in this component, you are better off using functional component.

Leveling Up

You will be handling state very often while developing React application. With all the areas covered above, you should have the confidence of being able to dive into the advanced part of state management in React. To dig deeper, I recommend React’s official documentation on State and Lifecycle as well as Uber’s React Guide on Props vs State.

The post React State From the Ground Up appeared first on CSS-Tricks.

Microsoft Edge Variable Fonts Demo

Post pobrano z: Microsoft Edge Variable Fonts Demo

The Edge team put together a thorough demo of variable fonts, showcasing them in all of their shape-shifting and adaptive glory. Equally interesting as the demo itself is a history of web typography and where variable fonts fit in the grand scheme of things.

This demo pairs well with v-fonts.com, which is an interactive collection of variable fonts that allows you to play around with the variable features each font provides.

Direct Link to ArticlePermalink

The post Microsoft Edge Variable Fonts Demo appeared first on CSS-Tricks.

Going From Dumb Little Idea to Real Website in Like 10 Minutes

Post pobrano z: Going From Dumb Little Idea to Real Website in Like 10 Minutes

I live in Bend, Oregon. I woke up with the dumbest idea ever that there should be a little food truck map website and it should be called Vend, Oregon. It’s not my finest idea, but hey, I’m full of those. Fortunately, we don’t have to spend all day on this.

1) Figure out what’s going to go on this dumb little website

Fortunately, all the hard work was already done. One of our local rags already created a list of them. They allude to a map multiple times, but it’s hard to dig it up. In searching around a bit, I found this which does have an embedded Google Map.

Perhaps this can be useful then! Let’s blow up this map and embed it properly!

2) Make the dumb site

Fortunately, Google Maps are embeddable. Let’s just slap their embed code in an HTML document:

<body>
  <iframe src="https://www.google.com/maps/d/embed?mid=1bg2tr60F_w395jAY-WW8JGbwSCM" width="640" height="480"></iframe>
</body>

And have it cover the entire page:

html, body {
  margin: 0;
  height: 100%; 
  overflow: hidden;
}

iframe {
  postion: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 0;
}

Let’s use CodePen Projects for this, as that’ll get us another step closer to having this live.

The extra files there are just a Bend logo I fired through RealFaviconGenerator.

3) Buy the dumb domain name

This is the point where you really start to question the idea. But, go ahead and pull the trigger anyway. The internet needs you.

4) It’s dumb, but it it might as well be HTTPS

One big reason to use CloudFlare is you get HTTPS even on their free plan. Might as well take advantage of that. This means pointing the nameservers from your domain registrant over to CloudFlare.

5) Deploy the CodePen Project

You can deploy the site right out of CodePen Projects.

Note that you get some IP addresses there. Add those as A Records right in CloudFlare and you’re done!

6) Bask in your dumb idea


Swear to god, 10 minutes from start to finish.

The post Going From Dumb Little Idea to Real Website in Like 10 Minutes appeared first on CSS-Tricks.

A Better Sketch File, a Better Designer, a Better You

Post pobrano z: A Better Sketch File, a Better Designer, a Better You

I’ve been thinking about this post by Isabel Lee for the last couple of weeks — it’s all about how we should be more considerate when making designs in Sketch. They argue that we’re more likely to see real efficiency and organizational improvements in our work if we name our layers, artboards, and pages properly. Isabel writes:

Keeping a super organized Sketch file has helped me smooth out my design process and saved me time when I was trying to find a specific component or understand an archived design. For instance, I was looking for an icon that I used six months ago and it was (relatively) easy to find because all my artboards and layers were well-named and grouped reverse-chronologically. I was also able to cross-reference it with my meeting notes from around that time. If I hadn’t done any of that work (thanks Past Isabel!), I probably would’ve had to dig through all my old designs and look at each layer. Or worse — I would’ve had to recreate that icon.

Since I read this I’ve been doing the same thing and effectively making “daily commits” with the naming of my pages and it’s been genuinely helpful when looking back through work that I’ve forgotten about. But what I really like about this tidy-up process is how Isabel describes the way in which they could easily look back on their work, identify weaknesses in their design process, and how to become a better designer:

Aside from making it easier to find things, it’s also helped me cultivate good documentation habits when I want to analyze my old work and see where I could’ve made improvements. I revisited one of my old Sketch files and realized that I didn’t do enough research before diving into a million iterations for an initial idea I had.

Direct Link to ArticlePermalink

The post A Better Sketch File, a Better Designer, a Better You appeared first on CSS-Tricks.

Consistent Design Systems in Sketch With Atomic Design and the Auto-Layout Plugin

Post pobrano z: Consistent Design Systems in Sketch With Atomic Design and the Auto-Layout Plugin

Do you design digital products (or websites) and hand design files off to developers for implementation? If you answered yes, settle in! While the should-designers-code debate rages on, we’re going to look at how adding a methodology to your design workflow can make you faster, more consistent, and loved by all developers… even if you don’t code.

Let’s dig in!

Why a methodology?

In the development world, it seems like at least half of your career is about staying up to date with new tech and leveling up your skills. While the pace may not be quite as frantic in the design landscape as it is in development, there definitely has been a huge shift in tools over the past three years or so.

Tools like Sketch have made a lot of the old pain of working in design files a thing of the past. Smart combinations of text styles, object styles, symbols, and libraries now mean sweeping changes are just one click away. No more picking through 40 Photoshop layers to make a single color change.

Yet, sweeping color changes in a marketing landing page is no longer the biggest design challenge. Design and development teams are now expected to deliver complex interfaces loaded with interaction and conditional states… for every device available now and the next day. Working as both a designer and developer, I have seen the workflow friction from both sides.

Beyond tools, designers need an approach.

Thinking in terms of „components”

If you work in the tech space in any capacity, you have likely heard of development frameworks such as React, Angular, or Vue.

Um yeah, I’m a designer so that doesn’t really concern me, bye.

Kinda. But if you’re hoping to do design work for modern digital products, there is a pretty big chance that said products will be built using one of these frameworks. No one expects an architect to build the structures themselves, but they better have a high-level understanding of the what the tools are and how they will be used.

So here’s what you need to know about modern front-end frameworks:

They have brought on a paradigm shift for developers in which products are built by combining a series of smaller components into complex systems which can adapt to different contexts and devices. This makes the code easier to maintain, and the entire system more flexible.

For a variety of legitimate reasons, many designers have not caught on to this paradigm shift as quickly as developers. We are missing a mental model for creating the pieces that make up these interfaces independently from their environment/pages/screens/viewports etc.

One such approach is Atomic Design.

What is Atomic Design?

First coined by Brad Frost, Atomic Design is a methodology which tries to answer a simple question: if hundreds of device sizes mean we can no longer effectively design „pages,” then how do we even design?

The answer lies in breaking down everything that could make up a „page” or „view” into smaller and smaller pieces, creating a „system” of blocks which can then be recombined into an infinite number of variations for our project.

You can think of it like the ingredients in a recipe. Sure, you could make muffins, but you could just as easily make a cake with the same list of ingredients.

Brad decided to use the chemistry analogy, and so he proposes that our systems are made up of:

  • Atoms
  • Molecules
  • Organisms

For the sake of simplicity, let’s take a look at how we might apply this to a website.

Atoms

Atoms represent the smallest building blocks which make up our user interfaces. Imagine a form label, a form input, and a button. Each one of those represents an atom:

A header, text block, and link each serve as atoms.

Molecules

Molecules are simply groups of atoms combined to create something new. For our purposes, we can think of molecules as groups of disjointed UI pieces which are combined to create a meaningful component.

The atoms come together to form a „card” component.

Organisms

Organisms are made up of groups of molecules (or atoms or other organisms). These are the pieces of an interface which we might think of as a „section.” In an invoicing application, an organism could be a dashboard combining a „new invoice” button (atom), a search form (molecule), a „total open” card (molecule), and table listing overdue invoices. You get the idea.

Let’s look at what a „featured block” organism might look like in our simple website:

A header (atom), three cards (molecules), an image (atom), and a teaser (molecule) are combined to form one featured block organism.

Using stacks for consistency

So, now that we have a mental model for the „stuff,” how do we go about creating these building blocks? Sketch is great out of the box, but the plugins available for it provide huge performance tools… just like text editors for developers. We will be using Sketch’s built-in symbols tools, as well as the amazing Stacks” feature from Anima App’s Auto-Layout plugin.

Using these tools will bring some priceless benefits which I will point out as we go, but at the very least you can count on:

  • better design consistency and faster iteration
  • a sanity check from using consistent spacing multipliers
  • faster reordering of content
  • help identifying design problems quickly and early on

What exactly are stacks?

If you’ve ever heard developers excitedly talk about flexbox for building layouts in CSS, then you can think of stacks as the Sketch equivalent. Stacks (like flexbox) allow you to group a series of layers together and then define their spacing and alignment on a vertical or horizontal axis.

Here we group three items, align them through their center, and set 48px vertical space between each one:

A simple stacked folder aligning and distributing three items.

The layers will automatically be group into a blue folder with an icon of vertical or horizontal dots to show what kind of stack you have.

Look at that! You just learned flexbox without touching a line of code. 😂

Nested stacks

The real power of stacks comes from nesting stacks inside other stacks:

Stacks can be nested inside of each other to create complex spacing systems.]

Here, we can see a card component made up of multiple stacks:

  • card__cta link from the previous example.
  • card__copy stack which handles the alignment & space for the header and text.
  • card__content which controls the spacing and alignment between the card__cta and card__copy stacks.

A quick note about layer naming

I almost always use the BEM naming convention for my components. Developers appreciate the logic when I have to to hand off design files because it often aligns with the naming conventions they are using in code. In the case where I’m developing the project myself, it gives me a bit of a head start as I’ve started thinking about the markup at the design stage.

If that’s super confusing, don’t worry about it. Please just make your colleagues’ job a little easier by organizing your layers and giving them descriptive names.

Stacks shmacks, I have great attention to detail and can do all this manually!

You’re absolutely right! But what about when you have carefully laid out 10 items, all of varying sizes, and now they need extra space between them? Or, you need to add a line of text to one of those items? Or, you need to split content into three columns rather than four?

That never happens, right? 😱

One of two things usually happens at this stage:

  1. You start manually reorganizing all the things and someone’s paying for wasted time (whether it’s you or the client).
  2. You kinda fudge it… after all, the developer surely knows what your original intentions were before you left every margin off by a couple pixels in your layout. ¯\_(ツ)_/¯

Here’s what stacks get you:

  • You can change the alignment or spacing options as much as you like with a simple value adjustment and things will just magically update.
  • You can resize elements without having to pick at your artboard to rejig all the things.
  • You can reorder, add, or remove items from the stack folder and watch the items redistribute themselves according to your settings—just like code. 🎉

Notice how fast it is to edit content and experiment with different layouts all while maintaining consistency:

Stacks and symbols make experimentation cheap and consistent.

OK, so now we know why stacks are amazing, how do we actually use them?

Creating stacks

Creating a stack is a matter of selecting two (or more) layers and hitting the stacks folder icon in the inspector. From there, you can decide if you are stacking your layers horizontally or vertically, and set the distance between the items.

Here’s an example of how we’d create an atom component using stacks:

Creating a horizontal stack with 20px spacing between the text and icon.

And, now let’s apply the stacks concept to a more complex molecule component:

Creating a card molecule using nested stacks.

Creating symbols from stacks

We’ve talked about the many benefits of stacks, but we can make them even more efficient by applying Sketch’s symbol tool to them. The result we get is a stack that can be managed from one source instance and reused anywhere.

Creating an atom symbol

We can grab that call-to-action stack we just created and make it a symbol. Then, we can use overrides for the text and know that stacks will honor the spacing:

Creating a symbol from a stack is great for ensuring space consistency with overrides.

If I decide later that I want to change the space by a few pixels, I can just tweak the stack spacing on the symbol and have it update on every instance 🎉

Creating a molecule symbol

Similarly, I can group multiple stacked atoms into a component and make that into a symbol:

Creating a card symbol from our stacks and call-to-action symbol.

Symbols + stacks = 💪

Wouldn’t it be nice if we could maintain the spacial requirements we set regardless of the tweaks we might bring to them down the line? Yes!

Replacing one item with another inside a component

Let’s assume our card component now requires a button rather than a link as a call-to-action. As long as we place that button in the correct stack folder, all the pixel-nudging happens automagically:

Because our symbol uses stacks, the distance between the copy and the call-to-action will automatically be respected.

Editing molecules and organisms on the fly 🔥

You might be thinking that this isn’t a huge deal and that adjusting the tiny spacial issue from the previous example would have taken just a moment without stacks. And you wouldn’t be wrong. But let’s refer back to our notions about atomic design for a moment, and ask what happens when we have far more complex „organisms” (groups of atoms and molecules) to deal with?

Similar to our mobile example from the beginning, this is where the built-in power of stacks really shines:

Stacks and symbols makes experimentation cheap and consistent.

With a library of basic symbols (atoms) at our fingertips, and powerful spacing/alignment tools, we can experiment and create endless variations of components. The key is that we can do it quickly and without sacrificing design consistency.

Complex layouts and mega stacks

Keeping with the elements we have already designed, let’s see what a layer stack might look like for a simple marketing page:

An example of an expanded layer stack.

Don’t let the initial impression of complexity of those stacks scare you. A non-stacked version of this artboard would not look so different aside from the color of the folder icons.

However it’s those very folders that give us all the power:

Layout experimentation can be fast and cheap!

We may not need to code, but we have a responsibility to master our tools for efficiency and figure out new workflows with our developer colleagues.

This means moving away from thinking of design in the context of pages, and creating collections of components… modules… ingredients… legos… figure out a metaphor that works for you and then make sure the whole team shares the vocabulary.

Once we do this, issues around workflow and collaboration melt away:

Speed and Flexibility

Carefully building components with symbols and using automated and consistent spacing/alignment with stacks does require a bit of time investment upfront. However, the return of easy experimentation and ability to change course quickly and at low cost is well worth it.

Consistency and UX

Having to think about how elements work as combinations and in different contexts will catch UX-smells early and expose issues around consistency before you’re 13 screens in. Changing direction by adjusting a few variables/components/spacing units beats nudging elements around an artboard all day.

Responsibility and Governance

A single 1440px page view of the thing you are building simply does not provided a developer with enough context for multiple screens and interaction. At the same time, crafting multiple high fidelity comps one tiny element at a time is a budget buster (and this is particularly true of app designs). So, what tends to happen on small teams? The developer gets the one gorgeous 1440px view… aaaaand all the cognitive overhead of filling in the gaps for everything else.

Providing the details is our job.

Atomic design gave us speed, creative freedom, and flexibility. It changed everything.”

—From the forward of Atomic Design

If we work with developers on digital products, we should be excited about learning how the sausage is made and adapt our approach to design accordingly. Our tools may not evolve quite as quickly as JavaScript frameworks, but if you haven’t taken a peek under to hood of some of these apps in the last couple of years, this is a great time to dig in!

The post Consistent Design Systems in Sketch With Atomic Design and the Auto-Layout Plugin appeared first on CSS-Tricks.

Chrome DevTools “Local Overrides”

Post pobrano z: Chrome DevTools “Local Overrides”

There’s been two really interesting videos released recently that use the „Local Overrides” feature of Chrome DevTools in order to play with web performance without even touching the original source code.

The big idea is that you can literally edit CSS and reload the page and your changes stick. Meaning you can use the other performance testing tools inside DevTools to see if your changes had the effect you wanted them to have. Great for showing a client a change without them having to set up a whole dev environment for you.

Direct Link to ArticlePermalink

The post Chrome DevTools “Local Overrides” appeared first on CSS-Tricks.

Notched Boxes

Post pobrano z: Notched Boxes

Say you’re trying to pull off a design effect where the corner of an element are cut off. Maybe you’re a Battlestar Galactica fan? Or maybe you just like the unusual effect of it, since it avoids looking like a typical rectangle.

I suspect there are many ways to do it. Certainly, you could use multiple backgrounds to place images in the corners. You could just as well use a flexible SVG shape placed in the background. I bet there is also an exotic way to use gradients to pull it off.

But, I like the idea of simply taking some scissors and clipping off the dang corners. We essentially can do just that thanks to clip-path. We can use the polygon() function, provide it a list of X and Y coordinates and clip away what is outside of them.

Check out what happens if we list three points: middle top, bottom right, bottom left.

.module {
  clip-path: 
    polygon(
      50% 0,
      100% 100%,
      0 100%
    );
}

Instead of just three points, let’s list all eight points needed for our notched corners. We could use pixels, but that would be dangerous. We probably don’t really know the pixel width or height of the element. Even if we did, it could change. So, here it is using percentages:

.module {
  clip-path: 
    polygon(
      0% 5%,     /* top left */
      5% 0%,     /* top left */
      95% 0%,    /* top right */
      100% 5%,   /* top right */
      100% 95%,  /* bottom right */
      95% 100%,  /* bottom right */
      5% 100%,   /* bottom left */
      0 95%      /* bottom left */
    );
}

That’s OK, but notice how the notches aren’t at perfect 45 degree angles. That’s because the element itself isn’t a square. That gets worse the less square the element is.

We can use the calc() function to fix that. We’ll use percentages when we have to, but just subtract from a percentage to get the position and angle we need.

.module {
  clip-path: 
    polygon(
      0% 20px,                 /* top left */
      20px 0%,                 /* top left */
      calc(100% - 20px) 0%,    /* top right */
      100% 20px,               /* top right */
      100% calc(100% - 20px),  /* bottom right */
      calc(100% - 20px) 100%,  /* bottom right */
      20px 100%,               /* bottom left */
      0 calc(100% - 20px)      /* bottom left */
    );
}

And you know what? That number is repeated so many times that we may as well make it a variable. If we ever need to update the number later, then all it takes is changing it once instead of all those individual times.

.module {
  --notchSize: 20px;
  
  clip-path: 
    polygon(
      0% var(--notchSize), 
      var(--notchSize) 0%, 
      calc(100% - var(--notchSize)) 0%, 
      100% var(--notchSize), 
      100% calc(100% - var(--notchSize)), 
      calc(100% - var(--notchSize)) 100%, 
      var(--notchSize) 100%, 
      0% calc(100% - var(--notchSize))
    );
}

Ship it.

See the Pen Notched Boxes by Chris Coyier (@chriscoyier) on CodePen.

This may go without saying, but make sure you have enough padding to handle the clipping. If you wanna get really fancy, you might use CSS variables in your padding value as well, so the more you notch, the more padding there is.

The post Notched Boxes appeared first on CSS-Tricks.

React Native: A Better DOM?

Post pobrano z: React Native: A Better DOM?

How do we convince web developers that React Native has already solved many of the hardest GUI problems for them? Go back in time and release React Native before React DOM? Is there an easier way…

— Nicolas (@necolas) March 1, 2018

Like a lot of people in this Twitter thread, I didn’t really understand that React Native was even for building on the web. I thought it was a way to write React to build native mobile apps. Nicolas has a whole „React Native for Web” repo though, explaining otherwise. Plus a conference talk.

It probably doesn’t help that the tagline is „Build native mobile apps using JavaScript and React.” I suppose, it does do that (e.g. build an iOS or Android app), but it also can build your web app, which could mean… single code base?

Several of the replies suggest „a better DOM” which is interesting. Or, as Nicolas points out, it’s kinda like „web: the good parts” as much of it is an intentionally limited subset of the involved platforms in order to simplify things and make them interoperable.

Obviously, this isn’t for every project. But, if you have a React-based website already, and either have or want a native mobile app, then it seems like this is worth exploring.

Direct Link to ArticlePermalink

The post React Native: A Better DOM? appeared first on CSS-Tricks.

Three Techniques for Performant Custom Font Usage

Post pobrano z: Three Techniques for Performant Custom Font Usage

There’s a lot of good news in the world of web fonts!

  1. The forthcoming version of Microsoft Edge will finally implement unicode-range, the last modern browser to do so.
  2. Preload and font-display are landing in Safari and Firefox.
  3. Variable fonts are shipping everywhere.

Using custom fonts in a performant way is becoming far easier. Let’s take a peek at some things we can do when using custom fonts to make sure we’re being as performant as we can be.

1) Reduce the File Size

Far from containing only numbers, the Latin alphabet and common punctuation, many fonts support multiple languages and include thousands of additional glyphs, adding significantly to the file size.

The Mac tool Font Book can display all the available glyphs in a font.

In these cases, subsetting is useful. Subsetting is the removal of characters you don’t need. You can do this using the command line tool pyftsubset, which can be downloaded as part of FontTools. (The website FontSquirrel offers a GUI for subsetting. Its a popular alternative thats also worth considering – but be aware that it isn’t compatible with variable fonts). The easiest way to specify the characters you want to keep is with unicode. Unicode is a standard that provides a unique code to every character from the world’s languages.

Unicode has assigned a number to many thousands of characters. We are interested in a very limited subset.

The pyftsubset command is followed by the name of your font file and the unicode specifying your chosen unicode range. The following is a subset that caters to the English language.

pyftsubset SourceSansPro.ttf --unicodes="U+0020-007F"

You can then reduce the size of the font further by compressing to a woff2 file format. You could do this with a separate command line utility from Google, or just add some extra options when you run the pyftsubset command:

pyftsubset SourceSansPro.ttf --unicodes="U+0020-007F" --flavor="woff2" --output-file="SourceSansPro.woff2"

If you’re confident you’re not going to use any of the characters you’ve removed from the font, this is all you need to do — you’ve radically lowered the size of the font, and you can now use it in @font-face as usual. But what if some of the pages on your site make use of additional glyphs that have been removed from the font? You’ll want to avoid any characters being displayed with a fallback typeface. To solve this potential issue, be sure to note the range you use when creating your subset with pyftsubset. You’ll want to specify it within the @font-face block.

@font-face {
  font-family: 'Source Sans Pro';
  src: url('/fonts/SourceSansPro.woff2') format('woff2');
  unicode-range: U+0020-007F; /* The bare minimum for the English Language */
}

The above unicode-range is specifying characters that are likely to be used across all pages of the site. This font will therefore be downloaded on every page.

Firefox has the best font-related dev-tooling. Look in the Fonts tab of Firefox to find out which fonts are being used. In other browsers look in the Network tab to find out which font files are being downloaded.

I’ll also create another file with pyftsubset. This won’t repeat any of the characters from the the first file. Rather, it will only contain glyphs that are rarely used on the site.

pyftsubset SourceSansPro.ttf --unicodes="U+00A0-00FF,U+0100-017F" --output-file="SourceSansProExtra.ttf"

By again specifying a unicode-range within another @font-face declaration, we ensure the file will be downloaded only when its needed — when a character on the page matches against the specified range.

@font-face {
  font-family: 'Source Sans Pro';
  src: url('/fonts/SourceSansProExtra.woff2') format('woff2');
  unicode-range: U+00A0-00FF, U+0100-017F; /* additional glyphs */
}
Adding some random French accents to the HTML will cause the extra subset file to be downloaded.

You should cater the range to your own purposes. If you have any unusual punctuation or letters in your header or footer, make sure you include them in your main font file, otherwise both files will always be downloaded. For the site I work on, for example, I’ve included the © symbol (U+00A) into the main subset, because it’s included at the bottom of every page. You can find a handy list of unicode characters on Wikipedia.

2) Load Key Font Files as Early as Possible

Wow.https://t.co/6CfAK6mjYs CSS has 100 different @​font-face blocks.

That’s, well… that’s a lot. pic.twitter.com/jj2NFS4vd5

— Zach “Fancy Letters” Leatherman (@zachleat) June 25, 2016

Imagine the only CSS in your stylesheet is one hundred @font-face declarations and the following lines of code:

* {
  font-family: 'Lora';
  font-style: italic;
  font-weight: bold;
}

How many fonts would the browser download? One hundred? The answer is,
just one. Fonts are lazy loaded by default. This is a smart move by browser vendors — only download what is actually needed. There is, however, a downside. To know what font variants are being used, the browser must parse all the HTML and all the CSS. Only after all of that will any font files be requested. If we want to kick things off more quickly, we have to use preloading.

Preloading is as simple as adding a link tag into the head of the document:

<link rel="preload" href="/fonts/Lora-Regular.woff2" as="font" type="font/woff2" crossorigin>
The preloaded font is the first resource to download after the HTML document itself.

It’s not a good idea to preload too many resources, or wastefully preload any resource that might not be used on the page. For this reason I stick to preloading only the normal weight, non-italic file. I’m less concerned about a late-loading bold or italic file as those styles are used less often across the site. A flash of unstyled text (FOUT) for these font files is less disruptive than a FOUT of the regular Roman font, which makes up the bulk of the text. If you’re using a variable font, this is a non-issue. However, preloading variable fonts currently presents its own problem.

Should You Preload a Variable Font?

It’s clearly wasteful to send a browser a resource it can’t use. That’s why we include a type attribute that specifies the MIME type of the resource. If the resource isn’t supported by the browser, it won’t be downloaded. In the case of fonts, we specify type="font/woff2". Edge, Safari and Firefox are implementing both variable fonts and preload at the same time, so there isn’t an issue for those browsers. Chrome and Opera, however, have supported preload since 2016. Variable fonts are a brand new addition, whereas woff2 has been supported since 2014. For that reason, preloading a variable woff2 will force older versions of Chrome and Opera to download a resource they won’t know what to do with.

Ideally, we’d be able to specify the resource as a variable font within the type attribute, but this is largely unnecessary. Chrome is evergreen. There’s a new release every six weeks and it automatically updates in the background. Relatively few visitors will be using an ancient version. Once variable fonts have been around in Chrome for several versions, it will be safe to preload.

3) Managing FOUT and FOIT

So far we’ve looked at speeding up font loading. A good user experience is not just about the total loading time of a page or a font — it’s about how users experience the site while it’s loading. If you want users to stick around, you need to think about perceived performance. The different browsers aren’t consistent in how they manage font loading. We can now easily decide the loading strategy for ourselves using the CSS font-display property.

The font-display property is defined within an @font-face block.

@font-face {
  font-family: ExampleFont;
  src: url(/fonts/SourceSansPro.woff2) format('woff2');
  font-display: fallback;
}

The available options are block, optional, swap and fallback. Which should you pick?

The optional value sounds like a good bet — fonts are a nice-to-have enhancement, but not a strict necessity. In practice, I’ve found it a bad choice. Seeing the typeface of a page change upon navigation or reload is unexpected for users, and somewhat disconcerting. The window of time given for the custom font to load is incredibly small. If you’re preloading the font, it’s likely to load within this narrow timeframe. If not, users will often experience the fallback web safe font — even on a good connection with an expensive computer. That’s not great for brand consistency. If you’ve put much time into finding a similar fallback font, this might be an acceptable option, but if it’s that similar and performance is paramount, then maybe you should reconsider why you’re using a custom font at all.

The swap value is a better option. The web safe fallback font is shown immediately and replaced by the custom font once it’s loaded. Unfortunately, the swap period is infinite, so on a slow connection, the font could change after the user has already become immersed in the text, creating a jarring and disconcerting experience.

The fallback value is similar to the default behavior of most browsers — a short block period of invisible text followed by a fallback font if the custom font still hasn’t loaded. Unlike swap, there is a timeout period. If the custom font doesn’t load within three seconds, the font doesn’t change — the user is left with the fallback. You can read a whole article on CSS-Tricks about font-display and decide which option works best for you.

Wrapping Up

Text makes up the majority of content on most websites. Font-loading is therefore an important piece in the performance puzzle. If you want to keep up with font loading developments, Zach Leatherman just started a newletter about the subject.

The post Three Techniques for Performant Custom Font Usage appeared first on CSS-Tricks.