Ir para o conteúdo principal
Version: 2.0.0-beta.22 🚧

Estilo e Layout

tip

This section is focused on styling through stylesheets. For more advanced customizations (DOM structure, React code...), refer to the swizzling guide.

Um site Docusaurus é uma aplicação React de uma única página. Você pode estilizá-lo da mesma forma que estiliza os aplicativos React.

Há algumas abordagens/frameworks que funcionarão, dependendo das suas preferências e do tipo de site que você está tentando construir. Websites that are highly interactive and behave more like web apps will benefit from more modern styling approaches that co-locate styles with the components. Estilo de componente também pode ser particularmente útil quando você deseja personalizar ou deslizar um componente.

Estilos globais

This is the most traditional way of styling that most developers (including non-front-end developers) would be familiar with. It works fine for small websites that do not have much customization.

If you're using @docusaurus/preset-classic, you can create your own CSS files (e.g. /src/css/custom.css) and import them globally by passing them as an option of the classic theme.

docusaurus.config.js
module.exports = {
// ...
presets: [
[
'@docusaurus/preset-classic',
{
theme: {
customCss: [require.resolve('./src/css/custom.css')],
},
},
],
],
};

Qualquer CSS que você escrever nesse arquivo estará disponível globalmente e pode ser referenciado diretamente usando strings literais.

/src/css/custom.css
.purple-text {
color: rebeccapurple;
}
function MyComponent() {
return (
<main>
<h1 className="purple-text">Purple Heading!</h1>
</main>
);
}

If you want to add CSS to any element, you can open the DevTools in your browser to inspect its class names. Class names come in several kinds:

  • Theme class names. These class names are listed exhaustively in the next subsection. They don't have any default properties. You should always prioritize targeting those stable class names in your custom CSS.
  • Infima class names. These class names are found in the classic theme and usually follow the BEM convention of block__element--modifier. They are usually stable but are still considered implementation details, so you should generally avoid targeting them. However, you can modify Infima CSS variables.
  • CSS module class names. These class names have a hash in production (codeBlockContainer_RIuc) and are appended with a long file path in development. They are considered implementation details and you should almost always avoid targeting them in your custom CSS. If you must, you can use an attribute selector ([class*='codeBlockContainer']) that ignores the hash.

Nomes de classes de tema

We provide some stable CSS class names for robust and maintainable global layout styling. These names are theme-agnostic and meant to be targeted by custom CSS.

tip

If you can't find a way to create a robust CSS selector, please report your customization use-case and we will consider adding new class names.

Exhaustive list of stable class names
export const ThemeClassNames = {
page: {
blogListPage: 'blog-list-page',
blogPostPage: 'blog-post-page',
blogTagsListPage: 'blog-tags-list-page',
blogTagPostListPage: 'blog-tags-post-list-page',
docsDocPage: 'docs-doc-page',
docsTagsListPage: 'docs-tags-list-page',
docsTagDocListPage: 'docs-tags-doc-list-page',
mdxPage: 'mdx-page',
},
wrapper: {
main: 'main-wrapper',
blogPages: 'blog-wrapper',
docsPages: 'docs-wrapper',
mdxPages: 'mdx-wrapper',
},
common: {
editThisPage: 'theme-edit-this-page',
lastUpdated: 'theme-last-updated',
backToTopButton: 'theme-back-to-top-button',
codeBlock: 'theme-code-block',
admonition: 'theme-admonition',
admonitionType: (type: 'note' | 'tip' | 'danger' | 'info' | 'caution') =>
`theme-admonition-${type}`,
},
layout: {
},
docs: {
docVersionBanner: 'theme-doc-version-banner',
docVersionBadge: 'theme-doc-version-badge',
docBreadcrumbs: 'theme-doc-breadcrumbs',
docMarkdown: 'theme-doc-markdown',
docTocMobile: 'theme-doc-toc-mobile',
docTocDesktop: 'theme-doc-toc-desktop',
docFooter: 'theme-doc-footer',
docFooterTagsRow: 'theme-doc-footer-tags-row',
docFooterEditMetaRow: 'theme-doc-footer-edit-meta-row',
docSidebarContainer: 'theme-doc-sidebar-container',
docSidebarMenu: 'theme-doc-sidebar-menu',
docSidebarItemCategory: 'theme-doc-sidebar-item-category',
docSidebarItemLink: 'theme-doc-sidebar-item-link',
docSidebarItemCategoryLevel: (level: number) =>
`theme-doc-sidebar-item-category-level-${level}` as const,
docSidebarItemLinkLevel: (level: number) =>
`theme-doc-sidebar-item-link-level-${level}` as const,
},
blog: {
},
} as const;

Estilizando seu site com Infima

@docusaurus/preset-classic usa Infima como um framework de estilo. Infima provides a flexible layout and common UI components styling suitable for content-centric websites (blogs, documentation, landing pages). Para obter mais detalhes, confira o site da Infima.

When you scaffold your Docusaurus project with create-docusaurus, the website will be generated with basic Infima stylesheets and default styling. You can override Infima CSS variables globally.

/src/css/custom.css
:root {
--ifm-color-primary: #25c2a0;
--ifm-code-font-size: 95%;
}

Infima usa 7 tonalidades de cada cor. Recomendamos usar o ColorBox para encontrar os diferentes tons de cores para a cor principal escolhida.

Como alternativa, use a seguinte ferramenta para gerar os diferentes tons de seu site e copiar as variáveis para /src/css/custom.css.

tip

Aim for at least WCAG-AA contrast ratio for the primary color to ensure readability. Use the Docusaurus website itself to preview how your color palette would look like. You can use alternative palettes in dark mode because one color doesn't usually work in both light and dark mode.

CSS Variable NameHexAdjustmentContrast Rating
--ifm-color-primary-lightest#3cad6eFail 🔴
--ifm-color-primary-lighter#359962Fail 🔴
--ifm-color-primary-light#33925dFail 🔴
--ifm-color-primary#2e85550AA 👍
--ifm-color-primary-dark#29784cAA 👍
--ifm-color-primary-darker#277148AA 👍
--ifm-color-primary-darkest#205d3bAAA 🏅

Replace the variables in src/css/custom.css with these new variables.

/src/css/custom.css
:root {
--ifm-color-primary: #2e8555;
--ifm-color-primary-dark: #29784c;
--ifm-color-primary-darker: #277148;
--ifm-color-primary-darkest: #205d3b;
--ifm-color-primary-light: #33925d;
--ifm-color-primary-lighter: #359962;
--ifm-color-primary-lightest: #3cad6e;
}

Modo Escuro

In light mode, the <html> element has a data-theme="light" attribute; in dark mode, it's data-theme="dark". Therefore, you can scope your CSS to dark-mode-only by targeting html with a specific attribute.

/* Overriding root Infima variables */
[data-theme='dark'] {
--ifm-color-primary: #4e89e8;
}
/* Styling one class specially in dark mode */
[data-theme='dark'] .purple-text {
color: plum;
}

Mobile View

Docusaurus uses 996px as the cutoff between mobile screen width and desktop. If you want your layout to be different in the mobile view, you can use media queries.

.banner {
padding: 4rem;
}
/** In mobile view, reduce the padding */
@media screen and (max-width: 996px) {
.heroBanner {
padding: 2rem;
}
}

Módulos CSS

Para estilizar seus componentes usando Módulos CSS, nomeie seus arquivos de folha de estilo com o sufixo .module.css (por exemplo, welcome.module.css). Webpack will load such CSS files as CSS modules and you have to reference the class names as properties of the imported CSS module (as opposed to using plain strings). Isso é semelhante à convenção usada no Criar aplicativo React.

styles.module.css
.main {
padding: 12px;
}

.heading {
font-weight: bold;
}

.contents {
color: #ccc;
}
import styles from './styles.module.css';

function MyComponent() {
return (
<main className={styles.main}>
<h1 className={styles.heading}>Hello!</h1>
<article className={styles.contents}>Lorem Ipsum</article>
</main>
);
}

The class names will be processed by webpack into a globally unique class name during build.

CSS-in-JS

caution

CSS-in-JS support is a work in progress, so libs like MUI may have display quirks. Boas-vindas aos PRs.

Sass/SCSS

Para usar Sass/SCSS como seu pré-processador CSS, instale o plugin não oficial Docusaurus 2 docusaurus-plugin-sass. Este plug-in funciona tanto para estilos globais quanto para a abordagem de módulos CSS:

  1. Instale docusaurus-plugin-sass:
npm install --save docusaurus-plugin-sass sass
  1. Inclua o plugin no seu arquivo docusaurus.config.js:
docusaurus.config.js
module.exports = {
// ...
plugins: ['docusaurus-plugin-sass'],
// ...
};
  1. Escreva e importe suas folhas de estilo no Sass/SCSS normalmente.

Estilos globais usando Sass/SCSS

Agora você pode definir a propriedade customCss de @docusaurus/preset-classic para apontar para o seu arquivo Sass/SCSS:

docusaurus.config.js
module.exports = {
presets: [
[
'@docusaurus/preset-classic',
{
// ...
theme: {
customCss: [require.resolve('./src/css/custom.scss')],
},
// ...
},
],
],
};

Módulos usando Sass/SCSS

Nomeie seus arquivos de folha de estilo com o sufixo .module.scss (por exemplo, welcome.module.scss) em vez de .css. Webpack usará sass-loader para pré-processar suas folhas de estilo e carregá-las como módulos CSS.

styles.module.scss
.main {
padding: 12px;

article {
color: #ccc;
}
}
import styles from './styles.module.scss';

function MyComponent() {
return (
<main className={styles.main}>
<article>Lorem Ipsum</article>
</main>
);
}