In which folder are the css files? Absolute and relative links. Connecting multiple CSS files to one HTML document
Hello everyone, friends. Today I will answer the simplest question: “how to connect a css style sheet to an html page?”
Video version of the article:
To do this, you need to insert the following line into the content of the tag:
Let me explain: The link tag allows you to connect external files to the page. The rel = “stylesheet” attribute gives instructions that the included file is a style sheet. Href is the path to the styles file. As a rule, its value is “style.css” if the style sheet is called that way and lies in the same folder as the html page for which it is connected.
How to specify the path to a file
Accordingly, if the css file is located somewhere else, then the path to it is written differently. Examples to make it clearer:
The table.css file is located in the styles folder, which is located in the same folder as the html page: href = “styles/table.css”
The fonts.css file is located in the styles folder, which is located in the css folder, which in turn is located where the html page is: href = “styles/css/fonts.css”
Two dots allow you to indicate the path back from the original location (from the place where our html page is located). So you can reach it like this:
Href = “../style.css” – the file is one level above the html file.
Href = “../../style.css” – two levels higher.
Href = “../../../css/style.css” – three levels higher + the style file itself is also located in the css folder.
I hope you understand these simple examples in order to fully understand how to set the path to a file.
Deprecated attribute
Previously, when connecting a style sheet, it was also necessary to specify the type = “text/css” attribute in the link tag, but today this is no longer a mandatory requirement - browsers already understand everything perfectly well. However, for full support in older browsers, you can play it safe and still add it.
Which we will now consider in order.
As I said earlier, css is designed to design html structures, that is, give them appearance, color, size, location, and so on, and therefore directly influence the html code.
To ensure this effect, a css connection is made to the html document.
The first way to include css is linked styles. It is used when the style sheet is written in a separate file.
In this case, the style.css file with the style sheet is connected to the html file in the head tag, using the link tag
<link href ="css/style.css " type ="text/css " rel ="stylesheet ">
link is a single tag;
href – a link attribute familiar to us, css/stile.css – a value indicating the path to the file, and the name of the file;
type – an attribute indicating the type of element to be connected, in our case it is text/css;
rel is an attribute that defines a relationship, and its value is usually written stylesheet;
In this code, usually only the value of style.css (the name of the connected table) changes. Tables are connected.
Now the browser will display the html file in the form that will be written for it in the style.css file.
By the way, for the future. You can connect as many style sheets as you like to one html file. All of them are included in the head tag.
And, what is used much more often, on the contrary, one table can be connected to many html files.
This is the most preferred way to include style sheets, since they are all in one file and therefore easier to define.
And also, if you have to change the style of several elements of the same type, it will be much easier to do this if they are collected in one group selector.
The fact is that one of the webmaster’s tasks is to reduce the amount of code while maintaining the same final result, and a separate style.css file most fully meets this requirement.
Just imagine, to write a title for an article, you need to set its size, color, font and, possibly, some other styles. And so for each post.
In the style.css file, you can set styles once, but for all post titles on the site.
Now do you understand the difference?
Nevertheless, other methods of connecting styles have a right to exist, so let's look at them and the situations in which they are used.
The second way to connect css is global styles allows you to connect (place) a style sheet directly in an html file.
This is done using the style tag, and it is written in the same way as in the first case in the head tag.
Как видите, таблица стилей расположена прямо в html файле. Всё это работает так-же, как и при первом способе подключения, но применяется реже, из за громоздкости, и главное, из-за невозможности воздействия стилей на несколько файлов.
Когда его применять? Я, например использую этот способ при создании дизайна в редакторе файлов.
Гораздо проще отлаживать документ, если и html и css находятся на одной странице и можно быстро подправить и то, и другое.
Третий способ подключения css — внутренние стили позволяет прописывать стили прямо внутри html тега.
Реализуется он при помощи атрибута style , который не стоит путать с одноимённым тегом.
Применяется он тогда, когда нужно оформить только один элемент контента.
Для примера возьмём кусочек текста, и зададим ему стили, заключив в тег span
В этой части самоучителя мы познакомимся с новыми для вас терминами, которые используются при описании папок и HTML-элементов.
Примечание: папку также часто называют директорией или каталогом.
Структура сайта
Не держите все файлы в одной папке. Даже небольшими сайтами намного проще управлять, если разложить HTML документы , изображения и другие ресурсы в разные папки, создав тем самым определенную структуру расположения различных файлов. Структурируя файлы как вам удобно, вы можете выбрать для себя достаточно гибкую систему организации файлов, учитывая то, что сайт может расти, система файлов при этом будет оставаться ясной и понятной. Структуру (иерархию) каталогов, в которых располагаются различные файлы, обычно можно увидеть в виде древа. Рассмотрим в качестве примера следующее изображение.
Как вы видите, структура - это всего лишь схема, отображающая вложенность одних каталогов в другие. В примере мы использовали всего три каталога, однако этого будет достаточно для того, чтобы описать всю необходимую информацию. Часто каталоги описывают с помощью терминов наследственных (семейных) связей. У нас есть папка под названием "Бананы", она расположена внутри папки "Фрукты". Папка "Фрукты" - это родитель каталога "Бананы", а каталог "Бананы" - ребенок (дочерний каталог) папки "Фрукты". Также у нас есть еще папка "Киви", которая является тоже ребенком каталога "Фрукты".
Чтобы вам лучше запомнить, опишем термины отдельно:
- Дочерний каталог - это папка, над которой в иерархическом древе есть родительский каталог.
- Родительский каталог - это папка, содержащая другой каталог.
- Есть еще такое понятие как "корневой каталог" - это основная (главная) папка, в которой расположены все прочие каталоги и файлы.
Структура элементов
Структуру элементов также можно представить в виде схемы, отображающей вложенность одних элементов в другие. Рассмотрим простой пример:
A diagram showing the nesting of elements can be represented as follows:
- Child element is an element that has a parent element above it in the hierarchical tree. A child element is also called child.
- Related element is another child element of the same parent element at the same branch level. Such elements are also called sisterly, in the example such elements are And ,
And