Archive

Archive for September, 2020

All the Ways to Make a Web Component

September 7th, 2020 No comments

This is a neat page that compares a ton of different libraries with web components. One of the things I learned after posting “A Bit on Web Components Libraries” is that the web platform APIs were designed for libraries to be built around them. Interesting, right?

This page makes a counter component. By extending HTMLElement natively, they do it in 1,293 bytes, then each library adds things on top of that. The big libraries, like Vue and React, are clearly much bigger (but bring a ton of other functionality to the table). One of the biggest is CanJS (230,634 bytes), which isn’t aiming to be small, but, from their about page: “It targets experienced developers building complex applications with long futures ahead of them.” If the goal is small, Svelte is true to its mission of nearly compiling itself away ending at just 3,592 bytes, a third of the size of the super tiny lit-html and half the size of uhtml — both of which are just tiny abstractions that offer nicer templating and re-rendering.

Direct Link to ArticlePermalink


The post All the Ways to Make a Web Component appeared first on CSS-Tricks.

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

Categories: Designing, Others Tags:

Import Non-ESM libraries in ES Modules, with Client-Side Vanilla JS

September 7th, 2020 No comments

We’re living through a weird era where there are tons of JavaScript libraries that were meant to be used as tags that expose available globals. AND there are tons of JavaScript libraries that are meant to be used through module loaders. AND there are tons of JavaScript libraries that assume you will use them via npm. AND there are tons of libraries built for ES6 imports. If you write a JavaScript library and are shooting for maximum usage, you’d make it work in all those ways, even though that’s obnoxious legwork.

I love Lea’s ideas here on taking libraries that were never really meant to be ES6 import-ed, but doing it anyway.

For example:

window.module = {};
import("https://cdn.jsdelivr.net/gh/reworkcss/css@latest/lib/parse/index.js").then(_ => {
  console.log(module.exports);
});

And a function if you needed to be safer about that, like a little abstraction:

CodePen Embed Fallback

Check out the article for another clever little trick.

Direct Link to ArticlePermalink


The post Import Non-ESM libraries in ES Modules, with Client-Side Vanilla JS appeared first on CSS-Tricks.

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

Categories: Designing, Others Tags:

Working with JavaScript Media Queries

September 7th, 2020 No comments

What’s the first thing that comes to mind when you think of media queries? Maybe something in a CSS file that looks like this:

body {
  background-color: plum;
}


@media (min-width: 768px) {
  body {
    background-color: tomato;
  }
}

CSS media queries are a core ingredient in any responsive design. They’re a great way to apply different styles to different contexts, whether it’s based on viewport size, motion preference, preferred color scheme, specific interactions and, heck, even certain devices like printers, TVs and projectors, among many others.

But did you know that we have media queries for JavaScript too? It’s true! We may not see them as often in JavaScript, but there definitely are use cases for them I have found helpful over the years for creating responsive plugins, like sliders. For example, at a certain resolution, you may need to re-draw and recalculate the slider items.

Working with media queries in JavaScript is very different than working with them in CSS, even though the concepts are similar: match some conditions and apply some stuff.

Using matchMedia()

To determine if the document matches the media query string in JavaScript, we use the matchMedia() method. Even though it’s officially part of the CSS Object Model View Module specification which is in Working Draft status, the browser support for it is great going as far back as Internet Explorer 10 with 98.6% global coverage.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Chrome Firefox IE Edge Safari
9 6 10 12 5.1

Mobile / Tablet

Android Chrome Android Firefox Android iOS Safari
84 79 3 5.0-5.1

The usage is nearly identical to CSS media queries. We pass the media query string to matchMedia() and then check the .matches property.

// Define the query
const mediaQuery = window.matchMedia('(min-width: 768px)')

The defined media query will return a MediaQueryList object. It is an object that stores information about the media query and the key property we need is .matches. That is a read-only Boolean property that returns true if the document matches the media query.

// Create a media condition that targets viewports at least 768px wide
const mediaQuery = window.matchMedia('(min-width: 768px)')


