Как применить стиль css в html
Перейти к содержимому

Как применить стиль css в html

  • автор:

CSS = Стили и цвета

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

CSS экономит много работы. Он может контролировать расположение нескольких веб-страниц все сразу.

CSS можно добавлять к элементам HTML тремя способами:

  • Встроенный — с помощью атрибута Style в элементах HTML
  • Internal -с помощью <style> элемента в <head> разделе
  • Внешний — с помощью внешнего CSS-файла

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

Совет: Вы можете узнать больше о CSS в нашем учебнике по CSS.

Встроенный CSS

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

Встроенный CSS использует атрибут style элемента HTML.

В этом примере устанавливается цвет текста элемента <h1> синим цветом:

Пример

Внутренняя CSS

Внутренний CSS используется для определения стиля для одной HTML-страницы.

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

Пример

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

Внешние CSS

Внешняя таблица стилей используется для определения стиля для многих HTML-страниц.

С помощью внешней таблицы стилей можно изменить внешний вид всего веб-узла, изменив один файл!

Чтобы использовать внешнюю таблицу стилей, добавьте ссылку на нее в разделе <head> страницы HTML:

Пример

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

Внешняя таблица стилей может быть написана в любом текстовом редакторе. Файл не должен содержать HTML-код и должен быть сохранен с расширением. CSS.

Вот как выглядит "styles.css":

Шрифты CSS

Свойство CSS color определяет используемый цвет текста.

Свойство CSS font-family определяет используемый шрифт.

Свойство CSS font-size определяет размер текста, который будет использоваться.

Пример

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

Граница CSS

Свойство CSS border определяет границу вокруг элемента HTML:

Пример

CSS заполнение

Свойство CSS padding определяет отступ (пробел) между текстом и границей:

Пример

CSS маржа

Свойство CSS margin определяет поле (пробел) за пределами границы:

Пример

Атрибут ID

Чтобы определить конкретный стиль для одного специального элемента, добавьте атрибут id к элементу:

then define a style for the element with the specific id:

Пример

Примечание: Идентификатор элемента должен быть уникальным в пределах страницы, поэтому селектор ID используется для выбора одного уникального элемента!

Атрибут class

Чтобы определить стиль для специального типа элементов, добавьте атрибут class к элементу:

Затем определите стиль для элементов с определенным классом:

Пример

Внешние ссылки

Внешние таблицы стилей можно ссылаться с полным URL-адресом или с помощью пути относительно текущей веб-страницы.

В этом примере используется полный URL-адрес для связывания с таблицей стилей:

Пример

Этот пример связывается с таблицей стилей, расположенной в папке HTML на текущем веб-узле:

Пример

Этот пример связывается с таблицей стилей, расположенной в той же папке, что и текущая страница:

Примере

Дополнительные сведения о путях к файлам можно прочитать в разделе пути к файлам HTML.

How to Add CSS to HTML: Understanding Inline, Internal & External CSS

Jamie Juviler

If you’re building a website, HTML is your best friend. With it, you create all of your page content, including headings, paragraphs, images, tables, forms, lists, and so on. However, you can’t control how these elements look on the page, at least not with HTML alone. That’s why we have CSS.

Site owner learning how to add CSS to HTML

CSS determines how the contents of a web page look when shown in browser. It can be used for a huge range of stylistic purposes, from changing colors and animating elements to determining the whole layout of your page.

HTML Styles — CSS

CSS saves a lot of work. It can control the layout of multiple web pages all at once.

CSS = Styles and Colors

What is CSS?

Cascading Style Sheets (CSS) is used to format the layout of a webpage.

With CSS, you can control the color, font, the size of text, the spacing between elements, how elements are positioned and laid out, what background images or background colors are to be used, different displays for different devices and screen sizes, and much more!

Tip: The word cascading means that a style applied to a parent element will also apply to all children elements within the parent. So, if you set the color of the body text to "blue", all headings, paragraphs, and other text elements within the body will also get the same color (unless you specify something else)!

Using CSS

CSS can be added to HTML documents in 3 ways:

  • Inline — by using the style attribute inside HTML elements
  • Internal — by using a <style> element in the <head> section
  • External — by using a <link> element to link to an external CSS file

The most common way to add CSS, is to keep the styles in external CSS files. However, in this tutorial we will use inline and internal styles, because this is easier to demonstrate, and easier for you to try it yourself.

Inline CSS

An inline CSS is used to apply a unique style to a single HTML element.

An inline CSS uses the style attribute of an HTML element.

The following example sets the text color of the <h1> element to blue, and the text color of the <p> element to red:

Example

Internal CSS

An internal CSS is used to define a style for a single HTML page.

An internal CSS is defined in the <head> section of an HTML page, within a <style> element.

The following example sets the text color of ALL the <h1> elements (on that page) to blue, and the text color of ALL the <p> elements to red. In addition, the page will be displayed with a "powderblue" background color:

Example

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

External CSS

An external style sheet is used to define the style for many HTML pages.

To use an external style sheet, add a link to it in the <head> section of each HTML page:

Example

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

The external style sheet can be written in any text editor. The file must not contain any HTML code, and must be saved with a .css extension.

Here is what the "styles.css" file looks like:

"styles.css":

Tip: With an external style sheet, you can change the look of an entire web site, by changing one file!

CSS Colors, Fonts and Sizes

Here, we will demonstrate some commonly used CSS properties. You will learn more about them later.

The CSS color property defines the text color to be used.

The CSS font-family property defines the font to be used.

The CSS font-size property defines the text size to be used.

Example

Use of CSS color, font-family and font-size properties:

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

CSS Border

The CSS border property defines a border around an HTML element.

Tip: You can define a border for nearly all HTML elements.

Example

Use of CSS border property:

CSS Padding

The CSS padding property defines a padding (space) between the text and the border.

Example

Use of CSS border and padding properties:

CSS Margin

The CSS margin property defines a margin (space) outside the border.

Example

Use of CSS border and margin properties:

Link to External CSS

External style sheets can be referenced with a full URL or with a path relative to the current web page.

Example

This example uses a full URL to link to a style sheet:

Example

This example links to a style sheet located in the html folder on the current web site:

Example

This example links to a style sheet located in the same folder as the current page:

You can read more about file paths in the chapter HTML File Paths.

Chapter Summary

  • Use the HTML style attribute for inline styling
  • Use the HTML <style> element to define internal CSS
  • Use the HTML <link> element to refer to an external CSS file
  • Use the HTML <head> element to store <style> and <link> elements
  • Use the CSS color property for text colors
  • Use the CSS font-family property for text fonts
  • Use the CSS font-size property for text sizes
  • Use the CSS border property for borders
  • Use the CSS padding property for space inside the border
  • Use the CSS margin property for space outside the border

Tip: You can learn much more about CSS in our CSS Tutorial.

HTML Exercises

HTML Style Tags

Tag Description
<style> Defines style information for an HTML document
<link> Defines a link between a document and an external resource

For a complete list of all available HTML tags, visit our HTML Tag Reference.

HTML Styles — CSS

CSS is used to style HTML. It determines how the HTML elements appear on the screen, paper, or in other media.

CSS saves a lot of work. It can control the layout of several pages all at once.

You can add CSS to HTML elements in 3 ways:

  • Inline, where the style attribute is used in HTML elements.
  • Internal, where the <style> element is used in the <head> section.
  • External, where an external CSS file is used.

Let’s look through each way.

Inline CSS

An inline CSS applies a particular style to a single HTML element. Here the style attribute of an HTML element is used.

In the example below the text color of the <p> element is red:

Example of the inline CSS:

Internal CSS

An internal CSS specifies a style for a single HTML page. It is defined in the <head> element of an HTML page, inside of a <style> tag:

Example of the internal CSS:

External CSS

An external style sheet specifies the style for multiple HTML pages. It can change the look of the whole website by changing just one file.

For using an external style sheet, you should add a link to it inside of the element of the HTML page:

Example of the external CSS sheet:

The file can’t contain any HTML code and must be saved with a .css extension.

CSS Fonts

The CSS color property describes the color of the text content.

The CSS font-family property defines the font of the text content.

The CSS font-size property defines the text size.

Example of the CSS fonts:

CSS Border

The CSS border property sets values to all four sides of an element.

Example of the CSS border property:

CSS Padding

The CSS padding property specifies padding (space) between the text and the border.

Example of the CSS padding property:

CSS Margin

The CSS margin property creates space around the element.

Example of the CSS margin property:

The id Attribute

The id attribute specifies a specific style for one element.

Example of the id attribute:

The Class Attribute:

The class attribute is used to specify a style for special kinds of elements.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *