К основному содержанию
правило

css — правило для Cursor: что делает и как установить

Задаёт стандарты вёрстки для Cursor: модульную структуру Sass, именование по БЭМ, переменные и производительную анимацию. Пригодится для поддержки чистоты в стилях.

Установить в Cursor · Вручную: положить файлы Все способы и платформы ↓
.cursor/rules/css.mdc
Открыть на GitHub

Что делает css

Правило регламентирует написание стилей в проекте с использованием Sass. Оно предписывает делить файлы по упрощённой схеме ITCSS на каталоги base, components, layout и utilities. Для селекторов вводится обязательный синтаксис БЭМ с отказом от глубокой вложенности. Цвета, типографика и отступы выносятся в дизайн-токены через переменные CSS в корневом файле _variables.scss.

Стилизация строится по принципу mobile-first с постепенным расширением через медиазапросы. Макеты страниц формируются на CSS Grid, а выравнивание элементов внутри блоков отдаётся Flexbox. Для шрифтов включается свойство font-display: swap, а анимации ограничиваются свойствами transform и opacity ради аппаратного ускорения. Изменение размеров или отступов в анимациях исключается, чтобы не вызывать повторные перерисовки интерфейса.

Инструкция прямо предписывает использовать препроцессор Sass. Проектам на чистом CSS или CSS Modules придётся переписать структуру импортов.

Какие задачи решает

  • избавиться от каскадных конфликтов селекторов через БЭМ
  • разделить стили проекта на модульные слои в Sass
  • настроить адаптивную сетку с подходом mobile-first
  • ускорить рендеринг за счёт анимации через transform и opacity

Примеры запросов агенту

  • Сверстай карточку товара с заголовком и кнопкой по методологии БЭМ
  • Разбей общие переменные и стили кнопок на Sass-модули по структуре ITCSS
  • Напиши адаптивную сетку каталога на CSS Grid с подходом mobile-first

Как установить css

Вручную: положить файлы

.cursor/rules/css.mdc

Во frontmatter: description, globs, alwaysApply

По шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules

Вопросы о css

Как установить css в Cursor?

Сохраните файл правила по пути .cursor/rules/css.mdc в корне вашего проекта.

Что делает правило css?

Оно инструктирует модель использовать архитектуру ITCSS в Sass, плоские селекторы по БЭМ, относительные единицы измерения и CSS-переменные для дизайн-токенов.

Какие требования к анимациям задаёт это правило?

Анимировать разрешено только свойства transform и opacity, поскольку они задействуют аппаратное ускорение. Анимация свойств width, height, margin или padding запрещена для предотвращения перерисовок.

Исходный текст

css.mdc · CC0-1.0
---
description: Definitive guidelines for writing maintainable, performant, and accessible CSS. Focus on modern practices, robust architecture, and efficient styling patterns.
globs: **/*
---
# CSS Best Practices

This guide outlines the definitive best practices for writing CSS within our team. Adhering to these principles ensures our stylesheets are scalable, maintainable, performant, and accessible.

## 1. Code Organization & Structure

Adopt a modular, predictable structure. Use Sass for pre-processing.

### 1.1 File Structure (Modular & Scalable)

Organize CSS into logical, focused files. A simplified ITCSS-like structure is recommended.

```css
/*
  css/
  ├── base/             // Project-wide defaults (reset, typography, variables)
  │   ├── _reset.scss
  │   ├── _typography.scss
  │   └── _variables.scss // Design tokens
  ├── components/       // Self-contained UI components (buttons, cards)
  │   ├── _button.scss
  │   └── _card.scss
  ├── layout/           // Major page sections (header, footer, grid)
  │   ├── _grid.scss
  │   └── _header.scss
  └── utilities/        // Single-purpose helper classes (spacing, text alignment)
      ├── _spacing.scss
      └── _helpers.scss
*/

// main.scss
@import 'base/reset';
@import 'base/variables';
@import 'base/typography';

@import 'layout/grid';
@import 'layout/header';

@import 'components/button';
@import 'components/card';