// Check if the media query is true
if (mediaQuery.matches) {
  // Then trigger an alert
  alert('Media Query Matched!')
}

That’s the basic usage for matching media conditions in JavaScript. We create a match condition (matchMedia()) that returns an object (MediaQueryList), check against it (.matches), then do stuff if the condition evaluates to true. Not totally unlike CSS!

But there’s more to it. For example, if we were change the window size below our target window size, nothing updates the way it will with CSS right out of the box. That’s because .matches is perfect for one-time instantaneous checks but is unable to continuously check for changes. That means we need to…

Listen for changes

MediaQueryList has an addListener() (and the subsequent removeListener()) method that accepts a callback function (represented by the .onchange event) that’s invoked when the media query status changes. In other words, we can fire additional functions when the conditions change, allowing us to “respond” to the updated conditions.

// Create a condition that targets viewports at least 768px wide
const mediaQuery = window.matchMedia('(min-width: 768px)')


function handleTabletChange(e) {
  // Check if the media query is true
  if (e.matches) {
    // Then log the following message to the console
    console.log('Media Query Matched!')
  }
}


// Register event listener
mediaQuery.addListener(handleTabletChange)

// Initial check
handleTabletChange(mediaQuery)

The one-two punch of matchMedia() and MediaQueryList gives us the same power to not only match media conditions that CSS provides, but to actively respond to updated conditions as well.

When you register an event listener with addListener() it won’t fire initially. We need to call the event handler function manually and pass the media query as the argument.

CodePen Embed Fallback

The old way of doing things

For the sake of context — and a little nostalgia — I would like to cover the old, but still popular, way of doing “media queries” in JavaScript (and, yes, those quotes are important here). The most common approach is binding a resize event listener that checks window.innerWidth or window.innerHeight.

You’ll still see something like this in the wild:

function checkMediaQuery() {
  // If the inner width of the window is greater then 768px
  if (window.innerWidth > 768) {
    // Then log this message to the console
    console.log('Media Query Matched!')
  }
}


// Add a listener for when the window resizes
window.addEventListener('resize', checkMediaQuery);

Since the resize event is called on each browser resize, this is an expensive operation! Looking at the performance impact of an empty page we can see the difference.

That’s a 157% increase in scripting!

An even simpler way to see the difference is with the help of a console log.

That’s 208 resize events versus six matched media events.

Even if we look past the performance issues, resize is restrictive in the sense that it doesn’t let us write advanced media queries for things like print and orientation. So, while it does mimic “media query” behavior by allowing us to match viewport widths, it’s incapable of matching much of anything else — and we know that true media queries are capable of so much more.

Conclusion

That’s a look at media queries in JavaScript! We explored how matchMedia() allows us to define media conditions and examined the MediaQueryList object that lets us do one-time (.matches) and persistent (addListener()) checks against those conditions so that we can respond to changes (.onchange) by invoking functions.

We also saw the “old” way of doing things by listening for resize events on the window. While it’s still widely used and a totally legit way to respond to changes to the size of the window.innerWidth, it’s unable to perform checks on advanced media conditions.

To finish the article here is a useful example that is not achievable in the old way. Using a media query I will check if the user is in the landscape mode. This approach is common when developing HTML5 games and is best viewed on a mobile device.

CodePen Embed Fallback

The post Working with JavaScript Media Queries appeared first on CSS-Tricks.

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

Categories: Designing, Others Tags:

Using max() for an inner-element max-width

September 7th, 2020 No comments

I go into all this in The “Inside” Problem. The gist: you want an edge-to-edge container, but the content inside to have a limited width. I think there is absolutely no problem using a nested element inside, but it’s also fun to look at the possibilities of making that work on a single element.

My favorite from that article is this one that calculates padding for you:

CodePen Embed Fallback

While calc() does indeed do the trick, it doesn’t allow you to have a minimum padding. Well, max() does. I still find it hella confusing that we reach for max() when we want a minimum value but, hey, just gotta build that muscle memory.

