- HTML Стили
- Способы добавления CSS стилей
- Внешняя таблица стилей
- Пример: Внешняя таблица стилей
- Внутренняя таблица стилей
- Пример: Внутренняя таблица стилей
- Встроенный стиль
- Пример: Приоритетность стилей
- Задачи
- Выравнивание текста по центру
- Задача HTML:
- Цвет фона страницы
- Задача HTML:
- Тип шрифта для страницы
- Задача HTML:
- Внешняя таблица стилей
- Задача HTML:
- CSS Tables
- Table Styling Properties
- Example of styling a table:
- Result
- Table color
- Collapse Borders
- Table Width and Height
- Table Text Alignment
- Table Padding
- Horizontal alignment with the text-align property
- Example of aligning the content of and elements to the right:
- Vertical alignment with the vertical align-property
- Example of the vertical alignment of elements’ content to bottom:
- Horizontal dividers
- Example of creating horizontal dividers:
- Hoverable tables
- Example of creating a hoverable table:
- Zebra-striped table
- Example of creating a zebra striped table:
- Responsive tables
- Example of creating a responsive table:
- CSS Tables
- Table Borders
- Example
- Full-Width Table
- Example
- Double Borders
- Collapse Table Borders
- Example
HTML Стили
CSS (Cascading Style Sheets), или каскадные таблицы стилей, используются для описания внешнего вида веб-документа, написанного языком разметки. CSS устанавливает стилевые правила, которые изменяют внешний вид элементов, размещенных на веб-страницах, выполняют тонкую настройку их деталей, таких как цвет, шрифт, размер, границы, фон и местоположение в документе.
Вы можете встроить CSS-код непосредственно в элемент разметки в виде значения атрибута style. Этот атрибут доступен для всех элементов HTML. С помощью CSS можно указать ряд свойств стиля для данного HTML-элемента. Каждое свойство имеет имя и значение, разделенные двоеточием (:). Каждое объявленное свойство отделяется точкой с запятой (;).
Вот как это выглядит для элемента
:
Пример: применение стилей к элементу
Способы добавления CSS стилей
Стандарт CSS предлагает три варианта применения таблицы стилей к веб-странице:
- Внешняя таблица стилей — определение правил таблицы стилей в отдельном файле .css, с последующим подключением этого файла в HTML-документ с помощью тега .
- Внутренняя таблица стилей — определение правил таблицы стилей с использованием тега , который обычно располагается в разделе HTML-документа .
- Встроенный стиль — это способ вставки языка таблицы стилей прямо в начальный тег HTML-элемента.
Давайте познакомимся со всеми тремя способами на конкретных примерах.
Внешняя таблица стилей
Давайте поместим эти три строки CSS в новый файл в любом текстовом редакторе (например Notepad++), а затем сохраним файл как style.css в папке styles. Чтобы применять CSS к нашему HTML-документу, вставьте следующую строку в шапку, то есть между тегами
и :Пример: Внешняя таблица стилей
Текст первый
Текст второй
Текст третий
Текст первый
Текст второй
Текст третий
Внутренняя таблица стилей
Данный стиль определяется в самом HTML-документе и обычно располагается в заголовке веб-страницы HEAD. По своей гибкости и возможностям этот способ подключения стилей уступает предыдущему, но также позволяет размещать все стили в одном месте. В данном случае, стили разполагаются прямо в теле HTML-документа. Вы можете включить правила CSS в НТМL-страницу, поместив их внутри элемента , который обычно находится в элементе , но фактически может быть помещен в любом месте документа. Этих тегов на странице может быть несколько.
Тег позволяет записывать внутри себя код в формате CSS:
Пример: Внутренняя таблица стилей
Заголовок
Текст первый
Текст второй
Текст третий
body < background-color:palegreen; >h1 < color: blue; font-family:verdana; >p Заголовок
Текст первый
Текст второй
Текст третий
В данном примере мы с помощью CSS установили цвет фона для элемента : background-color:palegreen, цвет и тип шрифта для заголовков : color: blue; font-family:verdana, а также размер шрифта, цвет и выравнивание текста по центру для параграфов
: font-size:20px; color:red; text-align:center.
Встроенный стиль
Когда необходимо отформатировать отдельный элемент HTML-страницы, описание стиля можно расположить непосредственно внутри открывающего тега при помощи уже специализированного атрибута style. Например:
Такие стили называют встроенными (inline), или внедренными. Правила, определенные непосредственно внутри открывающего тега элемента перекрывают правила, определенные во внешнем файле CSS, а также правила, определенные в элементе .
В следующем примере к HTML-документу подключены все три рассмотренные стиля форматирования:
Пример: Приоритетность стилей
Заголовок
Текст первый
Текст второй
Текст третий
body < background-color:palegreen; >h1 < color: blue; font-family:verdana; >p Заголовок
Текст первый
Текст второй
Текст третий
Чем ближе описание стиля находится к элементу, тем более высокий приоритет имеет этот стиль при выборе браузером конечного правила оформления. |
Задачи
Выравнивание текста по центру
Задача HTML:
Это параграф.
Цвет фона страницы
Задача HTML:
body h1 p Заголовок
Параграф
Тип шрифта для страницы
Задача HTML:
body h1 p Заголовок
Параграф
Внешняя таблица стилей
В папке styles находится файл со стилями style.css. Подключите стилевой файл (внешняя таблица стилей) к HTML-документу.
Задача HTML:
Параграф первый
Параграф второй
Параграф третий
CSS Tables
Some of the CSS properties are widely used to apply style on HTML tables. Each of them is described below.
In this chapter, we will talk about how to give styles to tables. We can change the color of headings and rows that we want.
Table Styling Properties
Here are CSS properties that we use for applying a style to the table. The background-color and color properties set the background color and the color of the text, respectively. The border-collapse property makes the table borders collapse. The text-align property sets the text position. Also, we should use the height, width and padding properties for styling.
Example of styling a table:
html> html> head> title>Title of the document title> style> table < width: 100%; border-collapse: collapse; > table, th, td < border: 1px solid black; > thead < background-color: #1c87c9; color: #ffffff; > th < text-align: center; height: 50px; > tbody tr:nth-child(odd) < background: #ffffff; > tbody tr:nth-child(even) < background: #f4f4f4; > style> head> body> table> thead> tr> th>Heading th> th>Heading th> tr> thead> tbody> tr> td>Some text td> td>Some text td> tr> tr> td>Some text td> td>Some text td> tr> tr> td>Some text td> td>Some text td> tr> tr> td>Some text td> td>Some text td> tr> tbody> table> body> html>
Result
Let’s explain the above code.
As you see our table has 2 parts: the first is the part where we have written headings, which is our part and the second part is the part where we have written some text. The table has black borders, for which we use border property. We can use any color we want as well as we can choose the style of borders.
Table color
As you see the part of our table is blue and wherever we write some text is in white. For the blue background, we use the background-color property, and for the white text, we use the color property. The other texts are written with black.
Collapse Borders
The border-collapse property specifies whether the borders of a table are collapsed into a single border or separated.
Table Width and Height
The table also has width and height properties. As you see we use these properties in our style. We use the width property for the whole table and the height property for the headings. We can use these properties with pixels and percents.
Table Text Alignment
Now about the table text alignment. As you know earlier we used the text-align property for the text position. In our example, as you see, we use the text-align property for the heading. For that, we use «text-align: center». You can read our previous chapter to know how to use it.
Table Padding
To control the space between the border and content in a table, use the padding property on and elements:
Horizontal alignment with the text-align property
Example of aligning the content of and elements to the right:
html> html> head> title>Title of the document title> style> table, td, th < border: 1px solid black; > table < border-collapse: collapse; width: 100%; > th, td < text-align: right; > style> head> body> h2>Horizontal alignment example h2> table> tbody> tr> th>Firstname th> th>Lastname th> th>Money th> tr> tr> td>Sherlock td> td>Holmes td> td>$200 td> tr> tr> td>John td> td>Watson td> td>$250 td> tr> tr> td>Mary td> td>Whatson td> td>$500 td> tr> tbody> table> body> html>
Vertical alignment with the vertical align-property
Example of the vertical alignment of elements’ content to bottom:
html> html> head> style> table, td, th < border: 1px solid black; > table < border-collapse: collapse; width: 100%; > td < height: 50px; vertical-align: bottom; text-align: right; padding-right: 10px; > style> head> body> h2>Vertical alignment example h2> table> tr> th>Firstname th> th>Lastname th> th>Money th> tr> tr> td>Sherlock td> td>Holmes td> td>$300 td> tr> tr> td>John td> td>Watson td> td>$250 td> tr> tr> td>Mary td> td>Watson td> td>$500 td> tr> table> body> html>
Horizontal dividers
Example of creating horizontal dividers:
html> html> head> title>Title of the document title> style> table < border-collapse: collapse; width: 100%; > th, td < padding: 10px; text-align: left; border-bottom: 1px solid #cccccc; > style> head> body> h2>Horizontal dividers example h2> table> tr> th>Firstname th> th>Lastname th> th>Money th> tr> tr> td>Sherlock td> td>Holmes td> td>$200 td> tr> tr> td>John td> td>Watson td> td>$350 td> tr> tr> td>Mary td> td>Watson td> td>$500 td> tr> table> body> html>
Hoverable tables
Example of creating a hoverable table:
html> html> head> title>Title of the document title> style> table < border-collapse: collapse; width: 100%; > tr < background-color: #f5f5f5; > th, td < padding: 15px; text-align: left; border-bottom: 1px solid #ccc; > tr:hover < background-color: #cdcdcd; > style> head> body> h2>Hoverable table example h2> table> tr> th>First Name th> th>Last Name th> th>Money th> tr> tr> td>Sherlock td> td>Holmes td> td>$200 td> tr> tr> td>John td> td>Watson td> td>$350 td> tr> tr> td>Mary td> td>Watson td> td>$500 td> tr> table> body> html>
Zebra-striped table
Using the nth-child() selector and adding the CSS background-color property to the odd (even) table rows, you can create a zebra-striped table.
Example of creating a zebra striped table:
html> html> head> title>Title of the document title> style> table < border-collapse: collapse; width: 100%; > th, td < text-align: left; padding: 10px; > tr:nth-child(even) < background-color: #6eeccf; > tr:nth-child(odd) < background-color: #2d7f88; > style> head> body> h2>Striped table example h2> table> tr> th>First name th> th>Last name th> th>Points th> tr> tr> td>Sherlock td> td>Holmes td> td>$250 td> tr> tr> td>John td> td>Watson td> td>$350 td> tr> tr> td>Mary td> td>Watson td> td>$500 td> tr> table> body> html>
Responsive tables
Example of creating a responsive table:
html> html> head> title>Title of the document title> style> div < overflow-x: auto; > table < border-collapse: collapse; width: 100%; > th, td < text-align: left; padding: 8px 5px; > tr:nth-child(even) < background-color: #6eeccf; > tr:nth-child(odd) < background-color: #2d7f88; > style> head> body> h2>Responsive table example h2> div> table> tr> th>First Name th> th>Last Name th> th>Money th> th>Money th> th>Money th> th>Money th> th>Money th> th>Money th> th>Money th> th>Money th> th>Money th> th>Money th> tr> tr> td>Sherlock td> td>Holmes td> td>$150 td> td>$150 td> td>$150 td> td>$150 td> td>$150 td> td>$150 td> td>$150 td> td>$150 td> td>$150 td> td>$150 td> tr> tr> td>John td> td>Watson td> td>$350 td> td>$350 td> td>$350 td> td>$350 td> td>$350 td> td>$350 td> td>$350 td> td>$350 td> td>$350 td> td>$350 td> tr> tr> td>Mary td> td>Watson td> td>$500 td> td>$500 td> td>$500 td> td>$500 td> td>$500 td> td>$500 td> td>$500 td> td>$500 td> td>$500 td> td>$500 td> tr> table> div> body> html>
CSS Tables
The look of an HTML table can be greatly improved with CSS:
Company | Contact | Country |
---|---|---|
Alfreds Futterkiste | Maria Anders | Germany |
Berglunds snabbköp | Christina Berglund | Sweden |
Centro comercial Moctezuma | Francisco Chang | Mexico |
Ernst Handel | Roland Mendel | Austria |
Island Trading | Helen Bennett | UK |
Königlich Essen | Philip Cramer | Germany |
Laughing Bacchus Winecellars | Yoshi Tannamuri | Canada |
Magazzini Alimentari Riuniti | Giovanni Rovelli | Italy |
Try it Yourself »
Table Borders
To specify table borders in CSS, use the border property.
Firstname | Lastname |
---|---|
Peter | Griffin |
Lois | Griffin |
Example
Full-Width Table
Firstname | Lastname |
---|---|
Peter | Griffin |
Lois | Griffin |
Example
Double Borders
To remove double borders, take a look at the example below.
Collapse Table Borders
The border-collapse property sets whether the table borders should be collapsed into a single border:
Firstname | Lastname |
---|---|
Peter | Griffin |
Lois | Griffin |
Example
Firstname | Lastname |
---|---|
Peter | Griffin |
Lois | Griffin |