W3docs

HTML Стили - CSS

На этой странице вы узнаете, как добавить CSS к элементам HTML тремя способами, оформить их с помощью различных CSS-свойств и изучить примеры.

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

CSS значительно экономит усилия. Он может управлять макетом сразу нескольких страниц одновременно.

Существует 3 способа добавить CSS к HTML-элементам:

  • Встроенный (Inline) — атрибут style добавляется непосредственно к HTML-элементу.
  • Внутренний (Internal) — элемент <style> помещается в раздел <head> страницы.
  • Внешний (External) — отдельный файл .css подключается к странице.

Зачем три метода? Каждый из них предполагает компромисс между удобством и охватом. Встроенные стили удобны, но применяются только к одному элементу. Внутренние стили охватывают одну страницу. Внешние таблицы стилей — рекомендуемый подход для реальных проектов, поскольку один файл может оформить весь сайт и кэшируется браузером.

Приоритет каскада

Когда несколько правил нацелены на один и тот же элемент, CSS разрешает конфликт по специфичности и порядку в источнике. Как правило, чем ближе стиль объявлен к элементу, тем выше его приоритет:

встроенный style > внутренний <style> > внешняя таблица стилей

То есть если внешняя таблица задаёт абзацу синий цвет, а встроенный style — красный, абзац будет красным. (Флаг !important может изменить этот порядок, но используйте его с осторожностью.) Подробнее — во введении в CSS.

Давайте рассмотрим каждый способ.

Встроенный CSS

Встроенный CSS применяет конкретный стиль к отдельному HTML-элементу. Для этого используется атрибут style элемента HTML.

В приведённом ниже примере цвет текста элемента <p> задан красным:

Пример встроенного CSS:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <h1>Usage of the inline CSS</h1>
    <p style="color:red;">The paragraph is red.</p>
  </body>
</html>

Внутренний CSS

Внутренний CSS задаёт стиль для одной HTML-страницы. Он определяется в элементе <head> HTML-страницы внутри тега <style>:

Пример внутреннего CSS:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      body {
        background-color: yellow;
      }
      h1 {
        font-size: 30px;
      }
      p {
        font-size: 18px;
      }
    </style>
  </head>
  <body>
    <h1>Lorem Ipsum</h1>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

Внешний CSS

Внешняя таблица стилей задаёт оформление для нескольких HTML-страниц. Она может изменить внешний вид всего сайта, редактируя лишь один файл.

Чтобы использовать внешнюю таблицу стилей, добавьте элемент <link> внутрь <head> на HTML-странице. Атрибут href указывает путь к файлу .css:

Пример внешней таблицы стилей CSS:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <h1>Lorem Ipsum</h1>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

Подключённый файл styles.css содержит правила. Он не может содержать HTML-код и должен быть сохранён с расширением .css. Для приведённой выше страницы файл styles.css мог бы выглядеть так:

body {
  background-color: yellow;
}
h1 {
  font-size: 30px;
}
p {
  font-size: 18px;
}

Шрифты и цвета CSS

Свойство CSS font-family задаёт гарнитуру шрифта для текстового содержимого.

Свойство CSS font-size определяет размер текста.

Свойство CSS color задаёт цвет самого текста. (Обратите внимание, что color — не свойство шрифта; оно управляет цветом переднего плана текста.)

Свойство CSS background-color задаёт цвет фона элемента.

Пример шрифтов и цветов CSS:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      h1 {
        color: #008000;
        font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
        font-size: 200%;
      }
      p {
        color: #666666;
        font-family: 'New Roman', serif;
        font-size: 150%;
      }
    </style>
  </head>
  <body>
    <h1>Lorem Ipsum</h1>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

Рамка CSS

Свойство CSS border устанавливает значения для всех четырёх сторон элемента.

Пример свойства border в CSS:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p {
        border: 2px dotted red;
      }
    </style>
  </head>
  <body>
    <h1>Heading</h1>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

Отступ CSS (Padding)

Свойство CSS padding задаёт внутренний отступ (пространство) между текстом и рамкой.

Пример свойства padding в CSS:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p {
        border: 2px dashed #008022;
        padding: 50px;
      }
    </style>
  </head>
  <body>
    <h1>Heading</h1>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

Внешний отступ CSS (Margin)

Свойство CSS margin создаёт пространство вокруг элемента.

Пример свойства margin в CSS:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p {
        border: 2px dashed #090fce;
        margin: 50px;
      }
    </style>
  </head>
  <body>
    <h1>Heading</h1>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

Атрибут id

Атрибут id обращается к единственному уникальному элементу. Значение id должно быть уникальным на странице — два элемента не могут иметь одинаковый id. В CSS он выбирается с помощью символа «решётки», например #large-text.

Пример атрибута id:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      #large-text {
        border: 8px groove powderblue;
        font-size: 24px;
        padding: 20px;
      }
    </style>
  </head>
  <body>
    <h1>Heading</h1>
    <p id="large-text">
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

Атрибут class

Атрибут class допускает повторное использование: один и тот же класс можно применить к любому количеству элементов, а один элемент может иметь несколько классов. Это делает классы подходящим инструментом для одинакового оформления группы элементов. В CSS класс выбирается с помощью точки, например .text.

Пример атрибута class:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .text {
        border: 8px inset powderblue;
        font-size: 20px;
        padding: 10px;
      }
    </style>
  </head>
  <body>
    <h1>Heading</h1>
    <p class="text">
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <p class="text">
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

Практика

Практика
Какие способы добавления CSS-стилей в HTML-документ описаны в статье W3docs?
Какие способы добавления CSS-стилей в HTML-документ описаны в статье W3docs?
Практика
Если внешняя таблица стилей задаёт абзацу синий цвет, а встроенный атрибут style задаёт красный, какой цвет победит?
Если внешняя таблица стилей задаёт абзацу синий цвет, а встроенный атрибут style задаёт красный, какой цвет победит?
Was this page helpful?