Reader Caluã de Lacerda Pataca responded to our last newsletter where we mentioned these functions with a this clever idea:

CodePen Embed Fallback

Now we can make sure that the content doesn’t smash up against the edges no matter what.


The post Using max() for an inner-element max-width appeared first on CSS-Tricks.

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

Categories: Designing, Others Tags:

A Tribute to Stranger Things Logo, Theme, and Artworks

September 7th, 2020 No comments
Stranger things cast artwork

Early 1980s, we are in Hawkins, Indiana trying to solve the mystery of the Upside Down. Who could ever watch Stranger Things and not fantasize about being a part of that nerdy gang, right?

Stranger things hawkins

This nostalgic, binge-worthy sci-fi series surely was something special. Primarily inspired by the classic 80s horror movies, Stranger Things revived a lot of memories, especially for Stephen Spielberg and Stephen King fans. The show goes deeper in many pop-culture elements and makes fans of A Nightmare on Elm Street and The Ghost Busters appreciate it even more if that’s even possible.

Stranger things ghost busters halloween

Some members of the gang might seem a little less interested in playing Dungeons & Dragons towards the end of the show because of the hormones however Stranger Things was also a geek haven for D&D fans especially in the first season.

Stranger things dungeons and dragons

Beyond all this, if there is one stylistically recognizable feature of Stranger Things, it’s the logo. Glowing red letters floating in the darkness as the frame zooms out, and all combined with the spooky theme at the end, Stranger Things!

Stranger things logo gif

Beyond doubt, it is one of the most iconic TV series logos of all time. More than recognizable in fact some fans even argue that aesthetically the 80s themed title sequence symbolizes the hive-mind concept and the collectivism theme in the show.

Dissecting the Stranger Things Logo

The history of the Stranger Things logo dates back to the 1970s. The font was designed by an American type designer and calligrapher, Ed Benguiat, and released by the International Typeface Corporation (ITC) in 1977. It is widely used in popular culture and was specifically chosen by Imaginary Forces, a creative studio whom Duffer Brothers work with.

If you are wondering why this font looks so familiar, it’s because ITC Benguiat is used on the covers of Stephen King novels published in the 1980s. That is exactly why it was chosen to be the font of the Stranger Things logo.

stephen king book covers

One last fun fact is that it is also used by Quentin Tarantino for the opening and end credits of his movies

quentin tarantino end credits

Without further ado, we like to share some of the best Stranger Things logo variations and artworks that will take you deeper into the darkness.

Stranger Things Logo and Artworks

Stranger things neon logo
by Jonathan Ball
Stranger things logo variation
Stranger Things by Rafael Serra
Stranger things logo variation 2
Stranger things logo and illustration of the woods
Stranger Things by Marie Bergeron
Stranger things black and white logo variation
Stranger things logo and an illustration of the gang and the woods
Stranger things waffle illustration and logo variation
Stranger things light bulb illustration and logo variation
Stranger things kids on the hill illustration
by milo van sluis
Stranger things kids on the hill illustration 2
eleven artwork
by Sam Dunn
Stranger things kids illustration
by Studio ?adne Halo
illustration of stranger things hopper and eleven
by Timi Alonge
Hawkins National Laboratory illustration
Hawkins by bek
eleven eating waffles
11 by Deborah Lee
the gang and the demogorgon
by Hans Bennewitz
stranger things kids illustration
by doug ahern design
the upside down artwork
by Jonathan Ball

Conclusion

These were some of our favorite Stranger Things logo variations and artworks that make us feel like we are wandering in the unknowns of the Upside Down. Tell us in the comment section, if it weren’t for this epic logo, would Stranger Things give us the chills it usually did when we see a glowing, red neon billboard at night.

Categories: Others Tags:

A Designer’s Guide to Kerning, Tracking, and Letter-Spacing in 2020 | L e t ‘ s D o T h i s

September 7th, 2020 No comments

Have you ever been working on a project, added some text, only to notice that you love the font, but something looks terribly, terribly off?

That’s what we call a kerning issue.

Today we’re going to go over some simple rules of kerning, tracking, and letter spacing in graphic design.

Let’s do this!

What is Kerning and Tracking?

Kerning is defined as the amount of space between two letters, or other characters, such as numbers, punctuation, etc.

Tracking refers to loosening or tightening a selected block of text, while kerning is the process of adding or subtracting space between specific pairs of characters.

source

Tracking and kerning are absolute essential parts of design, and can change the entire look of your design with literally the slide of a button.

Proper kerning and tracking can take your design from something boring, to something with incredible visual appeal.

Tracking

Tracking, which is also commonly known as letter-spacing, controls the consistent space between letters that are across a block of text.

The spacing will be consistent throughout the entire block of text, and this method of spacing is most typically used in headings and logos.

If you want to increase the space between characters, then you need to adjust the value with positive number, and if you want to decrease the space, the use negative values instead.

Here are some before and after examples of tracking usage.

Kerning

Okay, so, to understanding kerning a little bit better, imagine this.

You remember those old wooden type boxes?

They looked a little something like this.

So while tracking refers to the consistent space between letters, kerning refers to the space between each individual letter.

You can imagine that each letter in any given typeface is like that old wooden type boxes. Each letter has a box surrounding it, making it impossible to move the letters closer together while you type.

Until you adjust the kerning.

When you adjust the kerning, it’s kind of like you manipulate that bo, and adjust it to your liking.

As you can see in this picture, manual kerning is definitely the way to go.

Letter Combos To Beware Of

The right amount of kerning and tracking will make or break your design.

You can have an ugly typeface and adjust the tracking levels, and suddenly, it’s incredibly aesthetic and visually pleasing to the eye.

A couple of things I do want to tell you about, so that you can learn from my mistakes and I can make things easier for you, are some weird letter combinations that just don’t look right.

I’m going to let you in on some letter combos that you can always be on the look out for so your design is always the most optimal.

•Slanted letters like: A, K, V, W, Y

• Letters with arms or cross strokes: F, L, T

• Letter combinations: W or V + A (any order); T or F + a lowercase vowel

These letter combinations don’t typically look good, from a kerning perspective.

So that’s where you as a designer come in and make the adjustments to your liking.

I just saved you a lot of time, so now you don’t have to look and wonder what looks wrong in your typeface design.

You can just automatically look at these combos and make some changes.

You’re welcome.

Wrapping up

Kerning and tracking are things that will always improve the more you experiment with them.

So, now that you know what kerning and tracking is, keep up the good work, keep trying out new things, and see what vibes with your style.

And of course,

Until next time,

Stay creative, y’all!

Read More at A Designer’s Guide to Kerning, Tracking, and Letter-Spacing in 2020 | L e t ‘ s D o T h i s

Categories: Designing, Others Tags:

3 Essential Design Trends, September 2020

September 7th, 2020 No comments

A seasonal change is on the horizon and that always has me looking to refresh projects. This month’s design trends provide a few different ways to do that without ripping up your entire website.

Here’s what’s trending in design this month.

Animated Heroes (That Aren’t Video)

Hero headers and screens that feature video animation have been popular for a while, but more website designers are experimenting with other types of full-screen moving graphics.

What’s cool about this trend is that it can take on plenty of different forms and look a lot of different ways, meaning that no two websites are identical in this regard.

The other bonus to this trend is that you can add a full-screen animation to almost any style of design without a complete overhaul of the website. You may need a few small tweaks to create a seamless transition from one screen to the next, but it’s a quick, modern design element that you can deploy rather quickly.

Typozon uses a quick motion graphic with plenty of different brand marks to tell the story of their brand identity work. Admittedly, the animation can get a little dizzying if you look at it too long, but the bright colors on the olive background are attention-getting for sure.

Day 1 Club by Spotify opens with a lot of motion in the setup and then settles into subtle motion behind the primary call to action. Shades of black and soft movement bring everything together and help you focus on the bright red button and text overlay.

