← Назад к вопросам

С помощью чего в CSS задаются стили?

1.2 Junior🔥 241 комментариев
#HTML и CSS

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI2 апр. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

С помощью чего в CSS задаются стили

Стили в CSS задаются через набор инструментов и механизмов. Я расскажу о них подробно, так как это основа фронтенд-разработки.

1. Селекторы (Selectors)

Селектор — это механизм выбора элементов, к которым нужно применить стили.

Селекторы элементов (Type selectors)

p { color: blue; }
div { background: white; }
span { font-size: 14px; }

Селекторы классов (Class selectors)

.button { padding: 10px 20px; }
.active { color: red; }
.text-center { text-align: center; }

Селекторы ID (ID selectors)

#header { position: fixed; }
#main-content { max-width: 1200px; }

Комбинаторы (Combinators)

/* Потомок */
.container p { margin: 10px; }

/* Прямой потомок */
.container > p { color: black; }

/* Соседний элемент */
h1 + p { margin-top: 0; }

/* Все соседние элементы */
h1 ~ p { color: gray; }

Селекторы атрибутов (Attribute selectors)

input[type="text"] { border: 1px solid gray; }
a[href^="https"] { color: green; }
input[disabled] { opacity: 0.5; }

Псевдо-селекторы (Pseudo-selectors)

a:hover { color: red; }
input:focus { outline: blue; }
button:active { transform: scale(0.95); }
li:first-child { font-weight: bold; }
li:nth-child(2n) { background: #f0f0f0; }

Псевдо-элементы (Pseudo-elements)

p::before { content: '>> '; }
p::after { content: ' <<'; }
input::placeholder { color: gray; }

2. Свойства CSS (CSS Properties)

Свойства — это то, что мы меняем у элемента.

Типографика

.text {
  font-family: 'Arial', sans-serif;
  font-size: 16px;
  font-weight: bold;
  font-style: italic;
  line-height: 1.5;
  letter-spacing: 2px;
  text-align: center;
  color: #333;
}

Модель блока (Box Model)

.box {
  width: 100px;
  height: 100px;
  padding: 20px;           /* внутренний отступ */
  margin: 30px;            /* внешний отступ */
  border: 2px solid black; /* граница */
  box-sizing: border-box;  /* включить border в width */
}

Фон и цвета

.card {
  background-color: white;
  background-image: url('pattern.png');
  background-size: cover;
  border: 1px solid #ddd;
}

Позиционирование

.absolute { position: absolute; top: 10px; left: 20px; }
.fixed { position: fixed; bottom: 0; right: 0; }
.sticky { position: sticky; top: 0; }

Flexbox

.container {
  display: flex;
  justify-content: center;      /* по горизонтали */
  align-items: center;          /* по вертикали */
  gap: 20px;                    /* промежуток между элементами */
  flex-direction: column;        /* направление */
}

Grid

.grid {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  grid-gap: 20px;
  auto-rows: minmax(200px, auto);
}

Трансформации и анимации

.box {
  transform: rotate(45deg) scale(1.5) translateX(20px);
  transition: all 0.3s ease;
}

@keyframes slide {
  from { left: 0; }
  to { left: 100px; }
}

.animated {
  animation: slide 1s ease-in-out;
}

3. Cascading и Specificity (Каскадность и специфичность)

Каскадность — более специфичные селекторы переопределяют менее специфичные.

Иерархия специфичности

/* 0,0,0 - элемент */
p { color: blue; }

/* 0,1,0 - класс */
.text { color: red; } /* переопределит */

/* 1,0,0 - ID */
#main { color: green; } /* переопределит */

/* !important - наивысший приоритет */
.warning { color: orange !important; } /* переопределит всё */

4. Методы добавления стилей

Внешний файл (Recommended)

<link rel="stylesheet" href="styles.css">

Внутри тега style

<style>
  body { background: white; }
</style>

Инлайн стили (Избегай)

<div style="color: red; font-size: 16px;">Текст</div>

5. CSS препроцессоры (SCSS, LESS)

// Переменные
$primary-color: #3498db;
$font-size: 16px;

// Вложенность
.button {
  background: $primary-color;
  font-size: $font-size;
  
  &:hover {
    opacity: 0.9;
  }
  
  &.active {
    background: darken($primary-color, 10%);
  }
}

// Миксины
@mixin flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.container {
  @include flex-center;
}

6. Tailwind CSS (Modern approach)

<!-- Утилитарные классы вместо написания CSS -->
<div class="flex justify-center items-center gap-4 p-8 bg-white rounded-lg">
  <button class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
    Click me
  </button>
</div>

7. CSS-in-JS (в React экосистеме)

Styled Components

import styled from 'styled-components';

const Button = styled.button`
  background: blue;
  color: white;
  padding: 10px 20px;
  
  &:hover {
    opacity: 0.9;
  }
`;

export function MyComponent() {
  return <Button>Click</Button>;
}

CSS Modules

import styles from './Button.module.css';

export function Button() {
  return <button className={styles.button}>Click</button>;
}

8. CSS Variables (Custom Properties)

:root {
  --primary-color: #3498db;
  --spacing-unit: 8px;
  --border-radius: 4px;
}

.button {
  background: var(--primary-color);
  padding: var(--spacing-unit) calc(var(--spacing-unit) * 2);
  border-radius: var(--border-radius);
}

/* Меняем на мобильных */
@media (max-width: 768px) {
  :root {
    --spacing-unit: 4px;
  }
}

9. Media Queries (Responsive Design)

.container {
  padding: 20px;
}

@media (max-width: 768px) {
  .container {
    padding: 10px;  /* уменьшаем на мобильных */
  }
}

@media (min-width: 1200px) {
  .container {
    max-width: 1200px;  /* ограничиваем на больших экранах */
  }
}

10. BEM (Block Element Modifier)

/* Block */
.card { }

/* Element */
.card__header { }
.card__body { }
.card__footer { }

/* Modifier */
.card--active { }
.card__header--dark { }

Итоговый ответ:

Стили в CSS задаются через:

  1. Селекторы — выбор элементов (классы, ID, типы)
  2. Свойства — что меняем (color, size, position и т.д.)
  3. Значения — на что меняем
  4. Специфичность — приоритет применения стилей
  5. Современные методы — Tailwind, CSS Modules, Styled Components
  6. Media Queries — адаптивность

Это основа всего визуального оформления веб-приложений.

С помощью чего в CSS задаются стили? | PrepBro