Шрифт для адаптивной верстки

How to create responsive typography using CSS — Three different methods explained

TL;DR: Check out the final Codepen with all the methods. Resize the viewport to see the effect.

Why should you use responsive typography?

The web is used on various screen sizes. Your site has to work on mobile, tablet, laptop, desktop and basically everything in between so there’s a lot to take into consideration.

All of the method examples below are simplified as they only cover three selectors and one breakpoint.

You can use this simple HTML to try out all the methods in this tutorial:

 How to create responsive typography using CSS Vestibulum molestie sapien eget orci pellentesque, et aliquam lectus convallis. Phasellus neque velit, ultricies ut lacus at, finibus lobortis dui. Proin eget diam elit. Three different methods explained Pellentesque sagittis nisl nec rhoncus porta. Quisque luctus turpis nec turpis consequat fermentum et vitae diam. 

Method 1: Responsive typography using only media queries

This is the most basic method in our list.

Simply, declare your text styles and increase the font-size on bigger screens using a breakpoint:

/* Declare text styles */ h1  font-size: 2em; > h2  font-size: 1.5em; > p  font-size: 1em; > /* Increase font sizes by 1.5x on bigger screens */ @media (min-width: 48rem)  h1  font-size: 3em; > h2  font-size: 2.25em; > p  font-size: 1.5em; > > 

Check out the result from this Codepen. Resize the viewport to see the effect.

Using this method is totally fine and it does the job very well.

The downside is the large amount of code you have to write. The codebase gets larger with every new selector you need to add. You have to write the styles separately for every selector in each breakpoint.

In a real world you would probably have text selectors h1, h2, h3, h4, h5, h6, p and at least two breakpoints. At that point, this code is would’ve already gone from 20 lines to 67 lines. That’s 3.35x increase in the amount of code.

The next method will show how to decrease the code amount and make it easier to maintain!

Method 2: Responsive typography using a CSS custom property as a multiplier

CSS custom properties (variables) are super powerful. In the previous method, we increased the font sizes manually one selector at a time. Now, we’ll declare a multiplier variable for the font-sizes and only increase the value of the multiplier inside a breakpoint.

Let’s look at the code example in full and then break it down:

/* Declare a font size multiplier variable */ :root  --text-multiplier: 1; > /* Increase the size of the multiplier on bigger screens */ @media (min-width: 48rem)  :root  --text-multiplier: 1.5; > > /* Declare text styles using calc() function and the multiplier */ h1  font-size: calc(2em * var(--text-multiplier)); > h2  font-size: calc(1.5em * var(--text-multiplier)); > p  font-size: calc(1em * var(--text-multiplier)); > 

Check out the result from this Codepen. Resize the viewport to see the effect.

The first step is to declare a variable that we use to control our font size later on. We set the default value to 1.

The second step is to increase the multiplier value inside a breakpoint. Unlike SASS variables, CSS custom properties can be used inside media queries.

@media (min-width: 48rem)  :root  --text-multiplier: 1.5; > > 

The last step is to declare our font-sizes but this time we use the calc() function so we can utilise our multiplier.

h1  font-size: calc(2em * var(--text-multiplier)); > h2  font-size: calc(1.5em * var(--text-multiplier)); > p  font-size: calc(1em * var(--text-multiplier)); > 

As you can see, we only need to declare our font sizes once. This is a huge improvement compared to the first method.

Compared to the first method, we only have 17 lines of code compared to 20. If we would add four more selectors and one breakpoint, our code would only increase from 17 lines to 34. Remember that using the first method it would require 67 lines. Almost twice as much.

The decrease of code is due to our elegant way of using a CSS custom property as a multiplier. Adding another breakpoint takes only three lines of code because we don’t have to modify our font sizes at all. The code is also a lot easier to maintain and modify.

Adding breakpoints is as simple as:

/* Add more breakpoints */ @media (min-width: 64rem)  --text-multiplier: 1.75; > @media (min-width: 80rem)  --text-multiplier: 2.0; > 

To the user, this methods looks exactly the same as the first but the code is much better.

Next up, we’ll take a look at a new CSS clamp() function.

Method 3: Responsive typography using the CSS clamp() function

The clamp() function is pretty powerful! You can set a value using three parameters: a minimum value, a preferred value and a maximum value. Basically you’ll have a 3-in-1 value!

Example declaration for responsive text using the clamp() function looks like this:

font-size: clamp(2rem, 5vw, 3rem); 

This allows us to create responsive typography without any media queries. With only one line of code we set the minimum value (mobile), the maximum value (desktop) and the preferred value.

The font size will become fluid as it will always be the preferred value inside the min-max range. Very powerful!

To set the responsive typography for our demo, it is as simple as this:

/* Declare text styles */ h1, h2, p  /* Font minimum, preferred and maximum value */ font-size: clamp(var(--min), var(--val), var(--max)); > /* Font size variables */ h1  --min: 2em; /* minimum value */ --val: 5vw; /* preferred value = 5% viewport width */ --max: 3em; /* maximum value */ > h2  --min: 1.5em; /* minimum value */ --val: 4vw; /* preferred value = 4% viewport width */ --max: 2.25em; /* maximum value */ > p  --min: 1em; /* minimum value */ --val: 2.5vw; /* preferred value = 2.5% viewport width */ --max: 1.5em; /* maximum value */ > 

Check out the result from this Codepen. Resize the viewport to see the effect.

If you look at the code, you’ll see that by using CSS custom properties together with the clamp() function we are able to declare all the text styles at the same time with only on line of code.

After that, we just set the —min, —val and —max custom properties for each selector and we are done!

CSS custom properties can be scoped inside selectors so you can use the same custom properties with multiple selectors just like we have done here with our h1, h2 and p. These custom properties will not clash together even though they have the same name.

This method takes up 18 lines of code and with four more selectors and one breakpoint it would be 38 lines. So, it’s slightly larger than on the second method but we get fluid typography in return.

Note: The clamp() function is pretty new, so you should check if it has the browser support you need from caniuse.com.

Wrap up

CSS is powerful!

In many cases, there’s more than one way to achieve the desired result.

If you read this far, thank you! I hope you learned something new.

Here’s the final Codepen with all the methods once more. Resize the viewport to see the effect.

Thank you 🙏

I hope you found this article helpful 🔥

You can follow me on Twitter for more CSS, Design System and Figma content 💪

Источник

Отзывчивый шрифт. Адаптация текста между макетным и минимальным значениями

Адаптивный или отзывчивый шрифт — это мечта любого веб-разработчика. Я пересмотрел множество вариантов реализации, посидел вечерок и вывел для себя надежный работающий вариант. Им и хочу с тобой поделиться. Бонус SCSS миксин!

Итак, задача. Указывать значение по макету, а также минимальное значение при котором текст или заголовок хорошо бы смотрелся на мобильных устройствах, например iPhone 5 (320px). При этом шрифт бы адаптировался, увеличиваясь либо уменьшаясь в зависимости от ширины экрана.

Берем исходные значения из макета, к примеру заголовок H1 размером 40px. Так же нам нужна ширина всего полотна макета, к примеру 1280px.

Для получения минимального значения шрифта верстаем заголовок по макету и, с помощью средств разработчика Chrome (F12) выбираем нужный минимальный размер экрана и подбираем размер шрифта меняя значение пока текст не будет выглядеть адекватно. У меня получилось 24px

После этого в CSS, вместо font-size: 40px; пишем следующее.

font-size: calc(24px + 16 * (100vw / 1280)); 

Где 24px это наш минимальный шрифт, 16 – разница между шрифтом по макету 40 и минимальным шрифтом 24 (40-24 = 16). 100vw – это полная текущая ширина вьюпорта (экрана) 1280 – это ширина макета.

Тестируем и получаем отзывчивый шрифт, который полностью соответствует размеру по макету.

Но, на размере в 320px мы не увидим желаемого результата, а именно шрифта размером 24px. Это связано с тем, что мы никак не указали минимальный размер экрана именно в 320px.

Для решения ситуации пишем медиа запрос для 767px, и внутри меняем формулу:

Тут мы отнимаем 320px от полной ширины вьюпорта, а так же к добавочному числу 16 мы прибавляем еще его 70% (16 + 16 * 0.7)

Проверяем и видим полное соответствие поставленной задаче! При этом переход в брейк поинте сделан бесшовно и не заметно!

Конечно же мы можем закрыть все это в SCSS миксин:

$maxWidth: 1280; @mixin adaptiv-font($pcSize, $mobSize) < $addSize: $pcSize - $mobSize; $addMobSize: $addSize + $addSize * 0.7; @media (max-width: 767px) < font-size: calc(#+ # * ((100vw - 320px) / #)); > @media (min-width: 767px) < font-size: calc(#+ # * (100vw / #)); > > 

И подключать следующим образом:

Можно и вовсе избавиться от медиа запроса:

$maxWidth: 1280; @mixin adaptiv-font($pcSize, $mobSize) < $addSize: $pcSize - $mobSize; $maxWidth: $maxWidth - 320; font-size: calc(#+ # * ((100vw - 320px) / #)); > 

Буду рад прочесть в комментариях чем еще можно улучшить это решение. Спасибо за внимание!

Источник

Как сделать адаптивный шрифт css?

На сайте, есть меню ! На компьютере смотрится хорошо, но на более меньших размером гаджетов, шрифт ну слишком маленький, как лучше прописать в css , чтобы в зависимости от размера экрана, менялся размер шрифта в меню ?
5a8315d568c3e749305686.png 5a8315dedd4c8178348870.png

Ankhena

Дальше задавать нужные размеры в соответствующих интервалах медиа условий.
Но нужно понимать, что, вероятно, придется переделать не только размер шрифта.

media screen and (max-width: 768px) body < font-size: 2rem; >
Здесь меняете стили для нужных элементов , они применяться при размере экрана меньше 768px
>

5a831cd43d8f4460199377.png

Игорь Мясников, Извиняюсь конечно, но почему он их не видит ?

Игорь Мясников, В том то и дело, я если правильно понимаю то изменил его !
Если я конечно правильно понимаю! Я в коде ничего не менял, просто через браузер в инструментах для разработчиков поставил разрешение экрана как у iphone 8, но он все равно такой же и остался !

fastovvlad,
media only screen and (max-device-width:480px) /* Стили для мобильных браузеров ; (iPhone) */
>
или

5a8317962b319962359972.png

Он в нем и задан !

aliencash

drymind404

Задавать размеры текста, различных отступов, которые должны уменьшаться при уменьшении разрешения, с помощью единиц em и rem, в media-queries сделать несколько брекпоинтов, где уменьшать font-size у html в зависимости от разрешения. Нескольким элементам лучше задавать фиксированные размеры, в px. Например, параграфам. Иначе, как у вас, происходит чрезмерное уменьшение шрифтов. В своих сайтах обычно перед началом разработки уже выставляю p < font-size: 16px; >— тогда текст одинаково хорошо читается на любых устройствах. Некоторый не столь важный текст, показывающий, например, дополнительную информацию и тому подобное, можно делать меньше, например 12-14 px.

Источник

Читайте также:  Где научиться программированию python
Оцените статью