Kieran Baybutt uses multiple animations for this portfolio website. The most interesting might be on the “second screen.” A couple of things are happening here. The words change with mouse movements as does the background image. There’s also a cool hover pointer featuring portfolio elements that’s in constant motion. There’s a lot going on here, but it makes you want to click around.

Animated or Floating Circles

Circles might be one of the hottest design trends of 2020. They are in all kinds of projects and keep evolving in different ways.

Maybe part of the reason is because of the message that designers are trying to convey in these projects. Circles are associated with harmony and protection. They are used to represent unity, community, and commitment. In motion, circles can also spark feelings of motion or movement with speed determining how chaotic (or not) that movement may be.

This month’s iteration of circle trends is animated. Some circles animate in place, while others seem to float in space on the canvas.

The circles in each example have something in common though – they bring you into the design and encourage interaction with it. (That might be why this website design trend is increasing in popularity all the time.)

The circular motion for the UX+ logo actually helps draw the eye away from all the almost overwhelming animation on the left side of the split-screen design. With plenty of white space surrounding it, the constant movement is just enough to pull attention to the logo and then down the screen to important information about the event.

Katch Me uses circles that seem to float over the background video with a soft “bounce” in place. The animation changes when the mouse hovers over each circle with an expanded action and the ability to move the circle in a larger space. The circles here are actually the call-to-action buttons.

Visually, the circles for Anastasiia Afanasieva‘s website look like a mashup of the above examples. There’s a rotating animation for circles that seem to float in space. You have to click through this design though to see the real brilliance in it. Each circle has a hover state that changes the background color of the website (and images in each box) to match the color displayed.

Bright Yellow Coloring

Another website design trend that might be a reflection of the state of the world is in the use of the color yellow. With a global health pandemic, design projects are leaning in to brighter, more cheerful tones to help offset the stress of the world.

For many, yellow can shine just a bit of hope and optimism into gloomier times.

While most of the projects using bright yellow as an eye-popping accent, others are going all in.

Next Big Thing AG uses yellow imagery inside of oversized cutout lettering (another website design trend this year) on a dark background. Even with the darker overall palette, the design feels bright and enticing. You almost want to dive deeper into the design to see what the image behind the letters is and what else the site contains.

Sonya Mudvex uses a full yellow background on her portfolio homepage to stop visitors in their tracks. The rest of the design features a soft gray background and plenty of yellow accents. In addition to great use of color here, there are plenty of other UX tricks in this design, including some geolocation tools if you interact with the ticket validation graphic on the screen.

Upqode uses yellow with a peachy color palette to stand out. The illustrated animations are much more lively thanks to bright coloring. The overall color palette is a bit unexpected, and that’s what makes it interesting.

Conclusion

If this month’s website design trends tell you anything, it’s that interactive elements and animation are a growing part of the conversation. Are you already using these techniques in projects? (If not, it is probably time to think about it.)

You can also see how the influence of what’s happening in the world around us impacts design as well. It can counter other emotions to create a better mental space or mirror what’s happening in the world around us.

Source

Categories: Designing, Others Tags:

Popular Design News of the Week: August 31, 2020 – September 6, 2020

September 6th, 2020 No comments

Every week users submit a lot of interesting stuff on our sister site Webdesigner News, highlighting great content from around the web that can be of interest to web designers.

The best way to keep track of all the great stories and news being posted is simply to check out the Webdesigner News site, however, in case you missed some here’s a quick and useful compilation of the most popular designer news that we curated from the past week.

Adobe Photoshop: All Versions List 1990-2020 [Infographic]

Website Animation Types & Trends that will Dominate your Screen in 2020–2021

Text Fields & Forms Design

Amazon Bottlerocket OS

4 Things Web Designers Can do to Improve UX

Portfolio Must-Have for a Designer

The Design System Encyclopedia

76 Tools for Designers in 2020

Developers, Watch Out for these Burnout Symptoms

