diff --git a/docs/1.getting-started/4.styling.md b/docs/1.getting-started/4.styling.md index 455253f5d5a3..24ff83389813 100644 --- a/docs/1.getting-started/4.styling.md +++ b/docs/1.getting-started/4.styling.md @@ -1,27 +1,27 @@ --- -title: 'Styling' -description: 'Learn how to style your Nuxt application.' +title: 'Стилизация' +description: 'Узнайте, как стилизовать Nuxt-приложение.' navigation.icon: i-ph-palette-duotone --- -Nuxt is highly flexible when it comes to styling. Write your own styles, or reference local and external stylesheets. -You can use CSS preprocessors, CSS frameworks, UI libraries and Nuxt modules to style your application. +Nuxt очень гибок в плане стилизации. Пишите собственные стили или ссылайтесь на локальные и внешние таблицы стилей. +Вы можете использовать препроцессоры CSS, CSS-фреймворки, UI-библиотеки и модули Nuxt для стилизации приложения. -## Local Stylesheets +## Локальные таблицы стилей {#local-stylesheets} -If you're writing local stylesheets, the natural place to put them is the [`assets/` directory](/docs/guide/directory-structure/assets). +Если вы пишете локальные таблицы стилей, стандартным местом для их размещения является [директория `assets/`](/docs/guide/directory-structure/assets). -### Importing Within Components +### Импорт внутри компонентов {#importing-within-components} -You can import stylesheets in your pages, layouts and components directly. -You can use a javascript import, or a css [`@import` statement](https://developer.mozilla.org/en-US/docs/Web/CSS/@import). +Вы можете импортировать таблицы стилей напрямую в свои страницы, лейауты и компоненты. +Вы можете использовать javascript-импорт или [css-выражение `@import`](https://developer.mozilla.org/en-US/docs/Web/CSS/@import). ```vue [pages/index.vue] @@ -31,13 +31,13 @@ import('~/assets/css/first.css') ``` ::tip -The stylesheets will be inlined in the HTML rendered by Nuxt. +Таблицы стилей будут встроены в HTML-код, отрисованный Nuxt. :: -### The CSS Property +### Свойство CSS {#the-css-property} -You can also use the `css` property in the Nuxt configuration. -The natural place for your stylesheets is the [`assets/` directory](/docs/guide/directory-structure/assets). You can then reference its path and Nuxt will include it to all the pages of your application. +Вы также можете использовать свойство `css` в конфигурации Nuxt. +Стандартным местом для ваших таблиц стилей является [директория `assets/`](/docs/guide/directory-structure/assets). Вы можете указать путь к файлу стилей, и Nuxt включит его во все страницы приложения. ```ts [nuxt.config.ts] export default defineNuxtConfig({ @@ -46,12 +46,12 @@ export default defineNuxtConfig({ ``` ::tip -The stylesheets will be inlined in the HTML rendered by Nuxt, injected globally and present in all pages. +Таблицы стилей будут встроены в HTML-код, отрисованный Nuxt, внедрены глобально и представлены на всех страницах. :: -### Working With Fonts +### Работа со шрифтами {#working-with-fonts} -Place your local fonts files in your `~/public/` directory, for example in `~/public/fonts`. You can then reference them in your stylesheets using `url()`. +Поместите локальные файлы шрифтов в директорию `~/public/`, например, в `~/public/fonts`. Вы можете ссылаться на них в своих таблицах стилей с помощью `url()`. ```css [assets/css/main.css] @font-face { @@ -63,7 +63,7 @@ Place your local fonts files in your `~/public/` directory, for example in `~/pu } ``` -Then reference your fonts by name in your stylesheets, pages or components: +После этого, ссылайтесь на шрифты по имени в таблицах стилей, на страницах или в компонентах: ```vue ``` -### Stylesheets Distributed Through NPM +### Таблицы стилей, распространяемые через NPM {#stylesheets-distributed-through-npm} -You can also reference stylesheets that are distributed through npm. Let's use the popular `animate.css` library as an example. +Вы также можете ссылаться на таблицы стилей, распространяемые через npm. Давайте в качестве примера воспользуемся популярной библиотекой `animate.css`. ```bash [Terminal] npm install animate.css ``` -Then you can reference it directly in your pages, layouts and components: +После этого вы можете ссылаться на стили напрямую в своих страницах, лейаутах и ​​компонентах: ```vue [app.vue] ``` -### Scoped Styles +### Cтили с ограниченной областью видимости {#scoped-styles} -The scoped attribute allows you to style components in isolation. The styles declared with this attribute will only apply to this component. +Атрибут scoped позволяет вам стилизовать компоненты изолированно. Стили, объявленные с этим атрибутом, будут применяться только к этому компоненту. ```vue ``` -### CSS Modules +### CSS-модули {#css-modules} -You can use [CSS Modules](https://github.com/css-modules/css-modules) with the module attribute. Access it with the injected `$style` variable. +Вы можете использовать [CSS-модули](https://github.com/css-modules/css-modules) с атрибутом module. Доступ к модулю осуществляется с помощью внедренной переменной `$style`. ```vue ``` -### Preprocessors Support +### Поддержка препроцессоров {#preprocessors-support} -SFC style blocks support preprocessors syntax. Vite come with built-in support for .scss, .sass, .less, .styl and .stylus files without configuration. You just need to install them first, and they will be available directly in SFC with the lang attribute. +Блоки стилей SFC поддерживают синтаксис препроцессоров. Vite поставляется со встроенной поддержкой файлов .scss, .sass, .less, .styl и .stylus без конфигурации. Вам просто нужно установить их, и они будут доступны непосредственно в SFC с атрибутом lang. ::code-group ```vue [SCSS] ``` ```vue [Sass] ``` ```vue [LESS] ``` ```vue [Stylus] ``` :: -You can refer to the [Vite CSS docs](https://vitejs.dev/guide/features.html#css) and the [@vitejs/plugin-vue docs](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue). -For webpack users, refer to the [vue loader docs](https://vue-loader.vuejs.org). +Вы можете обратиться к [документации Vite CSS](https://vitejs.dev/guide/features.html#css) и [документации @vitejs/plugin-vue](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue). +Для пользователей webpack обратитесь к [документации по загрузчику Vue](https://vue-loader.vuejs.org). -## Using PostCSS +## Использование PostCSS {#using-postcss} -Nuxt comes with postcss built-in. You can configure it in your `nuxt.config` file. +Nuxt поставляется со встроенным postcss. Вы можете настроить его в файле `nuxt.config`. ```ts [nuxt.config.ts] export default defineNuxtConfig({ @@ -418,30 +418,30 @@ export default defineNuxtConfig({ }) ``` -For proper syntax highlighting in SFC, you can use the postcss lang attribute. +Для правильной подсветки синтаксиса в SFC можно использовать атрибут lang со значением postcss. ```vue ``` -By default, Nuxt comes with the following plugins already pre-configured: +По умолчанию Nuxt поставляется со следующими предварительно настроенными плагинами: -- [postcss-import](https://github.com/postcss/postcss-import): Improves the `@import` rule -- [postcss-url](https://github.com/postcss/postcss-url): Transforms `url()` statements -- [autoprefixer](https://github.com/postcss/autoprefixer): Automatically adds vendor prefixes -- [cssnano](https://cssnano.github.io/cssnano): Minification and purge +- [postcss-import](https://github.com/postcss/postcss-import): Улучшает правило `@import` +- [postcss-url](https://github.com/postcss/postcss-url): Преобразует выражения `url()` +- [autoprefixer](https://github.com/postcss/autoprefixer): Автоматически добавляет вендорные префиксы +- [cssnano](https://cssnano.github.io/cssnano): Минифицирует и очищает -## Leveraging Layouts For Multiple Styles +## Использование лейаутов для нескольких стилей {#leveraging-layouts-for-multiple-styles} -If you need to style different parts of your application completely differently, you can use layouts. -Use different styles for different layouts. +Если нужно стилизовать разные части приложения совершенно по-разному, вы можете использовать лейауты. +Используйте разные стили для разных лейаутов. ```vue @@ -455,70 +455,69 @@ Use different styles for different layouts. :read-more{to="/docs/guide/directory-structure/layouts"} -## Third Party Libraries And Modules +## Сторонние библиотеки и модули {#third-party-libraries-and-modules} -Nuxt isn't opinionated when it comes to styling and provides you with a wide variety of options. You can use any styling tool that you want, such as popular libraries like [UnoCSS](https://unocss.dev) or [Tailwind CSS](https://tailwindcss.com). +Nuxt не отличается категоричностью в вопросе стилизации, и предоставляет вам широкий спектр опций. Вы можете использовать любой инструмент для стилизации, который вам нужен, например, популярные библиотеки, такие как [UnoCSS](https://unocss.dev) или [Tailwind CSS](https://tailwindcss.com). -The community and the Nuxt team have developed plenty of Nuxt modules to make the integration easier. -You can discover them on the [modules section](/modules) of the website. -Here are a few modules to help you get started: +Сообщество и команда Nuxt разработали множество модулей, которые упрощают интеграцию. +Вы можете ознакомиться с ними в разделе [модули](/modules) веб-сайта. +Вот несколько модулей, которые помогут вам начать работу: -- [UnoCSS](/modules/unocss): Instant on-demand atomic CSS engine -- [Tailwind CSS](/modules/tailwindcss): Utility-first CSS framework -- [Fontaine](https://github.com/nuxt-modules/fontaine): Font metric fallback -- [Pinceau](https://github.com/Tahul/pinceau): Adaptable styling framework -- [Nuxt UI](https://ui.nuxt.com): A UI Library for Modern Web Apps -- [Panda CSS](https://panda-css.com/docs/installation/nuxt): CSS-in-JS engine that generates atomic CSS at build time +- [UnoCSS](/modules/unocss): Атомарный CSS-движок +- [Tailwind CSS](/modules/tailwindcss): CSS-фреймворк, основанный на утилитах +- [Fontaine](https://github.com/nuxt-modules/fontaine): реализация fallback-метрики шрифтов +- [Pinceau](https://github.com/Tahul/pinceau): Адаптивный фреймворк для стилизации +- [Nuxt UI](https://ui.nuxt.com): Библиотека пользовательского интерфейса для современных веб-приложений +- [Panda CSS](https://panda-css.com/docs/installation/nuxt): движок CSS-in-JS, который генерирует атомарный CSS во время сборки -Nuxt modules provide you with a good developer experience out of the box, but remember that if your favorite tool doesn't have a module, it doesn't mean that you can't use it with Nuxt! You can configure it yourself for your own project. Depending on the tool, you might need to use a [Nuxt plugin](/docs/guide/directory-structure/plugins) and/or [make your own module](/docs/guide/going-further/modules). Share them with the [community](/modules) if you do! +Модули Nuxt предоставляют вам хороший опыт разработки из коробки, но помните, что если ваш любимый инструмент не имеет модуля, это не значит, что вы не можете использовать его с Nuxt! Вы можете настроить его самостоятельно для своего проекта. В зависимости от инструмента вам может потребоваться использовать [плагин Nuxt](/docs/guide/directory-structure/plugins) и/или [создать свой собственный модуль](/docs/guide/going-further/modules). Поделитесь ими с [сообществом](/modules), если вы это сделаете! -### Easily Load Webfonts +### Простая загрузка веб-шрифтов {#easily-load-webfonts} -You can use [the Nuxt Google Fonts module](https://github.com/nuxt-modules/google-fonts) to load Google Fonts. +Вы можете использовать [модуль Nuxt Google Fonts](https://github.com/nuxt-modules/google-fonts) для загрузки Google Fonts. -If you are using [UnoCSS](https://unocss.dev/integrations/nuxt), note that it comes with a [web fonts presets](https://unocss.dev/presets/web-fonts) to conveniently load fonts from common providers, including Google Fonts and more. +Если вы используете [UnoCSS](https://unocss.dev/integrations/nuxt), обратите внимание, что он поставляется с [предустановками веб-шрифтов](https://unocss.dev/presets/web-fonts) для удобной загрузки шрифтов от распространенных поставщиков, включая Google Fonts и другие. -## Advanced +## Продвинутый уровень {#advanced} -### Transitions +### Переходы {#transitions} -Nuxt comes with the same `` element that Vue has, and also has support for the experimental [View Transitions API](/docs/getting-started/transitions#view-transitions-api-experimental). +Nuxt поставляется с тем же компонентом ``, что и Vue, а также поддерживает экспериментальный [View Transitions API](/docs/getting-started/transitions#view-transitions-api-experimental). :read-more{to="/docs/getting-started/transitions"} -### Font Advanced Optimization +### Продвинутая оптимизация шрифтов {#font-advanced-optimization} -We would recommend using [Fontaine](https://github.com/nuxt-modules/fontaine) to reduce your [CLS](https://web.dev/cls). If you need something more advanced, consider creating a Nuxt module to extend the build process or the Nuxt runtime. +Мы рекомендуем использовать [Fontaine](https://github.com/nuxt-modules/fontaine) для сокращения вашего [CLS](https://web.dev/cls). Если вам нужно что-то более продвинутое, рассмотрите возможность создания модуля Nuxt для расширения процесса сборки или рантайма Nuxt. ::tip -Always remember to take advantage of the various tools and techniques available in the Web ecosystem at large to make styling your application easier and more efficient. Whether you're using native CSS, a preprocessor, postcss, a UI library or a module, Nuxt has got you covered. Happy styling! +Всегда помните о необходимости использовать различные инструменты и методы, доступные в экосистеме Web в целом, чтобы сделать стилизацию вашего приложения проще и эффективнее. Используете ли вы собственный CSS, препроцессор, postcss, библиотеку пользовательского интерфейса или модуль, Nuxt поможет вам. Счастливой стилизации! :: -### LCP Advanced optimizations +### Продвинутая оптимизация LCP {#lcp-advanced-optimizations} -You can do the following to speed-up the download of your global CSS files: +Вы можете сделать следующее, чтобы ускорить загрузку ваших глобальных CSS-файлов: -- Use a CDN so the files are physically closer to your users -- Compress your assets, ideally using Brotli -- Use HTTP2/HTTP3 for delivery -- Host your assets on the same domain (do not use a different subdomain) +- Используйте CDN, чтобы файлы были физически ближе к вашим пользователям +- Сжимайте ваши ассеты, в идеале с помощью Brotli +- Используйте HTTP2/HTTP3 для доставки +- Размещайте ваши ассеты на том же домене (не используйте другой поддомен) -Most of these things should be done for you automatically if you're using modern platforms like Cloudflare, Netlify or Vercel. -You can find an LCP optimization guide on [web.dev](https://web.dev/optimize-lcp). +Большинство из этих вещей могут быть сделаны для вас автоматически, если вы используете современные платформы, такие как Cloudflare, Netlify или Vercel. +Вы можете найти руководство по оптимизации LCP на [web.dev](https://web.dev/optimize-lcp). -If all of your CSS is inlined by Nuxt, you can (experimentally) completely stop external CSS files from being referenced in your rendered HTML. -You can achieve that with a hook, that you can place in a module, or in your Nuxt configuration file. +Если весь ваш CSS встроен инлайн с помощью Nuxt, вы можете (экспериментально) полностью запретить внешние CSS файлы в отрисованном HTML. Вы можете добиться этого с помощью хука, который вы можете поместить в модуль или в файл конфигурации Nuxt. ```ts [nuxt.config.ts] export default defineNuxtConfig({ hooks: { 'build:manifest': (manifest) => { - // find the app entry, css list + // ищем список файлов css в точке входа в приложение const css = manifest['node_modules/nuxt/dist/app/entry.js']?.css if (css) { - // start from the end of the array and go to the beginning + // начинаем с конца массива и двигаемся к его началу for (let i = css.length - 1; i >= 0; i--) { - // if it starts with 'entry', remove it from the list + // если css начинается с «entry», удаляем его из списка if (css[i].startsWith('entry')) css.splice(i, 1) } }