Add responsive styles using TypeStyle Media Queries

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 4 years ago

Media queries are very important for designs that you want to work on both mobile and desktop browsers. TypeStyle gives media queries special attention, making it easy to write them using CSS in JS.

In this lesson we show TypeStyle's media function. We also demonstrate how you can add non standard media queries if you want. Finally we show how organizing media queries this way is encapsulated under CSS class names.

[00:00] Here, we have a simple React application that renders a div with some content to the document. We bring in TypeStyle, and use its style function to generate a CSS class that sets the color to red. We then use this CSS class to style this root div.

[00:18] Now, let's add some responsive styles to this class name. TypeStyle provides a media function to make it easy to write media queries, which we can import from the main module. The first argument to the media function is the media query.

[00:32] This argument can be followed by any number of style objects. Here, we have specified that when the width becomes at least 500 pixels, pump up the font size for this class name to be 300 pixels. Now, as we play around with the width of the viewport, you can see the font size change because of this media query.

[00:52] To make the UI feel more fluent, we can easily add a CSS transition. For example, here I am specifying a transition for font size over a duration of 02 seconds. Now, if we play around with the viewport width, you can see that it feels much more fluent.

[01:09] You can add as many media queries as you want for a class. This is because the media function just returns a new nested CSS object, which fits well with the TypeStyle mixin model. For example, we can restrict this first media query to a maximum width of 700 pixels.

[01:27] Next, we go ahead and add another distinct media query for when the width is greater than 700 pixels, and then we bump up the font even more. Now, if you play around with the UI, you can see that we have three distinct font sizes.

[01:43] You can even write non-standard media queries if you want using TypeStyle. You simply nest the query under the $nest property of the style object. For example, here we are targeting the iPhone. We are doing this by targeting the vendor prefix -webkit-min-device-pixel-ratio.

[02:08] One final thing worth mentioning here is that you have true encapsulation of the media query. For example, all these media queries are nested under the class name, something that is lacking in plain CSS.