Apple Accidentally Approved Malware to Run on MacOS

25 Inspiring Examples of Black Websites

Stitches – The Modern Styling Library

Component Driven User Interfaces

Intel Just Changed its Logo for the First Time since 2006

Nimbella – Simple Serverless Cloud for Developers

10 Habits of Successful Freelance Designers

Web Brutalism, Seamfulness, and Notion

Timely and Timeless Tactics for User-Oriented UX Design

How to Start a Freelance Web Design Business

Nessie – Lightweight Web Browser

5 Excellent Color Palette Generators Every Designer Should Try

7 Blunders You Must Stay Away from While Designing a Logo

Shopify Vs. WooCommerce ECommerce Platform Comparison

Pure CSS Images: 35 Free CSS Cartoon Characters

To Design and Develop an Interactive Globe

Want more? No problem! Keep track of top design news from around the web with Webdesigner News.

Source

Categories: Designing, Others Tags:

Beyond Media Queries: Using Newer HTML & CSS Features for Responsive Designs

September 4th, 2020 No comments
.

The browser will look for the first element where the media query matches the current viewport width, and then it will display the proper image (specified in the srcset attribute). The element is required as the last child of the element, as a fallback option if none of the initial source tags matches.

Beyond using media queries and modern CSS layouts, like flexbox and grid, to create responsive websites, there are certain overlooked things we can do well to make responsive sites. In this article, we’ll dig into a number tools (revolving around HTML and CSS) we have at the ready, from responsive images to relatively new CSS functions that work naturally whether we use media queries or not.

In fact, media queries become more of a complement when used with these features rather than the full approach. Let’s see how that works.

Truly responsive images

Remember when we could just chuck width: 100% on images and call it a day? That still works, of course, and does make images squishy, but there are a number of downsides that come with it, the most notable of which include:

  • The image might squish to the extent that it loses its focal point.
  • Smaller devices still wind up downloading the full size image.

When using images on the web, we have to make sure they’re optimized in terms of their resolution and size. The reason is to ensure that we have the right image resolution to fit the right device, so we don’t end up downloading really large and heavy images for smaller screens which could end up reducing the performance of a site.

In simple terms, we’re making sure that larger, high-resolution images are sent to larger screens, while smaller, low-resolution variations are sent to smaller screens, improving both performance and user experience.

HTML offers the element that allows us specify the exact image resource that will be rendered based on the media query we add. As described earlier, instead of having one image (usually a large, high-resolution version) sent to all screen sizes and scaling it to the viewport width, we specify a set of images to serve in specific situations.

<picture>
  <source media="(max-width:1000px)" srcset="picture-lg.png">
  <source media="(max-width:600px)" srcset="picture-mid.png">
  <source media="(max-width:400px)" srcset="picture-sm.png">
  <img src="picture.png" alt="picture"">
</picture>

In this example, picture.png is the full-size image. From there, we define the next-largest version of the image, picture-lg.png, and the size reduces in descending order until the smallest version, picture-sm.png. Note that we’re still using media queries in this approach, but it’s the element itself that is driving the responsive behavior rather than defining breakpoints in the CSS.

The media queries are added appropriately to scale with the sizes of the picture:

  • Viewports that are 1000px and above get picture.png.
  • Viewports that are between 601px and 999px get picture-lg.png.
  • Viewports that are between 401px and 600px get picture-sm.png.
  • Any thing smaller than 400px gets picture-sm.png.

Interestingly, we can also label each image by image density — 1x, 2x, 3x and so forth — after the URL. This works if we have made the different images in proportion to each other (which we did). This allows the browser to determine which version to download based on the screen’s pixel density in addition to the viewport size. But note how many images we wind up defining:

<picture>
  <source media="(max-width:1000px)" srcset="picture-lg_1x.png 1x, picture-lg_2x.png 2x, picture-lg_3x.png 3x">
  <source media="(max-width:600px)" srcset="picture-mid_1x.png 1x, picture-mid_2x.png 2x, picture-mid_3x.png 3x">
  <source media="(max-width:400px)" srcset="picture-small_1x.png 1x, picture-small_2x.png 2x, picture-small_1x.png 3x">
  <img src="picture.png" alt="picture"">
</picture>

Let’s look specifically at the two tags nested inside the element: .

The browser will look for the first element where the media query matches the current viewport width, and then it will display the proper image (specified in the srcset attribute). The element is required as the last child of the element, as a fallback option if none of the initial source tags matches.

We can also use image density to handle responsive images with just the element using the srcset attribute:

<img
 srcset="
  flower4x.png 4x,
  flower3x.png 3x,
  flower2x.png 2x,
  flower1x.png 1x
 "
 src="flower-fallback.jpg"
>

Another thing we can do is write media queries in the CSS based on the screen resolution (usually measured in dots per inch, or dpi) of the device itself and not just the device viewport. What this means is that instead of:

@media only screen and (max-width: 600px) {
  /* Style stuff */
}

We now have:

@media only screen and (min-resolution: 192dpi) {
  /* Style stuff */
}

This approach lets us dictate what image to render based the screen resolution of the device itself, which could be helpful when dealing with high resolution images. Basically, that means we can display high quality pictures for screens that support higher resolutions and smaller versions at lower resolutions. It’s worth noting that, although mobile devices have small screens, they’re usually high resolution. That means it’s probably not the best idea rely on resolution alone when determining which image to render. It could result in serving large, high-resolution images to really small screens, which may not be the version we really want to display at such a small screen size.

body {
  background-image : picture-md.png; /* the default image */
}


@media only screen and (min-resolution: 192dpi) {
  body {
    background-image : picture-lg.png; /* higher resolution */
  }
}

What gives us is basically the ability to art direct images. And, in keeping with this idea, we can leverage CSS features, like the object-fit property which, when used with object-position, allows us to crop images for better focal points while maintaining the image’s aspect ratio.

So, to change the focal point of an image:

@media only screen and (min-resolution: 192dpi) {
  body {
    background-image : picture-lg.png;
    object-fit: cover;
    object-position: 100% 150%; /* moves focus toward the middle-right */
  }
}

Setting minimum and maximum values in CSS

The min() function specifies the absolute smallest size that an element can shrink to. This function proves really useful in terms of helping text sizes to properly scale across different screen sizes, like never letting fluid type to drop below a legible font size:

html {
  font-size: min(1rem, 22px); /* Stays between 16px and 22px */
}

min() accepts two values, and they can be relative, percentage, or fixed units. In this example, we’re telling the browser to never let an element with class .box go below 45% width or 600px, whichever is smallest based on the viewport width:

.box {
  width : min(45%, 600px)
}

If 45% computes to a value smaller than 600px, the browser uses 45% as the width. Conversely, if 45% computes to a value greater than 600px, then 600px will be used for the element’s width.

The same sort of thing goes for the max() function. It also accepts two values, but rather than specifying the smallest size for an element, we’re defining the largest it can get.

.box {
  width : max(60%, 600px)
}

If 60% computes to a value smaller than 600px, the browser uses 60% as the width. On the flip side, if 60% computes to a value greater than 600px, then 600px will be used as the element’s width.

And, hey, we can even set a minimum and maximum range instead using the minmax() function:

.box {
  width : minmax( 600px, 50% ); /* at least 600px, but never more than 50% */
}

Clamping values

Many of us have been clamoring for clamp() for some time now, and we actually have broad support across all modern browsers (sorry, Internet Explorer). clamp() is the combination of the min() and max() functions, accepting three parameters:

  1. the minimum value,
  2. the preferred value, and
  3. the maximum value

For example:

.box {
  font-size : clamp(1rem, 40px, 4rem)
}

The browser will set the font at 1rem until the computed value of 1rem is larger than 40px. And when the computed value is above 40px? Yep, the browser will stop increasing the size after it hits 4rem. You can see how clamp() can be used to make elements fluid without reaching for media queries.

Working with responsive units

Have you ever built a page with a large heading or sub-heading and admired how great it looked on a desktop screen, only to check it on a mobile device and find out that’s it’s too large? I have definitely been in this situation and in this section I’ll be explaining how to handle such problems.

In CSS, you can determine sizes or lengths of elements using various units of measurements, and the most used units of measurements includes: px, em, rem, %, vw, and vh. Although, there are several more units that aren’t used as frequently. What’s of interest to us is that px can be considered an absolute unit, while the rest are considered relative units.

Absolute units

A pixel (px) is considered an absolute unit mainly because it’s fixed and does not change based on the measurement of any other element. It can be considered as the base, or root, unit that some other relative units use. Trying to use pixels for responsive behavior can bump into issues because it’s fixed, but they’re great if you have elements that should not be resized at all.

Relative units

Relative units, like %, em, and rem, are better suited to responsive design mainly because of their ability to scale across different screen sizes.

vw: Relative to the viewport’s width
vh: Relative to the viewport’s height
rem: Relative to the root () element (default font-size is usually 16px )
em: Relative to the parent element
%: Relative to the parent element

Again, the default font size for most browsers is 16px and and that’s what rem units use to generate their computed values. So, if a user adjusts the font size on the browser, everything on the page scales properly depending on the root size. For example, when dealing a root set at 16px, the number you specify will multiply that number times the default size. For example:

.8rem = 12.8px (.8 * 16)
1rem = 16px (1 * 16)
2rem = 32px (2 * 16)

What if either you or the user changes the default size? As we said already, these are relative units and the final size values will be based off of the new base size. This proves useful within media queries, where you just change the font size and the entire page scales up or down accordingly.

For example, if you changed the font-size to 10px within the CSS, then the calculated sizes would end up being:

html {
  font-size : 10px;
}
1rem = 10px (1 * 10)
2rem = 20px (2 * 10)
.5rem = 5px (.5 * 10)

Note: This also applies to percentage %. For instance:

100% = 16px;
200% = 32px; 
50% = 8px;

And what’s the difference between rem and em units? It’s what the unit uses as its base element. rem calculates values using the font size of the root () element, whereas an element declaring em values references the font size of the parent element that contains it. If the size of specified parent element is different from the root element (e.g. the parent elements is 18px but the root element is 16px) then em and rem will resolve to different computed values. This gives us more fine-grained control of how our elements respond in different responsive contexts.

vh is an acronym for viewport height, or the viewable screen’s height. 100vh represent 100% of the viewport’s height (depending on the device). In the same vein, vw stands for viewport width, meaning the viewable screen’s width of the device, and 100vw literally represents 100% of the viewport’s width.

Moving beyond media queries

See that? We just looked at a number of really powerful and relatively new HTML and CSS features that give us additional (and possible more effective) ways to build for responsiveness. It’s not that these new-fangled techniques replace what we’ve been doing all along. They are merely more tools in our developer tool belt that give us greater control to determine how elements behave in different contexts. Whether it’s working with font sizes, resolutions, widths, focal points, or any number of things, we have more fine-grain control of the user experience than ever before.

So, next time you find yourself working on a project where you wish you had more control over the exact look and feel of the design on specific devices, check out what native HTML and CSS can do to help — it’s incredible how far things have come along.


The post Beyond Media Queries: Using Newer HTML & CSS Features for Responsive Designs appeared first on CSS-Tricks.

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

Categories: Designing, Others Tags:

Supercharging Number Inputs

September 4th, 2020 No comments

Speaking of number scrubbing (i.e. adding mouse UX to number inputs), you can also add better keyboard commands to number inputs. Kilian Valkhof explains how he added up and down arrows to a number input, as well as modifier keys to change how much the keys increment the value, like Emmet does.

This would make a nice little web component.

Direct Link to ArticlePermalink


The post Supercharging Number Inputs appeared first on CSS-Tricks.

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

Categories: Designing, Others Tags: