Поиск элементов и изменение текста
Чтение — около 9 минут· без учёта практики
От вычислений к странице
Покупатель положил в корзину два товара. Программа уже знает их количество, а на кнопке по-прежнему написано «Корзина · 0». Как показать покупателю новое количество?
Когда браузер читает HTML, он строит DOM (Document Object Model, объектную модель документа).
В этой модели каждому элементу страницы соответствует объект. В кнопке «Корзина» число находится в элементе <span id="cart-count">0</span>.
Если скрипт изменит его текст, покупатель увидит новое количество.
Чтобы изменить надпись, скрипту сначала нужно найти счётчик. Для поиска браузер
предоставляет объект document, который представляет открытую страницу.
Поиск по селектору
document.querySelector(selector) ищет первый элемент, подходящий под CSS-селектор,
и возвращает объект этого элемента. Селектор передаём строкой.
Например, "#products" ищет по id, ".price" — по классу,
"h3" — по имени тега. Эти три способа разобраны в уроке CSS
о селекторах типа, класса и id.
У карточки мяча в Лавке есть атрибут data-id="ball". Селектор "[data-id='ball']" находит её по значению этого атрибута.
Чтобы найти цену мяча, запишем "[data-id='ball'] .price". Пробел означает, что элемент с классом price находится внутри карточки.
Такой поиск разобран в теме «Селекторы потомков».
Другие варианты записи можно посмотреть в справочнике CSS-селекторов.
Возьмём первые две карточки каталога Лавки — канат и мяч. У каждого товара название находится в h3.
В обоих вызовах на схеме ищем этот тег. Посмотрите на объект
слева от точки. В первом случае поиск начинается во всём документе, во втором — внутри карточки мяча.
Найдите названия мяча и каната
Атрибуты data-* позволяют хранить дополнительные данные прямо в HTML-элементе. У каждой карточки в атрибуте data-id записан код товара. У мяча это ball, у каната — rope. По этому значению скрипт находит нужную карточку, а внутри неё ищет заголовок h3 с названием товара.
Во вкладке index.html можно посмотреть разметку карточек внутри body, а во вкладке style.css — их оформление.
Запустите пример. В области результата появятся две карточки, а в панели «Консоль» — названия найденных товаров. Какое название изменится, если в main.js заменить ball на rope? Сделайте замену и запустите пример снова.
index.html
<main>
<h2 id="catalog-title">Лавка Тони</h2>
<div id="products">
<article class="product" data-id="rope">
<h3>Канат «Удав»</h3>
<strong class="price">490,00 ₽</strong>
</article>
<article class="product" data-id="ball">
<h3>Мяч для прогулок</h3>
<strong class="price">450,00 ₽</strong>
</article>
</div>
</main>
main.js
const firstName = document.querySelector("h3");
const card = document.querySelector("[data-id='ball']");
if (firstName !== null) {
console.log("Во всём документе:", firstName.textContent);
}
if (card !== null) {
const name = card.querySelector("h3");
if (name !== null) {
console.log("Внутри карточки:", name.textContent);
}
}
style.css
body {
margin: 1rem;
color: #2b211b;
background: #fffaf3;
font: 1rem/1.5 system-ui, sans-serif;
overflow-wrap: anywhere;
}
#products {
display: grid;
gap: .75rem;
}
.product {
padding: 1rem;
border: 1px solid #e2d2c0;
border-radius: 16px;
}
h3 {
margin: 0 0 .5rem;
}
Нажмите «Запустить», чтобы увидеть результат.
Хотя в примере два заголовка h3, querySelector() вернул только первое
в порядке документа. Это не массив. Для поиска всех совпадений есть отдельный метод, который разберём позже.
Когда мы вызываем querySelector() у найденной карточки, мы по-прежнему передаём методу CSS-селектор.
Так, card.querySelector("h3") находит первый заголовок h3 внутри карточки, поэтому повторять селектор самой карточки не нужно.
Ссылку на найденный заголовок можно сохранить в переменной name, объявленной через const.
Если изменить текст заголовка, ссылка в name останется прежней, а повторный вызов card.querySelector("h3") вернёт тот же элемент с новым текстом.
Читаем и меняем текст
Свойство textContent позволяет прочитать текст элемента и его потомков.
Если в #cart-items лежит абзац с подсказкой о пустой корзине, при чтении мы получим текст этой подсказки.
Присваивание этому свойству заменяет содержимое элемента новым текстом.
Выведите строку со скобками как текст
Предскажите, как на странице будет выглядеть строка с <b> после записи через textContent. Сравните строки «До замены» и «После замены» в консоли. Появился ли элемент b и остался ли прежний абзац?
index.html
<main>
<h2>Твоя корзина</h2>
<div id="cart-items"><p>В корзине пока пусто. Тони советует начать с игрушки.</p></div>
</main>
main.js
const items = document.querySelector("#cart-items");
const name = "<b>мяч</b>";
if (items !== null) {
console.log("До замены:", items.textContent);
items.textContent = name + " × 2";
console.log("После замены:", items.textContent);
console.log("Есть тег b:", items.querySelector("b") !== null);
console.log("Остался абзац:", items.querySelector("p") !== null);
}
style.css
body {
margin: 1rem;
color: #2b211b;
background: #fffaf3;
font: 1rem/1.5 system-ui, sans-serif;
overflow-wrap: anywhere;
}
Нажмите «Запустить», чтобы увидеть результат.
Проследите по схеме, что находится внутри #cart-items до и после записи в textContent.
Строка "<b>мяч</b>" здесь остаётся текстом: жирный элемент не создаётся.
Так удобно выводить поисковый запрос, имя покупателя или другие данные, которые должны отображаться буквально.
Не вставляйте такой текст как HTML. Само textContent не проверяет смысл введённых данных:
оно отвечает именно за текстовый вывод.
Прежний p внутри #cart-items исчез: присваивание заменило все дочерние узлы,
а не только видимые буквы. Поэтому меняйте небольшой целевой элемент, например .price или #cart-count.
Присваивание card.textContent = "450 ₽" удалило бы из карточки и заголовок, и остальные вложенные элементы.
textContent читает текст независимо от CSS-видимости и может включать пробелы и переносы из HTML.
Это не точная копия того, как браузер раскладывает текст на экране.
В примере с двумя карточками значение цены document.querySelector(".price").textContent — строка "490,00 ₽", а не число:
если нужно считать по текстовому значению, учитывайте преобразование типа.
В задании возьмём числовую цену прямо из данных.
Меняем классы, оформление оставляем в CSS
Добавим карточке состояние выбора. В учебном примере CSS уже описывает, как выглядит .is-selected:
остаётся добавить имя класса через classList.
Обновите состояние товара
У кольца нулевой остаток. Сверьте классы и подпись кнопки в консоли с карточкой. Измените stock на 3: как изменятся подпись о наличии и кнопка?
index.html
<main>
<article class="product is-muted" data-id="ring">
<h3>Кольцо «Апорт»</h3>
<p class="stock muted"></p>
<strong class="price">450,00 ₽</strong>
<button class="add" type="button">В корзину</button>
</article>
</main>
main.js
const card = document.querySelector(".product");
const stock = 0;
if (card !== null) {
card.classList.remove("is-muted");
card.classList.add("is-selected");
card.classList.toggle("is-unavailable", stock === 0);
console.log("Классы карточки:", card.className);
console.log("Есть класс product:", card.classList.contains("product"));
const status = card.querySelector(".stock");
const button = card.querySelector(".add");
if (status !== null && button !== null) {
status.textContent = stock > 0 ? "В наличии: " + stock : "Пока закончился";
button.textContent = stock > 0 ? "В корзину" : "Нет в наличии";
button.disabled = stock === 0;
console.log("Кнопка:", button.textContent);
}
}
style.css
body {
margin: 1rem;
color: #2b211b;
background: #fffaf3;
font: 1rem/1.5 system-ui, sans-serif;
overflow-wrap: anywhere;
}
.product {
padding: 1rem;
border: 1px solid #e2d2c0;
border-radius: 16px;
}
h3 {
margin: 0 0 .5rem;
}
.is-muted {
color: #6b5d52;
}
.is-selected {
border: 2px solid saddlebrown;
}
.is-unavailable .stock {
color: #6b5d52;
font-weight: 700;
}
button {
padding: .7rem 1.4rem;
border: 2px solid saddlebrown;
border-radius: 999px;
background: saddlebrown;
color: white;
font: inherit;
font-weight: 650;
cursor: pointer;
}
button:focus-visible {
outline: 3px solid #287a86;
outline-offset: 4px;
}
button:disabled {
opacity: .55;
cursor: not-allowed;
}
Нажмите «Запустить», чтобы увидеть результат.
classList.add("is-selected")добавляет класс, сохраняя остальные, а повторное добавление не создаёт дубликат,classList.remove("is-muted")удаляет указанный класс, причём отсутствие этого класса не мешает вызову,classList.contains("product")проверяет наличие класса и возвращает логическое значение,- В вызове
classList.toggle("is-unavailable", condition)второй аргументcondition— это условие, при котором у карточки должен быть классis-unavailable. В примере этоstock === 0. Если остаток равен нулю, условие даётtrueи метод добавляет класс, а при любом другом остатке условие даётfalseи метод убирает класс.
Без второго аргумента toggle("is-selected") переключает наличие класса на противоположное.
Если состояние уже известно из данных, удобнее передать условие: повторный вызов оставит нужное состояние,
а не перевернёт его снова.
Внешний вид задаётся в style.css. Само имя is-selected не имеет встроенного значения:
без соответствующего CSS класс появится, но оформление не изменится.
Цвет дополняет текст статуса, поэтому о наличии товара можно узнать и без различения цветов.
В Лавке у закончившегося товара кнопка показывает «Нет в наличии». В примере её подпись меняет textContent, а нажатие блокирует button.disabled = true.
Если элемент не найден
Поиск с корректным селектором возвращает null, если совпадений нет.
Это может быть опечатка, необязательный блок на другой странице или слишком ранний запуск скрипта.
Обращение к textContent или classList у null приведёт к ошибке.
Проверьте результат до обращения к свойству
В селекторе #catalog-staus пропущена буква. Запустите пример и посмотрите, дошла ли программа до последней строки. Исправьте селектор на #catalog-status и сравните подпись в каталоге с выводом в консоли.
index.html
<main>
<h2>Лавка Тони</h2>
<p id="catalog-status" role="status">Найдено: 2</p>
</main>
main.js
const status = document.querySelector("#catalog-staus");
console.log("Элемент найден:", status !== null);
if (status !== null) {
status.textContent = "Найдено: 1";
console.log("Новая подпись:", status.textContent);
} else {
console.log("Подпись не найдена");
}
console.log("Остальная программа работает");
style.css
body {
margin: 1rem;
color: #2b211b;
background: #fffaf3;
font: 1rem/1.5 system-ui, sans-serif;
overflow-wrap: anywhere;
}
Нажмите «Запустить», чтобы увидеть результат.
Условие status !== null отделяет найденный элемент от отсутствующего, поэтому внутри этой ветки можно обращаться к его свойствам.
Если блок по замыслу обязателен, одного пропуска недостаточно для исправления: проверьте селектор, разметку и момент запуска.
Здесь сообщение в консоли помогает заметить проблему.
Синтаксически неверный селектор, например "[", — другой случай:
он вызывает ошибку, а не возвращает null.
Для первых примеров используем заранее известные селекторы из разметки.
Когда элементы уже доступны
Браузер читает HTML сверху вниз и по мере чтения добавляет элементы в DOM. Проследите по схеме, на каком шаге в DOM появляется карточка товара.
Если поставить тег <script> после разметки карточек, перед </body>, к моменту запуска скрипта карточки уже будут в DOM.
Поэтому вызов document.querySelector(".product") найдёт первую карточку товара. Если выполнить тот же поиск до появления карточек, он вернёт null.
В редакторе HTML сначала подготавливается целиком, затем запускается JavaScript. Поэтому порядок подключения в настоящем HTML-файле проверяйте отдельно, если меняете его. Изменения DOM происходят в открытом документе, исходный файл на диске не переписывается. После обычной перезагрузки скрипт выполнится заново.
Описание API в справочнике:
document.querySelector(),
textContent и
classList.
Коротко
document.querySelector(селектор)возвращает первый подходящий элемент илиnull. Проверяйте результат перед использованием.textContentчитает и меняет текст элемента.classList.add,remove,toggleиcontainsуправляют классами. Оформление при этом описывается в CSS.- Чтобы скрипт нашёл карточки, подключите его после их разметки, перед
</body>.
Проверьте себя
Выберите ответ — объяснение появится сразу. Ответ можно менять.
Задания
Задание. Проект «Лавка Тони» — обновляйте подпись и счётчик вместе
Корзина уже умеет принимать покупки. Соберите обновление двух элементов страницы в одной функции, которая умеет показывать и пустую корзину.
Эти же шаги можно выполнить в своей папке.
- В
index.htmlочистите текст внутри#cart-items. Вjs/shop.jsперенесите присваиванияcartCount.textContentиcartItems.textContentизaddBall()в функциюrenderBallCart(). - Пусть функция показывает длину массива на кнопке. Для непустой корзины оставьте название мяча и количество. Для пустой запишите «В корзине пока пусто. Тони советует начать с игрушки.».
- В
addBall()послеcart.push(ball.id)вызовитеrenderBallCart(). Вызовите её также один раз при запуске страницы.
Проверьте результат. Нажмите «Корзина · 0» — в окне появится подсказка о пустой корзине. Нажмите «Закрыть», дважды нажмите у мяча «В корзину» и снова откройте корзину. На кнопке будет «Корзина · 2», в окне — «Мяч для прогулок × 2». Для проверки добавьте в конец renderBallCart() строку console.log(cart.length, cartCount.textContent). При каждой покупке в консоли можно будет сравнить количество в массиве и на кнопке.
Обновляйте подпись и счётчик вместе
Условие задания
js/shop.js
/*
Лавка Тони: программа магазина.
Разделы: товары, заказ, проверки и чек.
*/
console.log("Лавка Тони");
// Товары
const productName = "Мяч для прогулок";
const price = 450;
const isAvailable = true;
const isFavorite = false;
const description = "";
const ropeName = "Канат «Удав»";
const ropePrice = 490;
const ropeStock = 8;
// Заказ
const quantityText = "3";
const quantity = Number(quantityText);
const selectedProduct = null;
const promoCode = null;
let pickupPoint;
const pickupCost = 0;
const deliveryText = "150";
const savedDelivery = 0;
const delivery = savedDelivery ?? Number(deliveryText);
const savedName = "";
const customerName = savedName || "Гость";
const paid = 2000;
const hasCard = false;
const hasCash = true;
const isBlocked = false;
const isPaid = true;
const payOnPickup = true;
// Склад
const incoming = 5;
const packSize = 4;
let stock = 12;
stock += incoming;
stock -= quantity;
stock++;
const unpacked = stock % packSize;
// Чек заказа
function calcTotal(itemPrice, itemQuantity, itemDelivery = 150) {
if (itemQuantity <= 0) {
return 0;
}
return itemPrice * itemQuantity + itemDelivery;
}
const subtotal = price * quantity;
const total = calcTotal(price, quantity, delivery);
const change = paid - total;
function printReceipt() {
console.log(`Товары: ${subtotal}`);
console.log(`К оплате: ${total}`);
console.log(`Сдача: ${change}`);
}
console.log("Чек покупателю");
printReceipt();
console.log("Копия для склада");
printReceipt();
// Проверки заказа
const freeDeliveryFrom = 1000;
const selectedName = "Мяч для прогулок";
const hasEnough = stock >= quantity;
const hasFreeDelivery = subtotal >= freeDeliveryFrom;
const sameName = selectedName === productName;
const validQuantity = quantity > 0 && quantity <= stock;
const canPay = hasCard || hasCash;
const canOrder = validQuantity && canPay && !isBlocked;
let message = "";
if (isBlocked) {
message = "Заказ недоступен";
} else if (!hasEnough) {
message = "Недостаточно товара";
} else if (isPaid) {
message = "Передаём заказ в доставку";
} else {
message = "Ожидаем оплату";
}
// Подписи
const productCode = "B17";
const card = `${productName} — ${price} руб.`;
const badge = productName[0] + "-" + productCode;
// Признаки товара
const hasDescription = Boolean(description);
// Скидка на каждый мяч
const discountPerItem = 50;
const discountedTotal = (price - discountPerItem) * quantity + delivery;
const canCheckout = hasEnough && (isPaid || payOnPickup);
// Способ получения и наличие
const isPickup = delivery === 0;
const methodLabel = "Способ: " + (isPickup ? "Самовывоз" : "Доставка");
const stockLabel = isAvailable ? "В наличии" : "Закончился";
// Способ получения по коду из формы
const methodText = "1";
const methodCode = Number(methodText);
let methodName = "";
let methodCost = null;
switch (methodCode) {
case 1:
methodName = "Самовывоз";
methodCost = 0;
break;
case 2:
case 3:
methodName = "Доставка";
methodCost = 150;
break;
default:
methodName = "Неизвестный способ";
methodCost = null;
break;
}
// Упаковка заказа
const boxCapacity = 2;
let remaining = quantity;
let boxes = 0;
while (remaining > 0) {
if (remaining > boxCapacity) {
remaining -= boxCapacity;
} else {
remaining = 0;
}
boxes++;
}
// Подарки к заказам: Тони дарит мячик каждому чётному заказу дня
const lastOrder = 10;
const giftsEndAt = 8;
let giftCount = 0;
let giftSum = 0;
for (let orderNumber = 1; orderNumber <= lastOrder; orderNumber++) {
if (orderNumber === giftsEndAt) {
break;
}
if (orderNumber % 2 !== 0) {
continue;
}
giftSum += orderNumber;
giftCount++;
}
// Проверка calcTotal
console.log(calcTotal(ropePrice, 2));
console.log(calcTotal(price, 2, 0));
console.log(calcTotal(price, 0, 150));
// Данные первого товара
const ball = {
id: "ball",
name: productName,
price: price,
stock: stock,
priceLabel() {
return this.price + " ₽";
}
};
console.log(ball.priceLabel());
const rope = { id: "rope", name: ropeName, price: ropePrice, stock: ropeStock };
const ring = { id: "ring", name: "Кольцо «Апорт»", price: 450, stock: 0 };
const catalog = [ball, rope, ring];
console.log(catalog.length);
for (const product of catalog) {
console.log(product.name);
}
// Пробная цена для подарка
const gift = { id: rope.id, name: rope.name, price: rope.price };
gift.price = 0;
console.log(gift.price, rope.price);
function offerPrice(product) {
return product.offer?.price ?? product.price;
}
console.log(offerPrice(rope));
console.log(offerPrice({ price: rope.price, offer: { price: 0 } }));
function availableProducts(products) {
return products.filter(product => product.stock > 0);
}
console.log(availableProducts(catalog).map(product => product.name));
function findProduct(id) {
return catalog.find(product => product.id === id);
}
console.log(findProduct("rope")?.name ?? "Товар не найден");
console.log(findProduct("cat")?.name ?? "Товар не найден");
function countStock(products) {
return products.reduce((sum, product) => sum + product.stock, 0);
}
console.log(countStock(catalog));
function byPrice(products) {
return [...products].sort((first, second) => first.price - second.price);
}
console.log(byPrice(catalog).map(product => product.id));
console.log(catalog.map(product => product.id));
function searchProducts(products, query) {
const word = query.trim().toLowerCase();
return products.filter(product => product.name.toLowerCase().includes(word));
}
console.log(searchProducts(catalog, " КАНАТ ").map(product => product.name));
function checkEqual(label, actual, expected) {
if (actual === expected) {
console.log("Пройдено: " + label);
} else {
console.log("Ошибка: " + label, actual, expected);
}
}
checkEqual("пустой склад", countStock([]), 0);
checkEqual("поиск без регистра", searchProducts(catalog, " КаНаТ ")[0]?.id, "rope");
checkEqual("неизвестный код", findProduct("cat"), undefined);
const cartDialog = document.querySelector("#cart-dialog");
const openCart = document.querySelector("#open-cart");
const closeCart = document.querySelector("#close-cart");
openCart.addEventListener("click", () => cartDialog.showModal());
closeCart.addEventListener("click", () => cartDialog.close());
cartDialog.addEventListener("close", () => openCart.focus());
document.querySelector(".product h3").textContent = ball.name;
document.querySelector(".product .price").textContent = ball.priceLabel();
const cart = [];
const cartCount = document.querySelector("#cart-count");
cartCount.textContent = cart.length;
const cartItems = document.querySelector("#cart-items");
function addBall() {
cart.push(ball.id);
cartCount.textContent = cart.length;
cartItems.textContent = findProduct(cart[cart.length - 1]).name + " × " + cart.length;
}
document.querySelector(".product .add").addEventListener("click", addBall);
index.html
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Лавка Тони — учебный магазин игрушек и вещей для собак.">
<title>Лавка Тони</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/shop.css">
</head>
<body class="shop">
<a class="skip" href="#catalog">К товарам</a>
<main>
<section class="shop-hero" aria-labelledby="shop-title">
<div><p class="eyebrow">Маленькая лавка большого друга</p><h1 id="shop-title">Для игр, прогулок<br>и сладких снов.</h1>
<p>Привет, это Тони! Готовлю лавку игрушек и вещей для наших собачьих дел.</p>
<a class="shop-link" href="#catalog">Заглянуть в лавку ↓</a><p class="muted">Учебный магазин · без оплаты и настоящих заказов</p></div>
<figure><img src="assets/tony-toy.png" alt="Тони со своим любимым канатом" width="300" height="400"><figcaption>Главный по проверке игрушек</figcaption></figure>
</section>
<section id="catalog" aria-labelledby="catalog-title">
<div class="section-heading"><div><p class="eyebrow">Выбрано с лапой</p><h2 id="catalog-title">Лавка Тони</h2></div>
<button id="open-cart" type="button">Корзина · <span id="cart-count">0</span></button>
</div>
<p id="catalog-status" role="status">Первый товар в Лавке.</p>
<div id="products" class="products">
<article class="product" data-id="ball">
<div class="product-art"><img src="assets/ball.svg" alt="Мяч для прогулок" width="300" height="240"></div>
<div class="product-body">
<h3></h3>
<div class="product-bottom"><strong class="price"></strong>
<button class="add" type="button">В корзину</button>
</div>
</div>
</article>
</div>
</section>
</main>
<footer><p>© 2026 Тони и его хозяин · Сделано для любопытных</p></footer>
<dialog id="cart-dialog" aria-labelledby="cart-title">
<div class="section-heading">
<h2 id="cart-title">Твоя корзина</h2>
<button id="close-cart" type="button" class="secondary">Закрыть</button>
</div>
<div id="cart-items">В корзине пока пусто. Тони советует начать с игрушки.</div>
</dialog>
<script src="js/shop.js"></script>
</body>
</html>
css/style.css
/* Все обычные правила проекта распределены по слоям. */
@layer base, layout, components;
@layer base {
/* Общие стили сайта Тони */
/* Ширина и высота включают внутренние отступы и рамку — у всех элементов и псевдоэлементов */
*,
*::before,
*::after {
box-sizing: border-box;
}
/* Палитра сайта в пользовательских свойствах: цвет меняется в одном месте */
:root {
--accent: saddlebrown; /* заголовки, меню, акценты */
--text: #2b211b; /* основной текст */
--text-muted: #6b5d52; /* подписи и второстепенный текст */
}
/* Шрифт заголовков Nunito (лицензия SIL Open Font License): кириллица и латиница в разных файлах */
@font-face {
font-family: "Nunito";
src: url("../assets/nunito-cyrillic-800-normal.woff2") format("woff2");
font-weight: 800;
font-display: swap; /* пока шрифт загружается, текст виден запасным шрифтом */
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: "Nunito";
src: url("../assets/nunito-latin-800-normal.woff2") format("woff2");
font-weight: 800;
font-display: swap;
unicode-range: U+0000-00FF, U+2000-206F, U+20AC, U+2122;
}
body {
background-color: linen;
color: var(--text); /* цвет для потомков без собственного значения */
font-size: 1.0625rem; /* 17px при настройке браузера по умолчанию */
font-family:
system-ui,
-apple-system,
"Segoe UI",
Roboto,
sans-serif; /* системный шрифт устройства */
line-height: 1.6; /* множитель: у каждого элемента интервал от его собственного размера шрифта */
margin: 0; /* убираем отступ браузера: шапка и подвал во всю ширину окна */
}
/* Поля основного содержимого: текст не прижимается к краям окна */
/* Изображения и видео не шире колонки, пропорции сохраняются */
img,
video {
max-width: 100%;
height: auto;
}
/* Фреймы, аудиоплеер и поля формы не выходят за колонку */
iframe,
audio,
input,
select,
textarea,
button {
max-width: 100%;
}
/* Разрешаем группе полей сужаться вместе с колонкой. */
fieldset {
min-width: 0;
}
/* Общий цвет заголовков — групповой селектор */
h1,
h2 {
color: var(--accent);
font-family: "Nunito", "Trebuchet MS", system-ui, sans-serif;
font-weight: 800;
line-height: 1.2; /* крупному тексту хватает меньшего интервала */
}
/* Размеры заголовков в rem — от размера шрифта корня, а не родителя */
h1 {
text-align: center;
font-size: 2.5rem;
}
h2 {
font-size: 1.75rem;
}
}
@layer layout {
main {
padding: 1.5rem 1rem;
max-width: 68rem; /* на широком экране строки не растягиваются на всё окно */
margin: 0 auto; /* колонка по центру */
}
}
@layer components {
/* Вводный блок главной страницы */
.intro {
background-color: hsl(30, 80%, 95%);
padding: 1.5rem; /* фон вокруг текста; заодно не выпускает margin заголовка за пределы блока */
border-radius: 16px; /* скругляется и фон, хотя рамки нет */
/* Лапка в правом нижнем углу; цвет фона выше остаётся запасным, если картинка не загрузится */
background-image: url("../assets/paw.svg");
background-repeat: no-repeat;
background-position: right 1rem bottom 1rem;
background-size: 4rem;
}
/* Разделы главной — светлые карточки на фоне страницы */
main > section {
background-color: var(--paper, #fffaf3);
border: 1px solid hsl(28, 30%, 82%);
border-radius: 16px;
padding: 1.5rem;
margin-top: 1.5rem;
}
/* Ширина вводных абзацев ограничена 60ch; количество букв в строке зависит от шрифта и текста */
.intro p {
max-width: 60ch;
}
/* Важное предупреждение во вводном блоке — темнее основного акцента */
.intro strong {
color: #6e3510;
}
/* Оглавление главной страницы — переносимый ряд «таблеток» на Flexbox */
.toc {
background-color: white;
border: 1px solid tan;
display: flex;
flex-wrap: wrap; /* «таблетки», которым не хватает места, переходят на новую строку */
gap: 0.5rem; /* промежутки между «таблетками» и между строками */
list-style: none;
padding: 0.75rem;
}
/* Подчёркивание ссылок чуть ниже букв: не задевает выносные элементы */
a {
text-underline-offset: 3px;
}
/* Тонкая линия отделяет шапку от страницы */
header {
border-bottom: 1px solid tan;
}
/* Меню в одну строку на Flexbox: пункты — флекс-элементы, промежутки задаёт gap */
nav ul {
margin: 0;
padding: 0.5rem 1rem;
display: flex;
gap: 0.5rem;
list-style: none;
}
/* Ссылка на запись стоит отдельно у правого края: автоматический отступ забирает свободное место */
nav li:last-child {
margin-left: auto;
}
/* Ссылки меню в шапке — селектор потомков */
nav a {
color: var(--accent);
text-decoration: none;
display: inline-block; /* у строчной ссылки вертикальный padding не раздвигает строку */
padding: 0.4rem 0.9rem;
border-radius: 999px; /* «таблетка»: радиус больше половины высоты */
}
/* Ссылки оглавления главной страницы */
.toc a {
color: var(--text-muted); /* тёплый серый: контраст 6.34:1 на белом фоне оглавления */
display: block; /* ссылка заполняет «таблетку» целиком */
padding: 0.25rem 0.75rem;
border: 1px solid tan;
border-radius: 999px;
text-decoration: none;
}
/* Фотографии со скруглёнными углами */
figure img {
border-radius: 8px;
}
figcaption {
color: var(--text-muted); /* тёплый серый: контраст 5.64:1 на фоне linen */
font-size: 0.95rem;
}
footer {
background-color: hsl(30, 50%, 90%);
text-align: center;
padding: 1rem;
}
/* Ссылка в подвале берёт цвет текста подвала */
footer a {
color: inherit;
}
/* Поля формы получают шрифт страницы вместо шрифта браузера */
input,
select,
textarea,
button {
font: inherit;
}
/* Ссылки темнеют при наведении указателя */
a:hover {
color: #5c2d0c;
}
/* Ссылки меню подчёркиваются при наведении и фокусе с клавиатуры */
nav a:hover,
nav a:focus-visible {
text-decoration: underline;
}
/* Заметная рамка фокуса у ссылок, полей и кнопок при работе с клавиатуры */
:focus-visible {
outline: 3px solid #1f6feb;
outline-offset: 3px;
}
/* Цитата из книги — шрифтом с засечками и курсивом */
blockquote {
font-family: Georgia, "Times New Roman", serif;
font-style: italic;
border-left: 4px solid tan; /* черта слева выделяет цитату */
padding-left: 1rem;
}
/* Подпись под цитатой — у правого края */
blockquote + figcaption {
text-align: right;
}
/* Строки формы на Flexbox: подпись — колонка постоянной ширины, поле занимает остаток строки,
а на узком экране переносится под подпись */
fieldset p {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem 1rem;
}
fieldset p label {
flex: 0 0 12rem; /* не растёт и не сжимается, исходная ширина 12rem */
}
fieldset p input,
fieldset p select,
fieldset p textarea {
flex: 1 1 12rem; /* растёт и сжимается от исходной ширины 12rem */
min-width: 0; /* поле может стать уже своего автоматического минимума */
}
/* Фотоальбом на Grid. Все правила альбома собраны во вложенный блок: & — сам .gallery */
.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr));
gap: 1rem;
list-style: none;
padding: 0;
/* Карточка — точка отсчёта для значка */
& li {
position: relative;
}
/* Карточка со значком выделена рамкой */
& li:has(.badge) {
outline: 3px solid tan;
outline-offset: 4px;
border-radius: 8px;
}
& figure {
margin: 0;
}
& img {
width: 100%; /* фото заполняет ширину своей ячейки */
}
}
/* Список команд на Grid: термин в первой колонке шириной по самому длинному термину, описание — во второй */
dl {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
gap: 0.5rem 1rem;
}
dt {
grid-column: 1;
font-weight: bold;
}
dd {
grid-column: 2;
overflow-wrap: anywhere; /* длинный перевод переносится внутри своей колонки */
margin: 0; /* браузерный отступ слева больше не нужен: колонку задаёт сетка */
}
/* Длинные слова и адреса переносятся, а не выходят за край узкого экрана */
body {
overflow-wrap: break-word;
}
/* Таблица режима дня на узком экране прокручивается в своей рамке, а не сжимается до нечитаемых колонок */
.table-wrap {
overflow-x: auto;
}
table {
width: 100%;
min-width: 28rem;
}
/* Подпись таблицы прокручивается вместе с ней: прижимаем её к началу, чтобы она была видна сразу */
caption {
text-align: left;
}
/* Широкий экран: в разделе «Моя любимая игрушка» фото справа, текст слева.
На узком экране правило не действует, и раздел остаётся одной колонкой. */
@media (width >= 48rem) {
.toy {
display: grid;
grid-template-columns: minmax(0, 1fr) 300px;
column-gap: 1.5rem;
}
.toy figure {
grid-column: 2;
grid-row: 1 / span 6; /* фото рядом со всеми абзацами раздела */
margin: 0;
}
.toy hr {
width: 100%;
}
}
/* Значок «Любимая» в правом верхнем углу карточки; из потока исключён, поэтому фото не сдвигается */
.badge {
position: absolute;
top: 0.5rem;
right: 0.5rem;
padding: 0.2rem 0.7rem;
border-radius: 999px;
background-color: var(--accent);
color: white;
font-size: 0.85rem;
font-weight: bold;
}
/* Шапка прилипает к верхнему краю окна. Фон нужен, чтобы под шапкой не просвечивал текст страницы */
header {
position: sticky;
top: 0;
z-index: 10; /* выше карточек альбома: они тоже позиционированы и записаны в HTML позже шапки */
background-color: linen;
}
/* Липкая шапка должна быть низкой: пункты меню не сжимаются и не переносятся на вторую строку,
а если им не хватает места, меню прокручивается внутри шапки */
nav ul {
overflow-x: auto;
}
nav li {
flex-shrink: 0;
}
/* Заголовок, к которому ведёт ссылка-якорь, не прячется под липкой шапкой.
В rem: при увеличении текста растут и шапка, и отступ */
[id] {
scroll-margin-top: 4.5rem;
}
/* Ссылка, которая открывается в новой вкладке, помечена стрелкой — посетитель знает, что страница не сменится */
a[target="_blank"]::after {
content: " ↗";
}
/* Ссылка на электронную почту — с конвертом */
a[href^="mailto:"]::before {
content: "✉ ";
}
/* Первая ссылка меню — «Главная» — подписана лапкой без изменения HTML */
nav li:first-child a::before {
content: "🐾 ";
}
/* Первый абзац вводного блока крупнее остальных. :first-child здесь не подойдёт — первым стоит заголовок h1 */
.intro p:first-of-type {
font-size: 1.2rem;
}
/* Список игрушек: вместо стандартного кружка — косточка */
.toy-list li::marker {
content: "🦴 ";
}
/* Номера шагов в нумерованных списках — в цвет заголовков и жирные; текст пунктов не меняется */
ol li::marker {
color: var(--accent);
font-weight: bold;
}
/* Таблица режима дня: соседние рамки объединяются в одну линию */
table {
border-collapse: collapse;
}
/* Ячейки с воздухом и линией снизу; текст — от левого края и сверху, даже если в соседней ячейке две строки */
th,
td {
padding: 0.6rem 0.8rem;
border-bottom: 1px solid tan;
text-align: left;
vertical-align: top;
}
/* Шапка таблицы — в цвет заголовков сайта */
thead th {
background-color: var(--accent);
color: white;
}
/* Чётные строки тела таблицы — на светлом фоне: глаз не теряет строку */
tbody tr:nth-child(even) {
background-color: hsl(30, 80%, 95%);
}
/* Отдельные рамки без промежутков позволяют скруглить крайние ячейки. Линия только снизу не удваивается. */
table {
border-collapse: separate;
border-spacing: 0;
}
thead th:first-child {
border-top-left-radius: 8px;
}
thead th:last-child {
border-top-right-radius: 8px;
}
/* Форма записи: текстовые поля, список и область текста в едином стиле */
input:not([type="radio"], [type="checkbox"]),
select,
textarea {
padding: 0.5rem 0.75rem;
border: 1px solid #8a7660;
border-radius: 8px;
background-color: white;
}
/* Поле «Ведёт прогулку» менять нельзя — фон показывает это */
input[readonly] {
background-color: hsl(30, 80%, 95%);
}
/* Отмеченные флажки и переключатели — в цвет сайта */
input[type="radio"],
input[type="checkbox"] {
accent-color: var(--accent);
}
/* Неверно заполненное поле — после того как посетитель с ним поработал */
input:user-invalid,
select:user-invalid,
textarea:user-invalid {
border-color: firebrick;
}
/* Группы полей — светлые блоки с тонкой рамкой вместо рельефной рамки браузера */
fieldset {
margin-bottom: 1rem;
border: 1px solid #8a7660;
border-radius: 16px;
}
/* Группа полей, в которой сейчас работает посетитель */
fieldset:focus-within {
border-color: var(--accent);
}
/* Кнопки-«таблетки»: основная залита цветом, второстепенная — только рамка */
button {
padding: 0.7rem 1.4rem;
border: 2px solid var(--accent);
border-radius: 999px;
background-color: var(--accent);
color: white;
font-weight: bold;
cursor: pointer;
}
button[type="reset"] {
background-color: transparent;
color: var(--accent);
}
/* Текст ошибок связан с полями через aria-describedby и не полагается только на цвет рамки. */
.field-error {
display: none;
flex-basis: 100%;
color: firebrick;
font-weight: bold;
}
input:user-invalid + .field-error {
display: block;
}
/* Фото любимой игрушки — как карточка-полароид: слегка повёрнуто вокруг нижнего края, будто прижато к столу */
.toy img {
transform: rotate(-2deg);
transform-origin: 50% 100%;
}
/* Под указателем фото выпрямляется и чуть увеличивается */
.toy img:hover {
transform: rotate(0deg) scale(1.03);
}
/* «Таблетка» оглавления под указателем и в фокусе приподнимается: отдельное свойство translate */
.toc a:hover,
.toc a:focus-visible {
translate: 0 -2px;
}
/* Нажатая кнопка будто вдавливается */
button:active {
transform: translateY(1px) scale(0.98);
}
/* Плавные изменения: переходим конкретные свойства, а не all */
.toy img {
transition: transform 0.4s ease-out; /* фото выпрямляется плавно */
}
.toc a {
transition: translate 0.2s ease-out;
}
button {
transition:
background-color 0.2s,
transform 0.1s;
}
/* Посетитель попросил систему уменьшить движение — изменения происходят сразу, без переходов */
@media (prefers-reduced-motion: reduce) {
.toy img,
.toc a,
button {
transition: none;
}
}
/* Лапка у «Главной» машет, когда на ссылку наводят указатель */
@keyframes wag {
0%,
100% {
rotate: 0deg;
}
25% {
rotate: -18deg;
}
75% {
rotate: 18deg;
}
}
nav li:first-child a::before {
display: inline-block; /* строчный псевдоэлемент не поворачивается */
transform-origin: 50% 80%; /* лапка качается от «запястья» */
}
nav li:first-child a:hover::before,
nav li:first-child a:focus-visible::before {
animation-name: wag;
animation-duration: 0.5s;
animation-timing-function: ease-in-out;
animation-iteration-count: 2; /* помахать дважды и остановиться */
}
/* Приветствие на главной плавно появляется снизу при загрузке страницы */
@keyframes rise {
from {
opacity: 0;
translate: 0 16px;
}
/* to не задан: конечный кадр — обычный вид элемента */
}
.intro > * {
/* both: до старта — первый кадр (элемент скрыт во время задержки), после — последний */
animation: rise 0.6s ease-out both;
}
/* Строки появляются друг за другом */
.intro > :nth-child(2) {
animation-delay: 0.1s;
}
.intro > :nth-child(3) {
animation-delay: 0.2s;
}
.intro > :nth-child(4) {
animation-delay: 0.3s;
}
/* Посетитель попросил уменьшить движение — анимаций нет, всё видно сразу */
@media (prefers-reduced-motion: reduce) {
.intro > *,
nav li:first-child a:hover::before,
nav li:first-child a:focus-visible::before {
animation: none;
}
}
button:hover,
button:focus-visible {
background-color: #6b3513;
}
button[type="reset"]:hover,
button[type="reset"]:focus-visible {
background-color: hsl(30, 70%, 90%);
}
/* Подписи читаются на тёмной подложке и без декоративной тени. */
.gallery figcaption {
padding: 0.5rem;
color: white;
background-color: hsl(25, 50%, 15%);
text-shadow: 0 1px 3px rgb(0 0 0 / 60%);
}
/* Два слоя: чёткая тень у края и широкая мягкая тень под карточкой. */
.gallery li {
background-color: #fffaf3;
border-radius: 12px;
box-shadow: 0 1px 2px rgb(0 0 0 / 8%), 0 8px 24px rgb(0 0 0 / 8%);
}
/* Внутренняя тень дополняет уже знакомое преобразование нажатой кнопки. */
button:active {
box-shadow: inset 0 2px 3px rgb(0 0 0 / 25%);
}
/* Фигура обрезает только своё содержимое, тень родительской карточки остаётся снаружи. */
.gallery figure {
position: relative;
overflow: hidden;
border-radius: 12px;
}
.gallery figcaption {
position: absolute;
inset: auto 0 0;
padding: 2.5rem 0.5rem 0.5rem;
}
/* Запасная однотонная подложка остаётся в прежнем правиле; градиент подключается условно. */
@supports (background-image: linear-gradient(black, white)) {
.gallery figcaption {
background-color: transparent;
background-image: linear-gradient(
to top,
rgb(57 35 19 / 95%) 0,
rgb(57 35 19 / 95%) calc(100% - 2rem),
rgb(57 35 19 / 0%) 100%
);
}
}
/* Лапа остаётся верхним слоем; подсветка — под ней, над однотонным фоном. */
@supports (background-image: radial-gradient(white, transparent)) {
.intro {
background-image:
url("../assets/paw.svg"),
radial-gradient(ellipse at 80% 20%, rgb(255 196 110 / 45%), rgb(255 196 110 / 0%) 65%);
background-size: 4rem, auto;
background-position: right 1rem bottom 1rem, center;
background-repeat: no-repeat;
}
}
}
css/shop.css
.shop { --paper: #fffaf3; }
.shop main { max-width: 76rem; }
.shop h1 { text-align: left; font-size: clamp(2.3rem, 5vw, 4rem); margin: .4em 0; }
.shop h2 { margin: .2em 0; }
.shop h3 { margin: .2em 0; line-height: 1.3; }
.shop button, .shop input, .shop select { font: inherit; }
.shop button { font-weight: 650; }
.shop button:disabled { opacity: .55; cursor: not-allowed; }
.shop :focus-visible { outline: 3px solid #287a86; outline-offset: 4px; }
.shop [hidden] { display: none !important; }
.shop-hero { display: grid; grid-template-columns: 1.4fr 1fr; gap: 2rem; align-items: center; padding: 2rem 3rem; border-radius: 24px; background: #f5e3cc; margin: 1rem 0 3rem; }
.shop-hero p { max-width: 34rem; }
.shop-hero figure { margin: 0; text-align: center; }
.shop-hero img { height: 310px; width: 100%; object-fit: contain; }
.shop-hero figcaption { font-size: .85rem; color: var(--text-muted); }
.eyebrow { text-transform: uppercase; letter-spacing: .13em; font-size: .75rem; font-weight: 750; color: var(--accent); }
.muted { color: var(--text-muted); font-size: .875rem; }
.shop-link { display: inline-block; color: var(--accent); font-weight: 700; padding: .6rem 0; }
.section-heading { display: flex; justify-content: space-between; gap: 1rem; align-items: center; margin-bottom: 1.5rem; }
.filters { display: flex; gap: .85rem; align-items: end; flex-wrap: wrap; border: 1px solid #e5d5c2; border-radius: 18px; background: #f7eee3; padding: 1.1rem; }
.shop label { display: grid; gap: .4rem; font-size: .875rem; }
.filters .search { flex: 1 1 15rem; }
.shop .check { display: flex; align-items: center; gap: .5rem; min-height: 44px; }
.shop input[type="checkbox"] { width: 1.15rem; height: 1.15rem; }
.shop .secondary { background: transparent; color: var(--accent); border: 1px solid #bca286; }
.shop .secondary:hover { background: #f2dfc9; }
/* Поля и переключатели фильтра сохраняют нативное управление с клавиатуры. */
.filters > label:not(.check) { color: #715744; font-size: .75rem; font-weight: 650; gap: .5rem; }
.filters input[type="search"], .filters select { height: 46px; border: 1px solid #d7c4ae; border-radius: 11px; background-color: #fffdf9; color: var(--text); font-size: .875rem; font-weight: 400; box-shadow: 0 2px 3px #593b2010; }
.filters input[type="search"] { width: 100%; padding-left: 2.6rem; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' fill='none' stroke='%238b6c52' stroke-width='1.7' stroke-linecap='round'%3E%3Ccircle cx='8.5' cy='8.5' r='5.5'/%3E%3Cpath d='m13 13 4 4'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: .85rem center; }
.filters select { appearance: none; padding: 0 2.4rem 0 .85rem; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='none' stroke='%238b6c52' stroke-width='1.7' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m4 6 4 4 4-4'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right .8rem center; }
.filters input[type="search"]::placeholder { color: #8a7767; }
.filters .check { position: relative; height: 46px; padding: 0 .85rem; gap: .55rem; border: 1px solid #d7c4ae; border-radius: 11px; background: #fffdf9; color: #715744; cursor: pointer; font-size: .8125rem; white-space: nowrap; }
.filters .check:hover { border-color: #a57a52; }
.filters .check:has(:checked) { background: #efe0cd; border-color: #a57a52; color: #713c18; }
.filters .check input { appearance: none; flex-shrink: 0; width: 18px; height: 18px; margin: 0; border: 1.5px solid #b39b81; border-radius: 5px; background: white; }
.filters .check input:checked { border-color: var(--accent); background: var(--accent) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m4 9 3 3 7-7'/%3E%3C/svg%3E") center / 16px; }
.filters button[type="reset"] { min-height: 46px; padding: .5rem .65rem; border-color: transparent; border-radius: 10px; font-size: .8125rem; font-weight: 600; color: #715744; }
@media (forced-colors: active) { .filters .check input { appearance: auto; } .filters select { appearance: auto; } }
.products { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1.4rem; }
.product { border-radius: 16px; background: var(--paper); overflow: hidden; border: 1px solid #e2d2c0; display: flex; flex-direction: column; }
.product-art { position: relative; background: #efe2cf; }
.product:nth-child(3n + 2) .product-art { background: #e5e8dc; }
.product:nth-child(3n) .product-art { background: #efe0d8; }
.product-art img { width: 100%; height: 220px; object-fit: contain; padding: 1rem; display: block; }
.product .favorite { position: absolute; top: .8rem; right: .8rem; width: 44px; height: 44px; padding: 0; background: var(--paper); font-size: 1.4rem; }
.product-body { padding: 1.2rem; display: flex; flex: 1; flex-direction: column; }
.product-body p { margin: .3rem 0 .7rem; }
.product-description { font-size: .9rem; }
.product h3 a { color: inherit; text-decoration: none; }
.product h3 a:hover { text-decoration: underline; text-underline-offset: .2em; }
#product-page > a { color: var(--accent); text-underline-offset: .25em; }
.product-detail { display: grid; grid-template-columns: 1.1fr 1fr; gap: 2.5rem; align-items: start; margin-top: 2rem; }
.detail-gallery { min-width: 0; }
.shop .gallery-zoom { display: block; width: 100%; padding: 1.5rem; border-radius: 20px; background: #efe2cf; cursor: zoom-in; }
.gallery-zoom img { display: block; width: 100%; height: auto; }
.detail-price { font-size: 2rem; font-weight: 750; }
.detail-actions { display: flex; flex-wrap: wrap; gap: .75rem; }
.detail-gallery dialog img { display: block; width: 100%; }
@media (max-width: 650px) { .product-detail { grid-template-columns: 1fr; gap: 1rem; } }
.product-bottom { display: flex; gap: .5rem; justify-content: space-between; align-items: center; margin-top: auto; }
.price { white-space: nowrap; font-size: 1.15rem; }
.product-bottom button { padding: .5rem .9rem; font-size: .85rem; }
.shop-note { margin-top: 3rem; padding: 2rem; border-block: 1px solid #d9c5af; }
.shop-note p { max-width: 45rem; }
.shop dialog { width: min(40rem, calc(100% - 1.5rem)); max-height: 90dvh; padding: 1.5rem; border: 1px solid #d9c5af; border-radius: 20px; background: var(--paper); color: var(--text); }
.shop dialog::backdrop { background: rgb(43 33 27 / 55%); }
.shop:has(dialog[open]) { overflow: hidden; }
.cart-row { display: grid; grid-template-columns: 1fr auto; gap: .5rem; padding: 1rem 0; border-bottom: 1px solid #d9c5af; }
.quantity { display: flex; gap: .6rem; align-items: center; }
.quantity button { min-width: 44px; min-height: 44px; padding: .3rem; }
.cart-row .remove { font-size: .8rem; padding: .4rem .7rem; }
.promo { display: flex; gap: .75rem; align-items: end; margin-top: 1.5rem; }
.promo label { min-width: 0; flex: 1; }
.totals div { display: flex; justify-content: space-between; gap: 1rem; margin: .5rem 0; }
.totals dd { margin: 0; }
.grand-total { font-weight: 750; font-size: 1.3rem; border-top: 1px solid #d9c5af; padding-top: .6rem; }
#order-form { display: grid; gap: .8rem; border-top: 1px solid #d9c5af; padding-top: 1rem; }
#order-form p { margin: 0; }
#clear-cart { margin-top: 1rem; }
.error { color: #a02222; }
.notice:not(:empty), .storage-warning:not(:empty) { position: fixed; bottom: 1rem; left: 50%; transform: translateX(-50%); z-index: 20; margin: 0; padding: .8rem 1.2rem; width: max-content; max-width: 90%; background: #2b211b; color: white; border-radius: 12px; box-shadow: 0 4px 20px #0002; }
.storage-warning:not(:empty) { bottom: 5rem; }
.skip { position: absolute; left: -9999px; }
.skip:focus { left: 1rem; top: 1rem; z-index: 30; background: white; padding: 1rem; }
@media (max-width: 850px) { .products { grid-template-columns: repeat(2, minmax(0, 1fr)); } .shop-hero { padding: 1.5rem; gap: 1rem; } }
@media (max-width: 540px) { .shop-hero { grid-template-columns: 1fr; } .shop-hero img { height: 220px; } .products { grid-template-columns: 1fr; } .filters > label { flex: 1 1 100%; } .section-heading { flex-wrap: wrap; } .cart-row { grid-template-columns: 1fr; } .shop dialog { padding: 1rem; } }
/* Цвет иллюстрации сохраняется, когда поиск меняет порядок карточек. */
.products [data-id="ball"] .product-art { background-color: #e5e8dc; }
.products [data-id="rope"] .product-art { background-color: #efe2cf; }
.products [data-id="duck"] .product-art { background-color: #efe0d8; }
Подсказки на полях показывают, где писать код. Нажмите «?», чтобы перейти к первой подсказке. Нажмите ещё раз, чтобы скрыть их все.
Нажмите «Запустить», чтобы увидеть результат.
js/shop.js
/*
Лавка Тони: программа магазина.
Разделы: товары, заказ, проверки и чек.
*/
console.log("Лавка Тони");
// Товары
const productName = "Мяч для прогулок";
const price = 450;
const isAvailable = true;
const isFavorite = false;
const description = "";
const ropeName = "Канат «Удав»";
const ropePrice = 490;
const ropeStock = 8;
// Заказ
const quantityText = "3";
const quantity = Number(quantityText);
const selectedProduct = null;
const promoCode = null;
let pickupPoint;
const pickupCost = 0;
const deliveryText = "150";
const savedDelivery = 0;
const delivery = savedDelivery ?? Number(deliveryText);
const savedName = "";
const customerName = savedName || "Гость";
const paid = 2000;
const hasCard = false;
const hasCash = true;
const isBlocked = false;
const isPaid = true;
const payOnPickup = true;
// Склад
const incoming = 5;
const packSize = 4;
let stock = 12;
stock += incoming;
stock -= quantity;
stock++;
const unpacked = stock % packSize;
// Чек заказа
function calcTotal(itemPrice, itemQuantity, itemDelivery = 150) {
if (itemQuantity <= 0) {
return 0;
}
return itemPrice * itemQuantity + itemDelivery;
}
const subtotal = price * quantity;
const total = calcTotal(price, quantity, delivery);
const change = paid - total;
function printReceipt() {
console.log(`Товары: ${subtotal}`);
console.log(`К оплате: ${total}`);
console.log(`Сдача: ${change}`);
}
console.log("Чек покупателю");
printReceipt();
console.log("Копия для склада");
printReceipt();
// Проверки заказа
const freeDeliveryFrom = 1000;
const selectedName = "Мяч для прогулок";
const hasEnough = stock >= quantity;
const hasFreeDelivery = subtotal >= freeDeliveryFrom;
const sameName = selectedName === productName;
const validQuantity = quantity > 0 && quantity <= stock;
const canPay = hasCard || hasCash;
const canOrder = validQuantity && canPay && !isBlocked;
let message = "";
if (isBlocked) {
message = "Заказ недоступен";
} else if (!hasEnough) {
message = "Недостаточно товара";
} else if (isPaid) {
message = "Передаём заказ в доставку";
} else {
message = "Ожидаем оплату";
}
// Подписи
const productCode = "B17";
const card = `${productName} — ${price} руб.`;
const badge = productName[0] + "-" + productCode;
// Признаки товара
const hasDescription = Boolean(description);
// Скидка на каждый мяч
const discountPerItem = 50;
const discountedTotal = (price - discountPerItem) * quantity + delivery;
const canCheckout = hasEnough && (isPaid || payOnPickup);
// Способ получения и наличие
const isPickup = delivery === 0;
const methodLabel = "Способ: " + (isPickup ? "Самовывоз" : "Доставка");
const stockLabel = isAvailable ? "В наличии" : "Закончился";
// Способ получения по коду из формы
const methodText = "1";
const methodCode = Number(methodText);
let methodName = "";
let methodCost = null;
switch (methodCode) {
case 1:
methodName = "Самовывоз";
methodCost = 0;
break;
case 2:
case 3:
methodName = "Доставка";
methodCost = 150;
break;
default:
methodName = "Неизвестный способ";
methodCost = null;
break;
}
// Упаковка заказа
const boxCapacity = 2;
let remaining = quantity;
let boxes = 0;
while (remaining > 0) {
if (remaining > boxCapacity) {
remaining -= boxCapacity;
} else {
remaining = 0;
}
boxes++;
}
// Подарки к заказам: Тони дарит мячик каждому чётному заказу дня
const lastOrder = 10;
const giftsEndAt = 8;
let giftCount = 0;
let giftSum = 0;
for (let orderNumber = 1; orderNumber <= lastOrder; orderNumber++) {
if (orderNumber === giftsEndAt) {
break;
}
if (orderNumber % 2 !== 0) {
continue;
}
giftSum += orderNumber;
giftCount++;
}
// Проверка calcTotal
console.log(calcTotal(ropePrice, 2));
console.log(calcTotal(price, 2, 0));
console.log(calcTotal(price, 0, 150));
// Данные первого товара
const ball = {
id: "ball",
name: productName,
price: price,
stock: stock,
priceLabel() {
return this.price + " ₽";
}
};
console.log(ball.priceLabel());
const rope = { id: "rope", name: ropeName, price: ropePrice, stock: ropeStock };
const ring = { id: "ring", name: "Кольцо «Апорт»", price: 450, stock: 0 };
const catalog = [ball, rope, ring];
console.log(catalog.length);
for (const product of catalog) {
console.log(product.name);
}
// Пробная цена для подарка
const gift = { id: rope.id, name: rope.name, price: rope.price };
gift.price = 0;
console.log(gift.price, rope.price);
function offerPrice(product) {
return product.offer?.price ?? product.price;
}
console.log(offerPrice(rope));
console.log(offerPrice({ price: rope.price, offer: { price: 0 } }));
function availableProducts(products) {
return products.filter(product => product.stock > 0);
}
console.log(availableProducts(catalog).map(product => product.name));
function findProduct(id) {
return catalog.find(product => product.id === id);
}
console.log(findProduct("rope")?.name ?? "Товар не найден");
console.log(findProduct("cat")?.name ?? "Товар не найден");
function countStock(products) {
return products.reduce((sum, product) => sum + product.stock, 0);
}
console.log(countStock(catalog));
function byPrice(products) {
return [...products].sort((first, second) => first.price - second.price);
}
console.log(byPrice(catalog).map(product => product.id));
console.log(catalog.map(product => product.id));
function searchProducts(products, query) {
const word = query.trim().toLowerCase();
return products.filter(product => product.name.toLowerCase().includes(word));
}
console.log(searchProducts(catalog, " КАНАТ ").map(product => product.name));
function checkEqual(label, actual, expected) {
if (actual === expected) {
console.log("Пройдено: " + label);
} else {
console.log("Ошибка: " + label, actual, expected);
}
}
checkEqual("пустой склад", countStock([]), 0);
checkEqual("поиск без регистра", searchProducts(catalog, " КаНаТ ")[0]?.id, "rope");
checkEqual("неизвестный код", findProduct("cat"), undefined);
const cartDialog = document.querySelector("#cart-dialog");
const openCart = document.querySelector("#open-cart");
const closeCart = document.querySelector("#close-cart");
openCart.addEventListener("click", () => cartDialog.showModal());
closeCart.addEventListener("click", () => cartDialog.close());
cartDialog.addEventListener("close", () => openCart.focus());
document.querySelector(".product h3").textContent = ball.name;
document.querySelector(".product .price").textContent = ball.priceLabel();
const cartItems = document.querySelector("#cart-items");
const cart = [];
const cartCount = document.querySelector("#cart-count");
function renderBallCart() {
cartCount.textContent = cart.length;
cartItems.textContent = cart.length ? findProduct(cart[cart.length - 1]).name + " × " + cart.length : "В корзине пока пусто. Тони советует начать с игрушки.";
}
function addBall() {
cart.push(ball.id);
renderBallCart();
}
document.querySelector(".product .add").addEventListener("click", addBall);
renderBallCart();
index.html
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Лавка Тони — учебный магазин игрушек и вещей для собак.">
<title>Лавка Тони</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/shop.css">
</head>
<body class="shop">
<a class="skip" href="#catalog">К товарам</a>
<main>
<section class="shop-hero" aria-labelledby="shop-title">
<div><p class="eyebrow">Маленькая лавка большого друга</p><h1 id="shop-title">Для игр, прогулок<br>и сладких снов.</h1>
<p>Привет, это Тони! Готовлю лавку игрушек и вещей для наших собачьих дел.</p>
<a class="shop-link" href="#catalog">Заглянуть в лавку ↓</a><p class="muted">Учебный магазин · без оплаты и настоящих заказов</p></div>
<figure><img src="assets/tony-toy.png" alt="Тони со своим любимым канатом" width="300" height="400"><figcaption>Главный по проверке игрушек</figcaption></figure>
</section>
<section id="catalog" aria-labelledby="catalog-title">
<div class="section-heading"><div><p class="eyebrow">Выбрано с лапой</p><h2 id="catalog-title">Лавка Тони</h2></div>
<button id="open-cart" type="button">Корзина · <span id="cart-count">0</span></button>
</div>
<p id="catalog-status" role="status">Первый товар в Лавке.</p>
<div id="products" class="products">
<article class="product" data-id="ball">
<div class="product-art"><img src="assets/ball.svg" alt="Мяч для прогулок" width="300" height="240"></div>
<div class="product-body">
<h3></h3>
<div class="product-bottom"><strong class="price"></strong>
<button class="add" type="button">В корзину</button>
</div>
</div>
</article>
</div>
</section>
</main>
<footer><p>© 2026 Тони и его хозяин · Сделано для любопытных</p></footer>
<dialog id="cart-dialog" aria-labelledby="cart-title">
<div class="section-heading">
<h2 id="cart-title">Твоя корзина</h2>
<button id="close-cart" type="button" class="secondary">Закрыть</button>
</div>
<div id="cart-items"></div>
</dialog>
<script src="js/shop.js"></script>
</body>
</html>
css/style.css
/* Все обычные правила проекта распределены по слоям. */
@layer base, layout, components;
@layer base {
/* Общие стили сайта Тони */
/* Ширина и высота включают внутренние отступы и рамку — у всех элементов и псевдоэлементов */
*,
*::before,
*::after {
box-sizing: border-box;
}
/* Палитра сайта в пользовательских свойствах: цвет меняется в одном месте */
:root {
--accent: saddlebrown; /* заголовки, меню, акценты */
--text: #2b211b; /* основной текст */
--text-muted: #6b5d52; /* подписи и второстепенный текст */
}
/* Шрифт заголовков Nunito (лицензия SIL Open Font License): кириллица и латиница в разных файлах */
@font-face {
font-family: "Nunito";
src: url("../assets/nunito-cyrillic-800-normal.woff2") format("woff2");
font-weight: 800;
font-display: swap; /* пока шрифт загружается, текст виден запасным шрифтом */
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: "Nunito";
src: url("../assets/nunito-latin-800-normal.woff2") format("woff2");
font-weight: 800;
font-display: swap;
unicode-range: U+0000-00FF, U+2000-206F, U+20AC, U+2122;
}
body {
background-color: linen;
color: var(--text); /* цвет для потомков без собственного значения */
font-size: 1.0625rem; /* 17px при настройке браузера по умолчанию */
font-family:
system-ui,
-apple-system,
"Segoe UI",
Roboto,
sans-serif; /* системный шрифт устройства */
line-height: 1.6; /* множитель: у каждого элемента интервал от его собственного размера шрифта */
margin: 0; /* убираем отступ браузера: шапка и подвал во всю ширину окна */
}
/* Поля основного содержимого: текст не прижимается к краям окна */
/* Изображения и видео не шире колонки, пропорции сохраняются */
img,
video {
max-width: 100%;
height: auto;
}
/* Фреймы, аудиоплеер и поля формы не выходят за колонку */
iframe,
audio,
input,
select,
textarea,
button {
max-width: 100%;
}
/* Разрешаем группе полей сужаться вместе с колонкой. */
fieldset {
min-width: 0;
}
/* Общий цвет заголовков — групповой селектор */
h1,
h2 {
color: var(--accent);
font-family: "Nunito", "Trebuchet MS", system-ui, sans-serif;
font-weight: 800;
line-height: 1.2; /* крупному тексту хватает меньшего интервала */
}
/* Размеры заголовков в rem — от размера шрифта корня, а не родителя */
h1 {
text-align: center;
font-size: 2.5rem;
}
h2 {
font-size: 1.75rem;
}
}
@layer layout {
main {
padding: 1.5rem 1rem;
max-width: 68rem; /* на широком экране строки не растягиваются на всё окно */
margin: 0 auto; /* колонка по центру */
}
}
@layer components {
/* Вводный блок главной страницы */
.intro {
background-color: hsl(30, 80%, 95%);
padding: 1.5rem; /* фон вокруг текста; заодно не выпускает margin заголовка за пределы блока */
border-radius: 16px; /* скругляется и фон, хотя рамки нет */
/* Лапка в правом нижнем углу; цвет фона выше остаётся запасным, если картинка не загрузится */
background-image: url("../assets/paw.svg");
background-repeat: no-repeat;
background-position: right 1rem bottom 1rem;
background-size: 4rem;
}
/* Разделы главной — светлые карточки на фоне страницы */
main > section {
background-color: var(--paper, #fffaf3);
border: 1px solid hsl(28, 30%, 82%);
border-radius: 16px;
padding: 1.5rem;
margin-top: 1.5rem;
}
/* Ширина вводных абзацев ограничена 60ch; количество букв в строке зависит от шрифта и текста */
.intro p {
max-width: 60ch;
}
/* Важное предупреждение во вводном блоке — темнее основного акцента */
.intro strong {
color: #6e3510;
}
/* Оглавление главной страницы — переносимый ряд «таблеток» на Flexbox */
.toc {
background-color: white;
border: 1px solid tan;
display: flex;
flex-wrap: wrap; /* «таблетки», которым не хватает места, переходят на новую строку */
gap: 0.5rem; /* промежутки между «таблетками» и между строками */
list-style: none;
padding: 0.75rem;
}
/* Подчёркивание ссылок чуть ниже букв: не задевает выносные элементы */
a {
text-underline-offset: 3px;
}
/* Тонкая линия отделяет шапку от страницы */
header {
border-bottom: 1px solid tan;
}
/* Меню в одну строку на Flexbox: пункты — флекс-элементы, промежутки задаёт gap */
nav ul {
margin: 0;
padding: 0.5rem 1rem;
display: flex;
gap: 0.5rem;
list-style: none;
}
/* Ссылка на запись стоит отдельно у правого края: автоматический отступ забирает свободное место */
nav li:last-child {
margin-left: auto;
}
/* Ссылки меню в шапке — селектор потомков */
nav a {
color: var(--accent);
text-decoration: none;
display: inline-block; /* у строчной ссылки вертикальный padding не раздвигает строку */
padding: 0.4rem 0.9rem;
border-radius: 999px; /* «таблетка»: радиус больше половины высоты */
}
/* Ссылки оглавления главной страницы */
.toc a {
color: var(--text-muted); /* тёплый серый: контраст 6.34:1 на белом фоне оглавления */
display: block; /* ссылка заполняет «таблетку» целиком */
padding: 0.25rem 0.75rem;
border: 1px solid tan;
border-radius: 999px;
text-decoration: none;
}
/* Фотографии со скруглёнными углами */
figure img {
border-radius: 8px;
}
figcaption {
color: var(--text-muted); /* тёплый серый: контраст 5.64:1 на фоне linen */
font-size: 0.95rem;
}
footer {
background-color: hsl(30, 50%, 90%);
text-align: center;
padding: 1rem;
}
/* Ссылка в подвале берёт цвет текста подвала */
footer a {
color: inherit;
}
/* Поля формы получают шрифт страницы вместо шрифта браузера */
input,
select,
textarea,
button {
font: inherit;
}
/* Ссылки темнеют при наведении указателя */
a:hover {
color: #5c2d0c;
}
/* Ссылки меню подчёркиваются при наведении и фокусе с клавиатуры */
nav a:hover,
nav a:focus-visible {
text-decoration: underline;
}
/* Заметная рамка фокуса у ссылок, полей и кнопок при работе с клавиатуры */
:focus-visible {
outline: 3px solid #1f6feb;
outline-offset: 3px;
}
/* Цитата из книги — шрифтом с засечками и курсивом */
blockquote {
font-family: Georgia, "Times New Roman", serif;
font-style: italic;
border-left: 4px solid tan; /* черта слева выделяет цитату */
padding-left: 1rem;
}
/* Подпись под цитатой — у правого края */
blockquote + figcaption {
text-align: right;
}
/* Строки формы на Flexbox: подпись — колонка постоянной ширины, поле занимает остаток строки,
а на узком экране переносится под подпись */
fieldset p {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem 1rem;
}
fieldset p label {
flex: 0 0 12rem; /* не растёт и не сжимается, исходная ширина 12rem */
}
fieldset p input,
fieldset p select,
fieldset p textarea {
flex: 1 1 12rem; /* растёт и сжимается от исходной ширины 12rem */
min-width: 0; /* поле может стать уже своего автоматического минимума */
}
/* Фотоальбом на Grid. Все правила альбома собраны во вложенный блок: & — сам .gallery */
.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr));
gap: 1rem;
list-style: none;
padding: 0;
/* Карточка — точка отсчёта для значка */
& li {
position: relative;
}
/* Карточка со значком выделена рамкой */
& li:has(.badge) {
outline: 3px solid tan;
outline-offset: 4px;
border-radius: 8px;
}
& figure {
margin: 0;
}
& img {
width: 100%; /* фото заполняет ширину своей ячейки */
}
}
/* Список команд на Grid: термин в первой колонке шириной по самому длинному термину, описание — во второй */
dl {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
gap: 0.5rem 1rem;
}
dt {
grid-column: 1;
font-weight: bold;
}
dd {
grid-column: 2;
overflow-wrap: anywhere; /* длинный перевод переносится внутри своей колонки */
margin: 0; /* браузерный отступ слева больше не нужен: колонку задаёт сетка */
}
/* Длинные слова и адреса переносятся, а не выходят за край узкого экрана */
body {
overflow-wrap: break-word;
}
/* Таблица режима дня на узком экране прокручивается в своей рамке, а не сжимается до нечитаемых колонок */
.table-wrap {
overflow-x: auto;
}
table {
width: 100%;
min-width: 28rem;
}
/* Подпись таблицы прокручивается вместе с ней: прижимаем её к началу, чтобы она была видна сразу */
caption {
text-align: left;
}
/* Широкий экран: в разделе «Моя любимая игрушка» фото справа, текст слева.
На узком экране правило не действует, и раздел остаётся одной колонкой. */
@media (width >= 48rem) {
.toy {
display: grid;
grid-template-columns: minmax(0, 1fr) 300px;
column-gap: 1.5rem;
}
.toy figure {
grid-column: 2;
grid-row: 1 / span 6; /* фото рядом со всеми абзацами раздела */
margin: 0;
}
.toy hr {
width: 100%;
}
}
/* Значок «Любимая» в правом верхнем углу карточки; из потока исключён, поэтому фото не сдвигается */
.badge {
position: absolute;
top: 0.5rem;
right: 0.5rem;
padding: 0.2rem 0.7rem;
border-radius: 999px;
background-color: var(--accent);
color: white;
font-size: 0.85rem;
font-weight: bold;
}
/* Шапка прилипает к верхнему краю окна. Фон нужен, чтобы под шапкой не просвечивал текст страницы */
header {
position: sticky;
top: 0;
z-index: 10; /* выше карточек альбома: они тоже позиционированы и записаны в HTML позже шапки */
background-color: linen;
}
/* Липкая шапка должна быть низкой: пункты меню не сжимаются и не переносятся на вторую строку,
а если им не хватает места, меню прокручивается внутри шапки */
nav ul {
overflow-x: auto;
}
nav li {
flex-shrink: 0;
}
/* Заголовок, к которому ведёт ссылка-якорь, не прячется под липкой шапкой.
В rem: при увеличении текста растут и шапка, и отступ */
[id] {
scroll-margin-top: 4.5rem;
}
/* Ссылка, которая открывается в новой вкладке, помечена стрелкой — посетитель знает, что страница не сменится */
a[target="_blank"]::after {
content: " ↗";
}
/* Ссылка на электронную почту — с конвертом */
a[href^="mailto:"]::before {
content: "✉ ";
}
/* Первая ссылка меню — «Главная» — подписана лапкой без изменения HTML */
nav li:first-child a::before {
content: "🐾 ";
}
/* Первый абзац вводного блока крупнее остальных. :first-child здесь не подойдёт — первым стоит заголовок h1 */
.intro p:first-of-type {
font-size: 1.2rem;
}
/* Список игрушек: вместо стандартного кружка — косточка */
.toy-list li::marker {
content: "🦴 ";
}
/* Номера шагов в нумерованных списках — в цвет заголовков и жирные; текст пунктов не меняется */
ol li::marker {
color: var(--accent);
font-weight: bold;
}
/* Таблица режима дня: соседние рамки объединяются в одну линию */
table {
border-collapse: collapse;
}
/* Ячейки с воздухом и линией снизу; текст — от левого края и сверху, даже если в соседней ячейке две строки */
th,
td {
padding: 0.6rem 0.8rem;
border-bottom: 1px solid tan;
text-align: left;
vertical-align: top;
}
/* Шапка таблицы — в цвет заголовков сайта */
thead th {
background-color: var(--accent);
color: white;
}
/* Чётные строки тела таблицы — на светлом фоне: глаз не теряет строку */
tbody tr:nth-child(even) {
background-color: hsl(30, 80%, 95%);
}
/* Отдельные рамки без промежутков позволяют скруглить крайние ячейки. Линия только снизу не удваивается. */
table {
border-collapse: separate;
border-spacing: 0;
}
thead th:first-child {
border-top-left-radius: 8px;
}
thead th:last-child {
border-top-right-radius: 8px;
}
/* Форма записи: текстовые поля, список и область текста в едином стиле */
input:not([type="radio"], [type="checkbox"]),
select,
textarea {
padding: 0.5rem 0.75rem;
border: 1px solid #8a7660;
border-radius: 8px;
background-color: white;
}
/* Поле «Ведёт прогулку» менять нельзя — фон показывает это */
input[readonly] {
background-color: hsl(30, 80%, 95%);
}
/* Отмеченные флажки и переключатели — в цвет сайта */
input[type="radio"],
input[type="checkbox"] {
accent-color: var(--accent);
}
/* Неверно заполненное поле — после того как посетитель с ним поработал */
input:user-invalid,
select:user-invalid,
textarea:user-invalid {
border-color: firebrick;
}
/* Группы полей — светлые блоки с тонкой рамкой вместо рельефной рамки браузера */
fieldset {
margin-bottom: 1rem;
border: 1px solid #8a7660;
border-radius: 16px;
}
/* Группа полей, в которой сейчас работает посетитель */
fieldset:focus-within {
border-color: var(--accent);
}
/* Кнопки-«таблетки»: основная залита цветом, второстепенная — только рамка */
button {
padding: 0.7rem 1.4rem;
border: 2px solid var(--accent);
border-radius: 999px;
background-color: var(--accent);
color: white;
font-weight: bold;
cursor: pointer;
}
button[type="reset"] {
background-color: transparent;
color: var(--accent);
}
/* Текст ошибок связан с полями через aria-describedby и не полагается только на цвет рамки. */
.field-error {
display: none;
flex-basis: 100%;
color: firebrick;
font-weight: bold;
}
input:user-invalid + .field-error {
display: block;
}
/* Фото любимой игрушки — как карточка-полароид: слегка повёрнуто вокруг нижнего края, будто прижато к столу */
.toy img {
transform: rotate(-2deg);
transform-origin: 50% 100%;
}
/* Под указателем фото выпрямляется и чуть увеличивается */
.toy img:hover {
transform: rotate(0deg) scale(1.03);
}
/* «Таблетка» оглавления под указателем и в фокусе приподнимается: отдельное свойство translate */
.toc a:hover,
.toc a:focus-visible {
translate: 0 -2px;
}
/* Нажатая кнопка будто вдавливается */
button:active {
transform: translateY(1px) scale(0.98);
}
/* Плавные изменения: переходим конкретные свойства, а не all */
.toy img {
transition: transform 0.4s ease-out; /* фото выпрямляется плавно */
}
.toc a {
transition: translate 0.2s ease-out;
}
button {
transition:
background-color 0.2s,
transform 0.1s;
}
/* Посетитель попросил систему уменьшить движение — изменения происходят сразу, без переходов */
@media (prefers-reduced-motion: reduce) {
.toy img,
.toc a,
button {
transition: none;
}
}
/* Лапка у «Главной» машет, когда на ссылку наводят указатель */
@keyframes wag {
0%,
100% {
rotate: 0deg;
}
25% {
rotate: -18deg;
}
75% {
rotate: 18deg;
}
}
nav li:first-child a::before {
display: inline-block; /* строчный псевдоэлемент не поворачивается */
transform-origin: 50% 80%; /* лапка качается от «запястья» */
}
nav li:first-child a:hover::before,
nav li:first-child a:focus-visible::before {
animation-name: wag;
animation-duration: 0.5s;
animation-timing-function: ease-in-out;
animation-iteration-count: 2; /* помахать дважды и остановиться */
}
/* Приветствие на главной плавно появляется снизу при загрузке страницы */
@keyframes rise {
from {
opacity: 0;
translate: 0 16px;
}
/* to не задан: конечный кадр — обычный вид элемента */
}
.intro > * {
/* both: до старта — первый кадр (элемент скрыт во время задержки), после — последний */
animation: rise 0.6s ease-out both;
}
/* Строки появляются друг за другом */
.intro > :nth-child(2) {
animation-delay: 0.1s;
}
.intro > :nth-child(3) {
animation-delay: 0.2s;
}
.intro > :nth-child(4) {
animation-delay: 0.3s;
}
/* Посетитель попросил уменьшить движение — анимаций нет, всё видно сразу */
@media (prefers-reduced-motion: reduce) {
.intro > *,
nav li:first-child a:hover::before,
nav li:first-child a:focus-visible::before {
animation: none;
}
}
button:hover,
button:focus-visible {
background-color: #6b3513;
}
button[type="reset"]:hover,
button[type="reset"]:focus-visible {
background-color: hsl(30, 70%, 90%);
}
/* Подписи читаются на тёмной подложке и без декоративной тени. */
.gallery figcaption {
padding: 0.5rem;
color: white;
background-color: hsl(25, 50%, 15%);
text-shadow: 0 1px 3px rgb(0 0 0 / 60%);
}
/* Два слоя: чёткая тень у края и широкая мягкая тень под карточкой. */
.gallery li {
background-color: #fffaf3;
border-radius: 12px;
box-shadow: 0 1px 2px rgb(0 0 0 / 8%), 0 8px 24px rgb(0 0 0 / 8%);
}
/* Внутренняя тень дополняет уже знакомое преобразование нажатой кнопки. */
button:active {
box-shadow: inset 0 2px 3px rgb(0 0 0 / 25%);
}
/* Фигура обрезает только своё содержимое, тень родительской карточки остаётся снаружи. */
.gallery figure {
position: relative;
overflow: hidden;
border-radius: 12px;
}
.gallery figcaption {
position: absolute;
inset: auto 0 0;
padding: 2.5rem 0.5rem 0.5rem;
}
/* Запасная однотонная подложка остаётся в прежнем правиле; градиент подключается условно. */
@supports (background-image: linear-gradient(black, white)) {
.gallery figcaption {
background-color: transparent;
background-image: linear-gradient(
to top,
rgb(57 35 19 / 95%) 0,
rgb(57 35 19 / 95%) calc(100% - 2rem),
rgb(57 35 19 / 0%) 100%
);
}
}
/* Лапа остаётся верхним слоем; подсветка — под ней, над однотонным фоном. */
@supports (background-image: radial-gradient(white, transparent)) {
.intro {
background-image:
url("../assets/paw.svg"),
radial-gradient(ellipse at 80% 20%, rgb(255 196 110 / 45%), rgb(255 196 110 / 0%) 65%);
background-size: 4rem, auto;
background-position: right 1rem bottom 1rem, center;
background-repeat: no-repeat;
}
}
}
css/shop.css
.shop { --paper: #fffaf3; }
.shop main { max-width: 76rem; }
.shop h1 { text-align: left; font-size: clamp(2.3rem, 5vw, 4rem); margin: .4em 0; }
.shop h2 { margin: .2em 0; }
.shop h3 { margin: .2em 0; line-height: 1.3; }
.shop button, .shop input, .shop select { font: inherit; }
.shop button { font-weight: 650; }
.shop button:disabled { opacity: .55; cursor: not-allowed; }
.shop :focus-visible { outline: 3px solid #287a86; outline-offset: 4px; }
.shop [hidden] { display: none !important; }
.shop-hero { display: grid; grid-template-columns: 1.4fr 1fr; gap: 2rem; align-items: center; padding: 2rem 3rem; border-radius: 24px; background: #f5e3cc; margin: 1rem 0 3rem; }
.shop-hero p { max-width: 34rem; }
.shop-hero figure { margin: 0; text-align: center; }
.shop-hero img { height: 310px; width: 100%; object-fit: contain; }
.shop-hero figcaption { font-size: .85rem; color: var(--text-muted); }
.eyebrow { text-transform: uppercase; letter-spacing: .13em; font-size: .75rem; font-weight: 750; color: var(--accent); }
.muted { color: var(--text-muted); font-size: .875rem; }
.shop-link { display: inline-block; color: var(--accent); font-weight: 700; padding: .6rem 0; }
.section-heading { display: flex; justify-content: space-between; gap: 1rem; align-items: center; margin-bottom: 1.5rem; }
.filters { display: flex; gap: .85rem; align-items: end; flex-wrap: wrap; border: 1px solid #e5d5c2; border-radius: 18px; background: #f7eee3; padding: 1.1rem; }
.shop label { display: grid; gap: .4rem; font-size: .875rem; }
.filters .search { flex: 1 1 15rem; }
.shop .check { display: flex; align-items: center; gap: .5rem; min-height: 44px; }
.shop input[type="checkbox"] { width: 1.15rem; height: 1.15rem; }
.shop .secondary { background: transparent; color: var(--accent); border: 1px solid #bca286; }
.shop .secondary:hover { background: #f2dfc9; }
/* Поля и переключатели фильтра сохраняют нативное управление с клавиатуры. */
.filters > label:not(.check) { color: #715744; font-size: .75rem; font-weight: 650; gap: .5rem; }
.filters input[type="search"], .filters select { height: 46px; border: 1px solid #d7c4ae; border-radius: 11px; background-color: #fffdf9; color: var(--text); font-size: .875rem; font-weight: 400; box-shadow: 0 2px 3px #593b2010; }
.filters input[type="search"] { width: 100%; padding-left: 2.6rem; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' fill='none' stroke='%238b6c52' stroke-width='1.7' stroke-linecap='round'%3E%3Ccircle cx='8.5' cy='8.5' r='5.5'/%3E%3Cpath d='m13 13 4 4'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: .85rem center; }
.filters select { appearance: none; padding: 0 2.4rem 0 .85rem; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='none' stroke='%238b6c52' stroke-width='1.7' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m4 6 4 4 4-4'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right .8rem center; }
.filters input[type="search"]::placeholder { color: #8a7767; }
.filters .check { position: relative; height: 46px; padding: 0 .85rem; gap: .55rem; border: 1px solid #d7c4ae; border-radius: 11px; background: #fffdf9; color: #715744; cursor: pointer; font-size: .8125rem; white-space: nowrap; }
.filters .check:hover { border-color: #a57a52; }
.filters .check:has(:checked) { background: #efe0cd; border-color: #a57a52; color: #713c18; }
.filters .check input { appearance: none; flex-shrink: 0; width: 18px; height: 18px; margin: 0; border: 1.5px solid #b39b81; border-radius: 5px; background: white; }
.filters .check input:checked { border-color: var(--accent); background: var(--accent) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m4 9 3 3 7-7'/%3E%3C/svg%3E") center / 16px; }
.filters button[type="reset"] { min-height: 46px; padding: .5rem .65rem; border-color: transparent; border-radius: 10px; font-size: .8125rem; font-weight: 600; color: #715744; }
@media (forced-colors: active) { .filters .check input { appearance: auto; } .filters select { appearance: auto; } }
.products { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1.4rem; }
.product { border-radius: 16px; background: var(--paper); overflow: hidden; border: 1px solid #e2d2c0; display: flex; flex-direction: column; }
.product-art { position: relative; background: #efe2cf; }
.product:nth-child(3n + 2) .product-art { background: #e5e8dc; }
.product:nth-child(3n) .product-art { background: #efe0d8; }
.product-art img { width: 100%; height: 220px; object-fit: contain; padding: 1rem; display: block; }
.product .favorite { position: absolute; top: .8rem; right: .8rem; width: 44px; height: 44px; padding: 0; background: var(--paper); font-size: 1.4rem; }
.product-body { padding: 1.2rem; display: flex; flex: 1; flex-direction: column; }
.product-body p { margin: .3rem 0 .7rem; }
.product-description { font-size: .9rem; }
.product h3 a { color: inherit; text-decoration: none; }
.product h3 a:hover { text-decoration: underline; text-underline-offset: .2em; }
#product-page > a { color: var(--accent); text-underline-offset: .25em; }
.product-detail { display: grid; grid-template-columns: 1.1fr 1fr; gap: 2.5rem; align-items: start; margin-top: 2rem; }
.detail-gallery { min-width: 0; }
.shop .gallery-zoom { display: block; width: 100%; padding: 1.5rem; border-radius: 20px; background: #efe2cf; cursor: zoom-in; }
.gallery-zoom img { display: block; width: 100%; height: auto; }
.detail-price { font-size: 2rem; font-weight: 750; }
.detail-actions { display: flex; flex-wrap: wrap; gap: .75rem; }
.detail-gallery dialog img { display: block; width: 100%; }
@media (max-width: 650px) { .product-detail { grid-template-columns: 1fr; gap: 1rem; } }
.product-bottom { display: flex; gap: .5rem; justify-content: space-between; align-items: center; margin-top: auto; }
.price { white-space: nowrap; font-size: 1.15rem; }
.product-bottom button { padding: .5rem .9rem; font-size: .85rem; }
.shop-note { margin-top: 3rem; padding: 2rem; border-block: 1px solid #d9c5af; }
.shop-note p { max-width: 45rem; }
.shop dialog { width: min(40rem, calc(100% - 1.5rem)); max-height: 90dvh; padding: 1.5rem; border: 1px solid #d9c5af; border-radius: 20px; background: var(--paper); color: var(--text); }
.shop dialog::backdrop { background: rgb(43 33 27 / 55%); }
.shop:has(dialog[open]) { overflow: hidden; }
.cart-row { display: grid; grid-template-columns: 1fr auto; gap: .5rem; padding: 1rem 0; border-bottom: 1px solid #d9c5af; }
.quantity { display: flex; gap: .6rem; align-items: center; }
.quantity button { min-width: 44px; min-height: 44px; padding: .3rem; }
.cart-row .remove { font-size: .8rem; padding: .4rem .7rem; }
.promo { display: flex; gap: .75rem; align-items: end; margin-top: 1.5rem; }
.promo label { min-width: 0; flex: 1; }
.totals div { display: flex; justify-content: space-between; gap: 1rem; margin: .5rem 0; }
.totals dd { margin: 0; }
.grand-total { font-weight: 750; font-size: 1.3rem; border-top: 1px solid #d9c5af; padding-top: .6rem; }
#order-form { display: grid; gap: .8rem; border-top: 1px solid #d9c5af; padding-top: 1rem; }
#order-form p { margin: 0; }
#clear-cart { margin-top: 1rem; }
.error { color: #a02222; }
.notice:not(:empty), .storage-warning:not(:empty) { position: fixed; bottom: 1rem; left: 50%; transform: translateX(-50%); z-index: 20; margin: 0; padding: .8rem 1.2rem; width: max-content; max-width: 90%; background: #2b211b; color: white; border-radius: 12px; box-shadow: 0 4px 20px #0002; }
.storage-warning:not(:empty) { bottom: 5rem; }
.skip { position: absolute; left: -9999px; }
.skip:focus { left: 1rem; top: 1rem; z-index: 30; background: white; padding: 1rem; }
@media (max-width: 850px) { .products { grid-template-columns: repeat(2, minmax(0, 1fr)); } .shop-hero { padding: 1.5rem; gap: 1rem; } }
@media (max-width: 540px) { .shop-hero { grid-template-columns: 1fr; } .shop-hero img { height: 220px; } .products { grid-template-columns: 1fr; } .filters > label { flex: 1 1 100%; } .section-heading { flex-wrap: wrap; } .cart-row { grid-template-columns: 1fr; } .shop dialog { padding: 1rem; } }
/* Цвет иллюстрации сохраняется, когда поиск меняет порядок карточек. */
.products [data-id="ball"] .product-art { background-color: #e5e8dc; }
.products [data-id="rope"] .product-art { background-color: #efe2cf; }
.products [data-id="duck"] .product-art { background-color: #efe0d8; }
- Файл с правками
- Добавлено
Точка на вкладке отмечает файл с правками. Зелёным выделены добавленные фрагменты кода.
Изменён файл index.html
Удаленострока 44
<div id="cart-items">В корзине пока пусто. Тони советует начать с игрушки.</div>Добавленострока 44
<div id="cart-items"></div>Изменён файл js/shop.js
Добавленострока 242
const cartItems = document.querySelector("#cart-items");Удаленостроки 244–245
cartCount.textContent = cart.length;
const cartItems = document.querySelector("#cart-items");Добавленостроки 246–250
function renderBallCart() {
cartCount.textContent = cart.length;
cartItems.textContent = cart.length ? findProduct(cart[cart.length - 1]).name + " × " + cart.length : "В корзине пока пусто. Тони советует начать с игрушки.";
}
Удаленостроки 249–250
cartCount.textContent = cart.length;
cartItems.textContent = findProduct(cart[cart.length - 1]).name + " × " + cart.length;Добавленострока 253
renderBallCart();Добавленостроки 257–258
renderBallCart();Нажмите «Запустить», чтобы увидеть результат.
Задание. Покажите количество в корзине
На кнопке «Корзина · 0» число хранится в отдельном span с идентификатором cart-count. Количество задано в первой строке скрипта.
- Запустите код и посмотрите строку «Счётчик найден» в консоли. Исправьте селектор, чтобы найти счётчик по его идентификатору.
- Внутри проверки запишите
quantityвcount.textContent.
Ожидаемый результат. После запуска кнопка покажет «Корзина · 2», а консоль — «Число на кнопке: 2».
Поставьте quantity = 0 и запустите код ещё раз. На кнопке появится «Корзина · 0». Если убрать span, в консоли появится «Счётчик найден: false», и программа завершится без ошибки.
Проверьте счётчик
Условие задания
script.js
const quantity = 2;
const count = document.querySelector(".cart-count");
console.log("Счётчик найден:", count !== null);
if (count !== null) {
// Запишите количество в счётчик.
console.log("Число на кнопке:", count.textContent);
}
index.html
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Покажите количество в корзине</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id="open-cart" type="button">Корзина · <span id="cart-count">0</span></button>
<dialog id="cart-dialog" aria-labelledby="cart-title">
<h2 id="cart-title">Твоя корзина</h2>
<button id="close-cart" class="secondary" type="button">Закрыть</button>
<div id="cart-items"></div>
</dialog>
<script src="script.js"></script>
<script src="preview.js"></script>
</body>
</html>
preview.js
document.querySelector("#cart-items").textContent = quantity > 0
? "Мяч для прогулок × " + quantity
: "В корзине пока пусто. Тони советует начать с игрушки.";
const dialog = document.querySelector("#cart-dialog");
const openCart = document.querySelector("#open-cart");
const closeCart = document.querySelector("#close-cart");
openCart.addEventListener("click", () => dialog.showModal());
closeCart.addEventListener("click", () => dialog.close());
dialog.addEventListener("close", () => openCart.focus());
style.css
body {
margin: 1rem;
color: #2b211b;
background: #fffaf3;
font: 1rem/1.5 system-ui, sans-serif;
overflow-wrap: anywhere;
}
button {
padding: .7rem 1.4rem;
border: 2px solid saddlebrown;
border-radius: 999px;
background: saddlebrown;
color: white;
font: inherit;
font-weight: 650;
cursor: pointer;
}
button:focus-visible {
outline: 3px solid #287a86;
outline-offset: 4px;
}
dialog {
box-sizing: border-box;
width: min(30rem, calc(100% - 1.5rem));
padding: 1rem;
border: 1px solid #d9c5af;
border-radius: 20px;
color: inherit;
background: #fffaf3;
}
dialog::backdrop {
background: rgb(43 33 27 / 55%);
}
dialog h2 {
margin-top: 0;
}
.secondary {
border: 1px solid #bca286;
background: transparent;
color: saddlebrown;
}
#cart-items {
margin-top: 1rem;
}
Нажмите «Запустить», чтобы увидеть результат.
Задание. Корзина перед оформлением
Покупатель взял два мяча по 450 ₽. Обновите счётчик на кнопке «Корзина» и стоимость товаров внутри окна.
- Внутри готовой проверки найденных элементов рассчитайте
totalкак произведениеpriceиquantity. - Запишите количество в
count.textContent. Вitemsпокажите «Мяч для прогулок × 2», подставивquantity. При нуле верните исходную подсказку о пустой корзине. - Запишите сумму в
subtotal.textContent. Для вывода рублей используйтеtotal.toLocaleString("ru-RU", { style: "currency", currency: "RUB" }). С помощьюclassList.toggleдобавьте блокуtotalsклассis-readyтолько приquantity > 0. CSS покажет строку «Товары» при наличии этого класса.
Ожидаемый результат
- После запуска в консоли видны число 2 и сумма 900,00 ₽. Нажмите «Корзина · 2» и сверьте их с количеством мячей и строкой «Товары» в окне.
- При
quantity = 0кнопка показывает «Корзина · 0». В окне остаётся подсказка, строка «Товары» скрыта, а в консоли сумма равна 0,00 ₽. - При изменении цены сумма тоже должна пересчитываться.
Выполните задание
Условие задания
main.js
const price = 450;
const quantity = 2;
const count = document.querySelector("#cart-count");
const items = document.querySelector("#cart-items");
const totals = document.querySelector(".totals");
const subtotal = document.querySelector("#subtotal");
if (count !== null && items !== null && totals !== null && subtotal !== null) {
// Обновите счётчик, содержимое корзины, стоимость товаров и класс блока .totals.
console.log("Число на кнопке:", count.textContent);
console.log("Стоимость товаров:", subtotal.textContent);
}
index.html
<main>
<button id="open-cart" type="button">Корзина · <span id="cart-count">0</span></button>
<dialog id="cart-dialog" aria-labelledby="cart-title">
<h2 id="cart-title">Твоя корзина</h2>
<button id="close-cart" class="secondary" type="button">Закрыть</button>
<div id="cart-items">В корзине пока пусто. Тони советует начать с игрушки.</div>
<dl class="totals">
<div><dt>Товары</dt><dd id="subtotal">0,00 ₽</dd></div>
</dl>
</dialog>
</main>
style.css
body {
margin: 1rem;
color: #2b211b;
background: #fffaf3;
font: 1rem/1.5 system-ui, sans-serif;
overflow-wrap: anywhere;
}
button {
padding: .7rem 1.4rem;
border: 2px solid saddlebrown;
border-radius: 999px;
background: saddlebrown;
color: white;
font: inherit;
font-weight: 650;
cursor: pointer;
}
button:focus-visible {
outline: 3px solid #287a86;
outline-offset: 4px;
}
dialog {
box-sizing: border-box;
width: min(30rem, calc(100% - 1.5rem));
padding: 1rem;
border: 1px solid #d9c5af;
border-radius: 20px;
color: inherit;
background: #fffaf3;
}
dialog::backdrop {
background: rgb(43 33 27 / 55%);
}
dialog h2 {
margin-top: 0;
}
.secondary {
border: 1px solid #bca286;
background: transparent;
color: saddlebrown;
}
#cart-items {
margin-top: 1rem;
}
.totals {
display: none;
}
.totals.is-ready {
display: block;
}
.totals div {
display: flex;
justify-content: space-between;
}
preview.js
const dialog = document.querySelector("#cart-dialog");
const openCart = document.querySelector("#open-cart");
const closeCart = document.querySelector("#close-cart");
openCart.addEventListener("click", () => dialog.showModal());
closeCart.addEventListener("click", () => dialog.close());
dialog.addEventListener("close", () => openCart.focus());
Нажмите «Запустить», чтобы увидеть результат.
Подсказка
Начните с const total = price * quantity;.
Составьте подпись мяча через +. Для строки «Товары» используйте totals.classList.toggle("is-ready", quantity > 0).
Забегая вперёд Как подключить скрипт в head
Если подключить main.js в head обычным тегом <script src="main.js"></script>,
браузер выполнит его до того, как дойдёт до разметки карточек. Тогда document.querySelector(".product") вернёт null.
Чтобы оставить скрипт в head и дождаться карточек, добавьте атрибут
defer.
При записи <script src="main.js" defer></script> браузер загружает файл параллельно с чтением HTML, а запускает его после разбора всей разметки.
У обычного встроенного скрипта без src атрибут defer не действует.
С атрибутом async
браузер тоже загружает файл параллельно, но запускает его, как только тот готов. К этому моменту карточек в DOM может ещё не быть.
Позже в этом учебнике, в уроке «Скрипты и готовность страницы»,
мы сравним defer, async и модули и проверим, как задержка загрузки влияет на порядок выполнения скриптов.