@import 'utilities/spacing';
@import 'utilities/helpers';
```

### 1.2 Naming Convention (BEM)

Use BEM (Block-Element-Modifier) for clear, flat, and highly readable selectors. This prevents specificity wars and improves reusability.

❌ BAD: Deeply nested, ambiguous selectors
```css
.header .nav ul li a { /* ... */ }
.card.featured { /* ... */ }
```

✅ GOOD: BEM for clarity and reusability
```css
/* Block */
.card { /* ... */ }

/* Element */
.card__title { /* ... */ }
.card__image { /* ... */ }

/* Modifier */
.card--featured { /* ... */ }
.card__title--large { /* ... */ }
```

### 1.3 CSS Custom Properties (Design Tokens)

Centralize design values (colors, fonts, spacing) using CSS variables. This enables consistency, easy theming, and dynamic updates.

```css
/* _variables.scss */
:root {
  --color-primary: #007bff;
  --color-text: #333;
  --font-family-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto;
  --spacing-md: 1rem;
}

/* Usage */
.button {
  background-color: var(--color-primary);
  color: white;
  padding: var(--spacing-md);
  font-family: var(--font-family-sans);
}
```

### 1.4 Minimal Nesting (Sass)

Avoid excessive nesting in Sass; it leads to overly specific and hard-to-override CSS. Nest only when necessary for context or specificity (e.g., pseudo-states).

❌ BAD: Over-nested selectors
```scss
.nav {
  ul {
    li {
      a {
        color: var(--color-text);
        &:hover {
          color: var(--color-primary);
        }
      }
    }
  }
}
```

✅ GOOD: Flat structure, nest only for direct context
```scss
.nav {
  &__list { /* ... */ }
  &__item { /* ... */ }
  &__link {
    color: var(--color-text);
    &:hover {
      color: var(--color-primary);
    }
  }
}
```

## 2. Layout & Responsive Design

Prioritize mobile-first design using modern layout tools and relative units.

### 2.1 Mobile-First Approach

Design for small screens first, then progressively enhance for larger viewports using media queries.

```css
/* Mobile styles first */
.container {
  padding: 1rem;
}

/* Larger screens (e.g., tablet and up) */
@media (min-width: 768px) {
  .container {
    padding: 2rem;
  }
}
```

### 2.2 CSS Grid for 2D Layouts, Flexbox for 1D Layouts

Use the right tool for the job.

✅ GOOD: Flexbox for aligning items in a single dimension (row or column)
```css
.button-group {
  display: flex;
  gap: 1rem;
  justify-content: center; /* Horizontally center items */
  align-items: center;     /* Vertically center items */
}
```

✅ GOOD: CSS Grid for complex two-dimensional page layouts
```css
.page-layout {
  display: grid;
  grid-template-columns: 1fr; /* Single column on mobile */
  gap: 1.5rem;
}

@media (min-width: 992px) {
  .page-layout {
    grid-template-columns: 250px 1fr; /* Sidebar + main content on desktop */
    grid-template-areas: "sidebar main";
  }
  .page-layout__sidebar { grid-area: sidebar; }
  .page-layout__main { grid-area: main; }
}
```

### 2.3 Relative Units

Use relative units (`rem`, `em`, `vw`, `vh`, `%`) for flexible, scalable, and accessible designs. Avoid fixed `px` values for spacing and typography.

❌ BAD: Fixed `px` values
```css
.text { font-size: 16px; margin-bottom: 20px; }
.hero { height: 400px; }
```

✅ GOOD: Relative units
```css
.text { font-size: 1rem; margin-bottom: 1.25rem; } /* Based on root font-size */
.hero { min-height: 70vh; } /* Viewport height */
.image { max-width: 100%; height: auto; } /* Fluid images */
```

### 2.4 Container Queries

Leverage `@container` queries for component-level responsiveness, allowing components to adapt based on their parent container's size, not just the viewport.

```css
.card-container {
  container-type: inline-size;
  container-name: card-scope;
}

.card {
  display: flex;
  flex-direction: column;
}

