-
Notifications
You must be signed in to change notification settings - Fork 678
Добавляет статью "Mobile-first vs Desktop-first" #5450
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
solarrust
merged 28 commits into
doka-guide:main
from
reznikovAndrey:article/mobile-first-vs-desktop-first
Aug 27, 2024
Merged
Changes from 27 commits
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
0776485
Добавляет статью `Mobile-first vs Desktop-first`
reznikovAndrey 81b3e47
Улучшает визуал, добавляет ссылки
reznikovAndrey cbfdfae
Удалил комментарии
reznikovAndrey 91d5fd5
Добавляет пустую строку в конце `html` файла
reznikovAndrey 10b06aa
Добавляет пустые строки в `.md` файлах
reznikovAndrey d41c903
Убирает лишний пробел
reznikovAndrey 235e78d
Обновляет стили в верстке для демо
reznikovAndrey 8fdd15f
Добавляет пустую строку в конце файла
reznikovAndrey bcdac85
Убирает контрибьюторов
reznikovAndrey ad83f2a
Меняет описание
reznikovAndrey 00b87f2
Добавляет `related` статьи
reznikovAndrey 75aa96c
Улучшает блок `Кратко`
reznikovAndrey 232a929
Добавил главу `Особненности _Mobile-first_ подхода`
reznikovAndrey c577028
Убирает Trailing whitespace
reznikovAndrey 2ae9399
Добавляет раздел `Особненности _Desktop-first_ подхода`
reznikovAndrey e135c26
Отредактировал блок `Как пишется`, поправил стили в демо
reznikovAndrey 491b7cc
Добавляет `title` к демо
reznikovAndrey 7d88163
Обновляет демку
reznikovAndrey c8989b4
Меняет высоту `iframe` демо
reznikovAndrey b3dc900
Рефакторинг демки
reznikovAndrey 437df1a
Вносит мелкие правки по части пункутации в статью и блок "На практике"
reznikovAndrey 4a2e35f
Вносит мелкие правки в статью
reznikovAndrey 3444a60
Причёсывает демо
skorobaeus cc0d019
Изгоняет Онотоле
skorobaeus e1bcb37
Душнит про UI & UX
skorobaeus 4bd9c7d
Сражается с канцеляритом
skorobaeus 2577bd8
Упс
skorobaeus 5f2e346
Микро-правки
solarrust File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
253 changes: 253 additions & 0 deletions
253
css/mobile-first-vs-desktop-first/demos/adaptive-navbar/index.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,253 @@ | ||
<!DOCTYPE html> | ||
<html lang="ru"> | ||
|
||
<head> | ||
<title>Адаптивная вёрстка — Mobile-first vs Desktop-first — Дока</title> | ||
<meta charset="utf-8"> | ||
<meta name="viewport" content="width=device-width, initial-scale=1"> | ||
<link rel="preconnect" href="https://fonts.googleapis.com"> | ||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> | ||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto+Mono&family=Roboto:wght@400;500&display=swap"> | ||
<style> | ||
* { | ||
box-sizing: border-box; | ||
margin: 0; | ||
padding: 0; | ||
} | ||
|
||
body { | ||
font-family: "Roboto", sans-serif; | ||
background-color: #18191C; | ||
} | ||
|
||
code { | ||
font-family: "Roboto Mono", monospace; | ||
} | ||
|
||
header { | ||
border: 1px solid #000000; | ||
padding: 20px; | ||
background-color: #FFFFFF; | ||
} | ||
|
||
main { | ||
color: #FFFFFF; | ||
padding: 20px; | ||
} | ||
|
||
a { | ||
border-radius: 3px; | ||
color: inherit; | ||
text-decoration: none; | ||
font-style: italic; | ||
transition: background-color 0.2s linear; | ||
} | ||
|
||
a:hover { | ||
outline-width: 0; | ||
color: #FFFFFF; | ||
background-color: #000000; | ||
transition: all 0.2s linear; | ||
} | ||
|
||
pre { | ||
margin-block-start: 1em; | ||
font-size: inherit; | ||
} | ||
|
||
h1 { | ||
margin-bottom: 17px; | ||
font-size: 1.625rem; | ||
font-weight: 500; | ||
} | ||
|
||
.burger-icon { | ||
width: 24px; | ||
height: 24px; | ||
border: none; | ||
background: none; | ||
vertical-align: middle; | ||
cursor: pointer; | ||
} | ||
|
||
.link_active { | ||
text-decoration: underline; | ||
} | ||
|
||
.navbar { | ||
line-height: 1; | ||
} | ||
|
||
.navbar__links_list { | ||
display: flex; | ||
flex-direction: column; | ||
gap: 25px; | ||
margin-block-start: 25px; | ||
} | ||
|
||
.navbar__links_list>li { | ||
list-style-type: none; | ||
} | ||
|
||
.navbar__links_list_hidden { | ||
display: none; | ||
} | ||
|
||
.active-styles-example { | ||
padding: 20px; | ||
background-color: #2E9AFF; | ||
color: #18191c; | ||
font-size: 18px; | ||
} | ||
|
||
#flex-direction, | ||
#current-screen-width, | ||
#burger-icon { | ||
background-color: #000000; | ||
color: #FFFFFF; | ||
border-radius: 3px; | ||
} | ||
|
||
.text-list { | ||
list-style-type: none; | ||
} | ||
|
||
.text-list-item { | ||
position: relative; | ||
padding-inline-start: 25px; | ||
text-transform: lowercase; | ||
} | ||
|
||
.text-list-item + .text-list-item { | ||
margin-block-start: 10px; | ||
} | ||
|
||
.text-list-item::before { | ||
content: ""; | ||
position: absolute; | ||
top: 5px; | ||
left: 0; | ||
width: 14px; | ||
height: 14px; | ||
background-color: currentColor; | ||
} | ||
|
||
@media (width >= 640px) { | ||
header { | ||
padding: 20px 40px; | ||
} | ||
|
||
main { | ||
padding: 40px; | ||
} | ||
|
||
.active-styles-example { | ||
margin-inline-start: auto; | ||
width: 65%; | ||
padding: 25px 40px; | ||
} | ||
|
||
.burger-icon { | ||
display: none; | ||
} | ||
|
||
.navbar__links_list { | ||
flex-direction: row; | ||
margin: 0; | ||
} | ||
} | ||
</style> | ||
</head> | ||
|
||
<body> | ||
<header> | ||
<nav class="navbar"> | ||
<button class="burger-icon" onclick="handleClick(this)"> | ||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 26 26" aria-hidden="true"> | ||
<path stroke="#000" stroke-linecap="round" stroke-width="4" d="M3 4h20M3 13h20M3 22h20"/> | ||
</svg> | ||
</button> | ||
<ul class="navbar__links_list"> | ||
<li> | ||
<a href="#" class="link_active">Интересные факты</a> | ||
</li> | ||
<li> | ||
<a href="#">Происхождение</a> | ||
</li> | ||
<li> | ||
<a href="#">История одомашнивания</a> | ||
</li> | ||
<li> | ||
<a href="#">Физиология</a> | ||
</li> | ||
</ul> | ||
</nav> | ||
</header> | ||
<main> | ||
<h1>Интересные факты</h1> | ||
<ul class="text-list"> | ||
<li class="text-list-item">В каждом кошачьем ухе находится более чем 30 мускулов;</li> | ||
<li class="text-list-item">В среднем, коты спят по 16-18 часов в день, что составляет более 70% кошачьей жизни;</li> | ||
<li class="text-list-item">Кошки не чувствуют вкуса сладкого;</li> | ||
<li class="text-list-item">У кошек и людей за управление эмоциональным состоянием отвечают одинаковые отделы головного мозга.</li> | ||
</ul> | ||
</main> | ||
|
||
<div class="active-styles-example"> | ||
<p>Текущая ширина экрана: | ||
<code><span id="current-screen-width"></span>px</code> | ||
</p> | ||
<pre> | ||
.navbar__links_list { | ||
flex-direction: <span id="flex-direction"></span>; | ||
} | ||
|
||
.burger-icon { | ||
display: <span id="burger-icon"></span>; | ||
} | ||
</pre> | ||
</div> | ||
|
||
<script> | ||
const linksList = document.querySelector('ul'); | ||
const flexDirection = document.getElementById('flex-direction'); | ||
const screenWidth = document.getElementById('current-screen-width'); | ||
const burgerIconStyle = document.getElementById('burger-icon') | ||
|
||
let isOpen = false; | ||
|
||
handleResize() | ||
|
||
window.addEventListener('resize', handleResize) | ||
|
||
function handleResize() { | ||
screenWidth.innerText = window.innerWidth; | ||
|
||
if (window.innerWidth >= 640) { | ||
linksList.classList.remove('navbar__links_list_hidden') | ||
flexDirection.innerText = 'row' | ||
burgerIconStyle.innerText = 'none' | ||
|
||
} else { | ||
flexDirection.innerText = 'column' | ||
burgerIconStyle.innerText = 'initial' | ||
|
||
if (!isOpen) { | ||
linksList.classList.add('navbar__links_list_hidden') | ||
} | ||
} | ||
} | ||
|
||
function handleClick() { | ||
if (isOpen) { | ||
linksList.classList.add('navbar__links_list_hidden') | ||
isOpen = false | ||
} else { | ||
linksList.classList.remove('navbar__links_list_hidden') | ||
isOpen = true | ||
} | ||
} | ||
</script> | ||
</body> | ||
|
||
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,126 @@ | ||
--- | ||
title: "Mobile-first vs Desktop-first" | ||
description: "Разбираем основные подходы вёрстки и отвечаем на вопрос «С какого экрана начать верстать?»" | ||
authors: | ||
- rezn1kovAndrey | ||
contributors: | ||
- skorobaeus | ||
related: | ||
- css/pixel-perfect | ||
- html/seo-for-beginners | ||
- tools/site-readers | ||
- tools/web-app-types | ||
solarrust marked this conversation as resolved.
Show resolved
Hide resolved
|
||
tags: | ||
- article | ||
--- | ||
|
||
## Кратко | ||
|
||
_Mobile-first_ и _Desktop-first_ — это подходы в веб-дизайне и разработке, которые определяют, для каких устройств начинается проектирование дизайна и разработка в первую очередь. | ||
|
||
Mobile-first подход получил широкое распространение в современном вебе благодаря возросшей популярности мобильных устройств. Однако есть типы задач (CRM / ERP системы, дашборды, эффектные имидживые проекты), для решения которых Desktop-first остаётся более подходящим. | ||
|
||
## Mobile-first | ||
|
||
### Минималистичные интерфейсы | ||
|
||
Важно понимать, что в данном случае термин «минималистичные интерфейсы» не означает, что функциональность интерфейсов урезана. Минималистичность здесь — следствие небольшого размера экрана. В первую очередь создается UI & UX (англ. User Interface & User Experience, «пользовательский интерфейс и пользовательский опыт») именно для таких устройств. Далее, на основе мобильных интерфейсов, дорабатывается UI & UX для более широких экранов. | ||
|
||
### Мобильные сценарии использования | ||
|
||
Чтобы пользователю было комфортнее работать с мобильным интерфейсом, при его разработке учитывают: | ||
|
||
- удобство сенсорного взаимодействия (по интерактивным элементам должно быть удобно тапать пальцами); | ||
- возможность навигации одной рукой (дотягивается ли большой палец, не мешает ли ему что-то при скролле?); | ||
- приоритетность основного контента (не заставляйте пользователя доскролливать до контента, ради которого он зашёл). | ||
|
||
Не ограничивайтесь эмуляцией мобильной версии в браузере, откройте сайт, который разрабатываете, на смартфоне и попробуйте выполнить все приходящие в голову действия одной рукой, пока готовите кофе. | ||
|
||
### SEO | ||
|
||
Google преимущественно использует мобильную версию сайта для индексации ([mobile-first-indexing](https://developers.google.com/search/docs/crawling-indexing/mobile/mobile-sites-mobile-first-indexing)). | ||
|
||
## Desktop-first | ||
|
||
### Богатая функциональность | ||
|
||
Благодаря большому размеру экрана, как правило, не возникает проблем с расположением элементов интерфейса, которые предлагают расширенную функциональность. Например, интерфейс аналитического дашборда может вмещать редактируемые таблицы с большим количеством столбцов. | ||
|
||
### Десктопные сценарии использования | ||
|
||
С десктопным интерфейсом пользователь взаимодействует с помощью клавиатуры и мыши. Курсор менее требователен к области клика, чем палец, зато он всегда на экране: хорошей практикой будет следить, чтобы контент не появлялся и не пропадал с экрана при малейшем сдвиге мыши. Клавиатура в пользовательском интерфейсе может быть представлена (в виде подсказок о горячих клавишах) или нет, но в любом случае интерфейс должен на неё отзываться: например, отправится ли форма при нажатии на «Enter»? | ||
|
||
## Как пишется | ||
|
||
В качестве примера рассмотрим адаптивный блок навигации, который на планшетах и десктопе располагается горизонтально, а на мобильных устройствах — вертикально (и появляется при клике на иконку). | ||
|
||
Договоримся, что брейкпоинты будут такими: | ||
|
||
- мобильные устройства: ширина экрана меньше 640 пикселей; | ||
- планшеты: от 640 до 1024 пикселей; | ||
- десктопные устройства: больше 1024 пикселей. | ||
|
||
### Mobile-first | ||
|
||
Прописываем стили для мобильного устройства в начале CSS-файла. Не оборачиваем их в [медиавыражение](/css/media/). Ниже, внутри медиавыражения с соответствующим условием, пишем стили для планшета и десктопа: | ||
|
||
```css | ||
/* стили для мобильной версии */ | ||
.burger-icon { | ||
cursor: pointer; | ||
} | ||
|
||
.navbar__links_list { | ||
display: flex; | ||
flex-direction: column; | ||
gap: 25px; | ||
} | ||
|
||
/* стили для планшетной и десктопной версий */ | ||
@media (width >= 640px) { | ||
.burger-icon { | ||
display: none; | ||
} | ||
|
||
.navbar__links_list { | ||
flex-direction: row; | ||
margin: 0; | ||
} | ||
} | ||
|
||
/* здесь могли бы быть дополнительные стили для десктопной версии */ | ||
@media (width >= 1024px) {} | ||
``` | ||
|
||
### Desktop-first | ||
|
||
Прописываем стили для десктопного устройства, а далее, с помощью медиавыражений с соответствующими условиями, дописываем стили для остальных разрешений: | ||
|
||
```css | ||
/* стили для десктопной версии */ | ||
.burger-icon { | ||
display: none; | ||
} | ||
|
||
.navbar__links_list { | ||
display: flex; | ||
gap: 25px; | ||
} | ||
|
||
/* здесь могли бы быть дополнительные стили для планшетной версии */ | ||
@media (width < 1024px) {} | ||
|
||
/* стили для мобильной версии */ | ||
@media (width < 640px) { | ||
.burger-icon { | ||
display: initial; | ||
cursor: pointer; | ||
} | ||
|
||
.navbar__links_list { | ||
flex-direction: column; | ||
} | ||
} | ||
``` | ||
|
||
<iframe title="Адаптивная навигация" src="demos/adaptive-navbar/" height="590"></iframe> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
Современные CSS-фреймворки и UI-библиотеки в большинстве своем также придерживаются Mobile-first подхода: | ||
- [Tailwind](https://tailwindcss.com/docs/responsive-design#working-mobile-first) | ||
- [Material UI](https://mui.com/material-ui/getting-started/usage/#responsive-meta-tag) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.