@container card-scope (min-width: 400px) {
  .card {
    flex-direction: row;
    align-items: center;
  }
  .card__image {
    width: 150px;
    height: auto;
  }
}
```

## 3. Performance Considerations

Optimize CSS for fast loading and efficient rendering.

### 3.1 Efficient Selectors

Browsers read selectors right-to-left. Keep selectors short and avoid overly specific or universal selectors where possible.

❌ BAD: Overly specific, slow selector
```css
main div p.title { /* ... */ }
* { box-sizing: border-box; } /* Global, but expensive if not reset */
```

✅ GOOD: Short, class-based selectors
```css
.title { /* ... */ }
.button { /* ... */ }
```

### 3.2 Minimize Reflows & Repaints

Animate `transform` and `opacity` properties for smooth animations, as they can be hardware-accelerated. Avoid animating properties that trigger layout changes (e.g., `width`, `height`, `margin`, `padding`).

❌ BAD: Animating layout properties
```css
.modal {
  transition: width 0.3s ease, height 0.3s ease;
}
```

✅ GOOD: Animating `transform` and `opacity`
```css
.modal {
  transition: transform 0.3s ease, opacity 0.3s ease;
  transform: scale(0.9);
  opacity: 0;
}
.modal.is-open {
  transform: scale(1);
  opacity: 1;
}
```

### 3.3 Font Optimization

Use `font-display: swap` for web fonts to prevent invisible text during font loading (FOIT).

```css
@font-face {
  font-family: 'CustomFont';
  src: url('CustomFont.woff2') format('woff2');
  font-weight: 400;
  font-display: swap; /* Crucial for performance */
}
```

## 4. Accessibility

Bake accessibility into every styling decision.

### 4.1 Color Contrast

Ensure text and interactive elements meet WCAG AA contrast ratios (4.5:1 for normal text, 3:1 for large text/UI components). Use tools to check.

### 4.2 Visible Focus Indicators

Provide clear, visible focus styles for keyboard users.

❌ BAD: Removing outline without replacement
```css
a:focus, button:focus {
  outline: none; /* Don't do this without a custom focus style! */
}
```

✅ GOOD: Custom, visible focus styles
```css
a:focus, button:focus {
  outline: 2px solid var(--color-primary);
  outline-offset: 2px;
}
```

### 4.3 Respect `prefers-reduced-motion`

Offer a reduced motion experience for users who prefer it.

```css
/* Default animation */
.element {
  transition: transform 0.3s ease-out;
}

/* Reduced motion preference */
@media (prefers-reduced-motion: reduce) {
  .element {
    transition: none;
    animation: none;
  }
}
```

## 5. Common Pitfalls & Anti-patterns

Avoid these patterns to maintain a healthy codebase.

### 5.1 Avoid `!important`

`!important` breaks the cascade and makes styles extremely difficult to override and debug. Use it only in rare, justified cases (e.g., utility classes that *must* override everything).

❌ BAD: Overuse of `!important`
```css
.button {
  background-color: red !important;
}
```

✅ GOOD: Manage specificity carefully, use BEM, and rely on the cascade.
```css
/* Adjust specificity or order */
.button--primary {
  background-color: var(--color-primary);
}
```

### 5.2 Avoid ID Selectors in CSS

IDs have extremely high specificity, leading to specificity wars and reduced reusability. Reserve IDs for JavaScript hooks or fragment identifiers.

❌ BAD: Styling with IDs
```css
#main-nav {
  /* ... */
}
```

✅ GOOD: Use classes instead
```css
.main-nav {
  /* ... */
}
```

### 5.3 No Inline Styles

Inline styles are difficult to manage, override, and maintain. Keep all styling in stylesheets.

❌ BAD: Inline styles
```html
<div style="color: red; font-size: 16px;">Hello</div>
```

✅ GOOD: Class-based styling
```html
<div class="text-error text-base">Hello</div>
```
```css
.text-error { color: red; }
.text-base { font-size: 1rem; }
```

### 5.4 Use Shorthand Properties

Use shorthand properties where appropriate to reduce file size and improve readability.

❌ BAD: Longhand properties
```css
.box {
  margin-top: 10px;
  margin-right: 20px;
  margin-bottom: 10px;
  margin-left: 20px;
}
```

✅ GOOD: Shorthand properties
```css
.box {
  margin: 10px 20px;
}
```

### 5.5 Browser Compatibility (`@supports`)

Use `@supports` to provide progressive enhancements for modern CSS features, with fallbacks for older browsers.

```css
/* Fallback for older browsers */
.gallery {
  display: block; /* Default to block layout */
}

/* Enhanced layout with Grid */
@supports (display: grid) {
  .gallery {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 1rem;
  }
}
```

© sanjeed5 · CC0-1.0 · sanjeed5/awesome-cursor-rules-mdc

Похожие правила IDE

Все правила IDE по теме «Фронтенд и UI» →
scss-best-practices Mindrally Скилл задаёт правила вёрстки на SCSS: структуру файлов 7-1, правила вложенности селекторов, систему переменных и соглашения БЭМ. Помогает агенту писать чистые стили. CX Codex +1 1 700установок sass-best-practices Mindrally Скилл задаёт агенту правила письма на Sass с отступами: структура файлов, переменные, миксины, BEM. Пригодится, если стили в проекте пишут на .sass, а не на SCSS. CX Codex +1 845установок css-architecture aj-geddes Скилл для ИИ-агента, который помогает разложить CSS по методологиям BEM, SMACSS и CSS-in-JS. Пригодится, когда стили в проекте растут быстрее, чем вы успеваете их переименовывать. CX Codex +1 959установок good-css vojtaholik Заменяет каскады брейкпоинтов и вспомогательные скрипты современными возможностями CSS. Работает с чистым CSS, Tailwind, StyleX и CSS-in-JS. CX Codex +1 1 500установок liquid-theme-standards benjaminsehl Скилл задаёт правила вёрстки и клиентских скриптов для тем Shopify. Помогает писать предсказуемый код в файлах .liquid и ресурсах ассетов. CX Codex +1 2 900установок tailwind-css-patterns giuseppe-trisciuoglio Скилл с готовыми паттернами Tailwind CSS: адаптивные сетки, карточки, формы, тёмная тема. Пригодится, когда агент верстает компоненты на React, Vue или Svelte. CX Codex +1 17 700установок

Из того же набора240

Весь набор →
d3 Правило для Cursor задаёт, как писать код визуализаций на D3.js v7+: модульные импорты, selection.join() вместо ручного enter/update/exit, стили через CSS. ★ 3 580звёзд репо cypress Задаёт правила E2E-тестирования в Cypress для Cursor: изоляцию тестов, селекторы по data-cy, моки через cy.intercept() и вход через сессии. ★ 3 580звёзд репо customtkinter Правило для Cursor подсказывает, как организовать приложение на customtkinter: вынести логику интерфейса в класс и последовательно настроить оформление. ★ 3 580звёзд репо cuda Правило задаёт Cursor стиль работы с CUDA C++: проверка ошибок API, разделение host и device кода, оптимизация ядер. Пригодится, если пишете GPU-код и устали от молчаливых падений. ★ 3 580звёзд репо crewai Правило для Python-файлов подсказывает Cursor, как организовать CrewAI: разделять агентов, задачи и оркестрацию, а также передавать контекст между задачами. ★ 3 580звёзд репо codemirror Правило для Cursor задаёт, как писать редакторы на CodeMirror 6: модульные импорты, неизменяемое состояние, конфигурация через расширения. ★ 3 580звёзд репо cloudflare Задаёт стандарты разработки под Cloudflare Workers и Pages в Cursor. Помогает писать stateless-код для edge-рантайма, подключать базы данных и следить за размером бандла. ★ 3 580звёзд репо click Правило задаёт рекомендации по созданию CLI на Python с библиотекой click. Помогает организовать команды, параметры, вывод и подсказки. ★ 3 580звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой