Ways to connect CSS markup to HTML. What is CSS, connecting a CSS file

Connecting CSS occurs in several ways, which are used depending on the situation. Now we will look at these methods in more detail. There will be quite a lot of information, so don’t even try to memorize it, but be sure to try to figure out what’s what.

Yes, and one more point that was already touched upon in the previous lesson, but I will repeat it again. Often many beginners are afraid of the phrase “Cascading style sheets” or simply “style sheets”, so when they encounter such expressions in the text, it subconsciously seems to them that they do not understand what is being said. So, in fact, there are no tables in the form that you are used to - no. And these words describe only one thing - everything that relates to CSS, that is, various CSS rules, properties, values, and so on. In general, everything that we will study in this textbook. By the way, this can also include simply the words “CSS” and “styles”.

Built-in styles

Connecting built-in styles (inline) involves applying the style attribute to a specific tag on the page. In this case, the attribute value is one or more (separated by semicolons) with the corresponding values. As a rule, this method is used in cases where it is necessary to change the characteristics of a specific element on one specific page.

General syntax

<тег style="свойство:значение; свойство:значение; ...">...

An example of connecting inline styles to CSS

Connecting built-in styles

Paragraph 1

Paragraph 2

Result in browser

Paragraph 1

Paragraph 2

Internal styles

Internal styles are indicated in the header of the document and are connected using the tag. In this case, the CSS no longer affects one element, but all the elements specified in the styles that are present on this page. Typically, this method is used when it is necessary to change the styles of several identical elements within one HTML page.

An example of connecting internal styles to CSS

Connecting built-in styles

Paragraph 1

Paragraph 2

Result in browser

Paragraph 1

Paragraph 2

External styles

External styles are included in a separate file using the . In this case, all styles are located in a regular text file with the .css extension and affect the elements of all pages to which this file is connected. Usually, the creation of site styles begins with this method, since only with its help all the advantages of CSS are felt, because by changing the data in just one file you can control the display of a large number of pages at once. And already in the process of working on the site, internal or built-in styles are added, if necessary.

When using external styles, authors act in completely different ways. Some store all site styles in one file, others - in several. For example, one file contains styles for the entire site and is present on all pages, another is additionally connected only to certain sections, a third - to certain subsections, etc. What you do is up to you to decide.

Example of connecting external styles to CSS

Connecting external styles

Paragraph 1

Paragraph 2

Contents of the style.css file

Body ( background: #ccccff; /* page background color */ ) p ( color: red; /* paragraph text color */ font-family: Helvetica, sans-serif; /* paragraph font */ font-size: 150 %; /* font size */ text-align: center; /* centered text */ border: 5px green double; /* border styles */ )

Result in browser

Paragraph 1

Paragraph 2

As you can see, everything is very simple. In general, by the names of almost all CSS properties you can already understand what changes they make, of course, if you know at least a little English.

In most examples of this CSS tutorial I will use inner styles since they are the most visual for demonstration. For further study, it’s better for you to immediately create a file of external styles and get used to using them. For example, make a subfolder style , create a style.css file in it and connect it to your HTML page.

Including CSS via the @import rule

Another way to connect styles located in separate files is to use the rule . This rule is used to combine several style sheets into one, which is sometimes quite convenient. The connection occurs in external or internal style sheets; for this, after the rule name, the url() construction is written, where the address of the CSS file is indicated in quotes (" "). Or url() is not written at all, but quotes and the file address immediately appear. The general syntax is as follows.

In an external style sheet

@import url("file address"); @import "file address"; ...

In the inner

Let's look at the use of this rule in external style sheets, for this I will give you two examples for comparison.

Example 1: normal connection of external styles

External styles

Page content.

Example 2: connecting external styles together with the @import CSS rule

External styles with @import

Page content.

Contents of the style1.css file

@import url("style/style2.css"); @import url("style/style3.css"); Below here, in addition, there can be regular styles with properties, values, etc.

To rule worked correctly, it must be specified at the very beginning of the style sheet. The only exception is the rule here , which always comes first, although in practice it is used extremely rarely.

I don't recommend that you use all this variety of CSS methods right away - concentrate on regular external style sheets, as this is the main option. If you want, you can, of course, experiment, but nothing more. In general, you can always decide how to connect CSS, the main thing would be what to connect. :)

Custom styles

Many browsers have the ability to include a file with CSS by the users themselves, so that they can change the appearance of the sites they view, as they say, “to suit themselves.” For example, change the font size and typeface, the color of the text and background of some elements, etc. Naturally, in this case, styles are created by the user himself. For example, in Internet Explorer you can enable custom styles by going to: Tools → Internet Options → General → Appearance.

Any HTML document, no matter how many elements it contains, will essentially be “dead” without the use of styles. Styles or better yet cascading style sheets(Cascading Style Sheets) or simply CSS determine the presentation of the document, its appearance. Let's take a quick look at the use of styles in the context of HTML5.

A style in CSS is a rule that tells the web browser how to format an element. Formatting may include setting the element's background color, setting the font color and type, and so on.

A style definition consists of two parts: a selector, which points to an element, and a style declaration block, a set of commands that establish formatting rules. For example:

Div( background-color:red; width: 100px; height:60px; )

In this case the selector is div. This selector specifies that this style will be applied to all div elements.

After the selector, there is a style declaration block in curly braces. Between the opening and closing curly braces, commands are defined that indicate how to format the element.

Each command consists of a property and a value. So, in the following expression:

Background-color:red;

background-color represents the property, and red represents the value. The property defines a specific style. There are many CSS properties. For example, background-color specifies the background color. After the colon comes the value for this property. For example, the above command sets the background-color property to red. In other words, the background color of the element is set to “red”, that is, red.

After each command there is a semicolon, which separates this command from others.

Sets of such styles are often called style sheets or CSS(Cascading Style Sheets or cascading style sheets). There are different ways to define styles.

style attribute

The first way is to embed styles directly into the element using the style attribute:

Styles

Styles

There are two elements defined here - header h2 and block div. The title has a blue text color defined using the color property. At the block div width properties are defined ( width), height ( height), as well as the background color ( background-color).

The second way is to use the style element in the html document. This element tells the browser that the data inside is css code and not html:

Styles</title&g <style> h2{ color:blue; } div{ width: 100px; height: 100px; background-color: red; } </style> </head> <body> <h2>Styles</h2> <div></div> </body> </html> </p><p>The result in this case will be absolutely the same as in the previous case.</p> <p>Often element <b>style</b> defined inside the element <b>head</b>, however can also be used in other parts of the HTML document. Element <b>style</b> contains sets of styles. For each style, a selector is indicated first, after which the same definitions of css properties and their values ​​that were used in the previous example appear in curly braces.</p> <p>The second method makes the HTML code cleaner by placing styles in the style element. But there is also a third way, which is to transfer the styles to an external file.</p> <p>Let's create a text file in the same folder with the html page, which we will rename to styles.css and define the following content in it:</p><p>H2( color:blue; ) div( width: 100px; height: 100px; background-color: red; )</p><p>These are the same styles that were inside the style element. And also change the code of the html page:</p><p> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Styles

Styles

There is no longer an element here style, but there is an element link, which includes the above created file styles.css:

Thus, by defining styles in an external file, we make the html code cleaner, separating the page structure from its styling. When defined this way, styles are much easier to modify than if they were defined within elements or within an element style, and this method is preferred in HTML5.

Using styles in external files allows you to reduce the load on the web server using a caching mechanism. Because the web browser can cache the css file and the next time the web page is accessed, it can retrieve the desired css file from the cache.

It is also possible that all these approaches are combined, and for one element some css properties are defined inside the element itself, other css properties are defined inside the style element, and others are in an external included file. For example:

And in the style.css file the following style is defined:

Div( width:50px; height:50px; background-color:red; )

In this case, the div element has a width property defined in three places, with different values. What value will be applied to the element in the end? Here we have the following priority system:

  • If an element has built-in styles (inline styles) defined, then they have the highest priority, that is, in the example above, the final width will be 120 pixels
  • Next in order of priority are the styles that are defined in the style element
  • The least priority styles are those defined in an external file.

HTML attributes and css styles

Many html elements allow you to set display styles using attributes. For example, for a number of elements, we can use the width and height attributes to set the width and height of the element, respectively. However, this approach should be avoided and CSS styles should be used instead of inline attributes. It is important to clearly understand that HTML markup should provide only the structure of the HTML document, and its entire appearance and styling should be determined by CSS styles.

CSS Code Validation

In the process of writing CSS styles, questions may arise as to whether it is correct to define styles this way and whether they are correct. And in this case we can use the css validator, which is available at http://jigsaw.w3.org/css-validator/.
Here is a video tutorial on how to connect CSS to HTML

In this chapter we will talk about how to implement CSS into an HTML document, that is, link the style description of an element directly to the element itself, some HTML tag.

This task can be accomplished in three ways:

  • Write a style description directly in the element itself. This method is good only if there is only one such element in the HTML document that needs a separate style description.
  • Write a style description for all identical elements of the HTML document. This method is justified if the style of the page is fundamentally different from the overall design of the site (a group of interconnected pages).
  • Extract the style description of HTML elements into a separate CSS file. This will allow you to manage the design of the entire site, each page of the site in which a reference to a CSS file is indicated. This method is the most effective use of a cascading style sheet.

Let's take a closer look at each option, and at the same time get acquainted with the rules of CSS writing syntax.

The style attribute.

Almost every HTML tag has an attribute style, which indicates that a certain style description is applied to this tag.

It is written like this:

style="">

Everything that will be written between the attribute quotes style and will be a style description for this element, in this case the element

Well, for example:

style="color: #ff0000; font-size:12px"> this is a paragraph with a personal style

In this case, we specified that this paragraph should be displayed in red and have a font size of 12 pixels. In subsequent chapters I will talk in detail about what is written in quotes, but now we are talking about how to apply CSS to any HTML tag.

Using the same principle, you can specify an individual style for almost every HTML element.




style attribute

style="background-color: #c5ffa0">

style="color: #0000ff; font-size:18px">All about elephants



Buy an elephant


style="color: #ff0000; font-size:14px">


style="color: #0000ff; font-size:16px">Rent an elephant


style="color: #ff0000; font-size:14px">




But once again, this method of introducing CSS is good only if you need to set a certain style for a small number of HTML elements.

Tag (not to be confused with the attribute of the same name) in which the elements we need are described.

Take a look at the example, there will be comments below.




Style tag



All about elephants


On this site you will find any information about elephants.


Buy an elephant


With us you can purchase the best elephants at competitive prices!!


Rent an elephant


Only here you can rent any elephants!!




As can be seen from the example, we achieved exactly the same result as in the first case, only now we do not assign a style to each element individually, but placed it in the “head” of the document, thereby indicating that all headings

,

- the paragraphs will be blue

- red. Imagine how much easier our work would be if there were a hundred such paragraphs and about fifteen headings on a page, and the document itself would weigh less by “removing” all repeating style descriptions for each individual element.

Now the promised comments:

Tag the styles of certain HTML elements are directly declared according to the following syntax:

If several properties of an element are specified in a style declaration block, they are separated by a semicolon.

CSS in a separate external file.

How long does it take to short, we come to the main, in my opinion, advantage of CSS, namely the ability to put all information related to the design of the site into a separate external file.

So, open notepad (or another editor) and write the following text in it:

Body (background-color: #c5ffa0)
a (color:#000060; font-weight: bold;)
a:hover (color:#ff0000; font-weight: bold; text-decoration:none)
h1 (color: #0000ff; font-size:18px)
h2 (color: #ff00ff; font-size:16px)
p (color: #600000; font-size:14px)

I will try to tell you in detail about what we wrote about this strange thing in the subsequent chapters of this textbook.

All! The style description file has been created! Now all that remains is just a little bit, namely to force the necessary pages of our site to draw information from this file.

This is done using the tag (connection). Tag multi-purpose and serves to “link” an HTML document with additional external files that ensure its proper operation. Tag is a kind of link, only intended not for users, but for browser programs (browsers). Because carries exclusively service information; it is located in the head of the HTML document between the tags and is not displayed on the screen by browsers.

Tag has attributes:

href- The path to the file.
rel- Defines the relationship between the current document and the file being referenced.
  • shortcut icon - Specifies that the included file is a .
  • stylesheet- Specifies that the included file contains a style sheet.
  • application/rss+xml - A file in XML format to describe the news feed.
type- MIME data type of the attached file.

Since we include a cascading style sheet as an external file, our service link takes the following form:

I repeat, to certainly dispel possible misunderstandings. Attribute rel assign a value stylesheet Since we are connecting a cascading style sheet as an external file, we indicate the path to the css file (in this example the file is called mystyle.css and lies next to the HTML document in which this link is written) we also indicate that this file is text and contains a style description type="text/css"

Now we insert this line into the page headers of our site and enjoy the result..

mystyle.css file
body (background-color: #c5ffa0)
a (color:#000060; font-weight: bold;)
a:hover (color:#ff0000; font-weight: bold; text-decoration:none)
h1 (color: #0000ff; font-size:18px)
h2 (color: #ff00ff; font-size:16px)
p (color: #600000; font-size:14px)
Index.html file



cascading style sheet



Menu:


All about elephants.
Buy an elephant.
Rent an elephant.


All about elephants


On this site you will find any information about elephants.




File elephant.html



cascading style sheet



Menu:


All about elephants.
Buy an elephant.
Rent an elephant.


Buy an elephant


With us you can purchase the best elephants at competitive prices!!




File elephant1.html



cascading style sheet



Menu:


All about elephants.
Buy an elephant.
Rent an elephant.


Rent an elephant


Only here you can rent any elephants!!




In the example above, "site about elephants", there are currently three pages, each of which is associated with one single external css file - mystyle.css. Thus, we significantly “unloaded” it and made the design of the entire site “mobile-friendly”. Imagine how many kilobytes we would win if this site had a hundred full-fledged pages!? And also, how much time would we save if we needed to change anything in its design!?

In this chapter, we looked at three ways to embed CSS in an HTML document. Which one is better to use?

  • Use attribute style for any element, if this element with a different style from other elements is the only one on the entire site.
  • Use tag . You need to add a style sheet to every web page. If the site has a large number of pages that require the same design, then adding and editing styles becomes a thankless job - the process will take a very long time. Therefore, internal style sheets are considered inconvenient.

    External style sheets are much more common. You only need to connect the table to all the necessary web pages using the tag with the rel attribute (defines the relationship between the page and the included file) and the stylesheet value, which means that the included file contains a style sheet. The href attribute is the path (URL) to your .css file:

    By editing just one file, you can change the style for the entire site at once, regardless of how many pages there are. This is very convenient, especially for large resources.

    Lesson: creating a style sheet

    Since external style sheets are the most convenient and widely used in design development, we will learn how to create them. You can download the archive with files for this lesson on this page.

    In the folder you will find an HTML document with an example of a simple page and an image (to be used in the tutorial). Open the HTML document in your browser. You will see that the page looks completely normal. To give it a more attractive look, let's style it.

    For now, you don't need to delve too deeply into what any given piece of code means. Now you need to understand the principle of operation. Let's get started.

    Connecting CSS to HTML

    To begin, open any text editor on your computer (notepad will do) and create an empty file called style , saving it with the .css extension (you should end up with a style.css file). Save the file in the folder where the downloaded HTML document is located.

    Open the HTML document in a text editor, as well as in a browser (to easily view changes in the appearance of the page). Add between tags the following code:

    Briefly summarize what you just did. By pasting this code into an HTML document, you:

    • provided a link to a font called Roboto Condensed, which will be taken from the Google server (we will tell you more about Google fonts later);
    • connected our external style sheet style.css (empty for now).

    Writing CSS style

    Save your changes to the HTML document and go to the empty .css file you created. Let's add some styling to the page:

    Html ( padding-top: 5px; background-image: url(background.jpg); )

    Save your changes. Congratulations, you have written your first rule - it concerns the tag . The first property - padding-top - will add a top padding of 5 pixels between the browser window and the web page content. With the second property, background-image , you have included an image for the background of the entire page by specifying the path to the graphic file (located in the same folder as the HTML document).

    Refresh the open web page in your browser. If everything is done correctly, you will see that a background has appeared on the page, and the space between the top of the window and the text has increased slightly.

    Body ( width: 75%; padding: 40px; margin: 15px auto; background-color: #EBEBEB; border-radius: 30px; )

    Save the changes to the file. Now you:

    • set the area for the tag content , which is equal to 75% of the browser window width;
    • provided a margin of 40 pixels from all sides of the content area;
    • positioned the area in the center of the page, and also made an indentation at the top and bottom of 15 pixels;
    • set the background color #EBEBEB for the content area;
    • rounded the corners of the rectangular area, specifying a rounding radius of 30 pixels.

    Update the HTML document again. At the same time, make sure that the cache is disabled or reload the page with all files associated with it updated, using a special key combination (for example, for Chrome this is Ctrl+F5).

    You will see that a rectangular area with rounded corners has been added to the center of the page. This is the result of your actions in the CSS file. You can also try making your browser window smaller and admire how the width of the rectangular area adjusts to its size. This is due to the fact that width is specified as a percentage.

    Changing the font using CSS

    It's time to decorate our text. Add this code to your stylesheet and save your changes:

    H1 ( color: #E87E04; font-size: 2em; margin-left: 20px; font-family: "Roboto Condensed", sans-serif; ) h2 ( color: #E87E04; font-size: 1.7em; margin-left : 20px; font-family: "Roboto Condensed", sans-serif; ) p ( color: #22313F; line-height: 150%; margin-top: 20px; margin-left: 20px; font-family: "Roboto Condensed ", sans-serif; )

    Having written this, you set the font colors for the h1 , h2 , p tags, indicated their sizes, added a margin from the left edge of 20 pixels and additionally for

    We indented the top by 20 pixels and set the line-height (line spacing of the text) to 50% larger than the standard one. In addition, you connected the Roboto Condensed font to all three tags (that’s why you had to provide a link to it in the HTML file at the very beginning).

    Refresh the page in your browser and admire the result. In this tutorial we will try one more thing. Add this code to CSS:

    Emphasis ( font-weight: bold; )

    Save and refresh the page in your browser. You will see that in the last paragraph the font has become bold in some parts of the text. To understand what happened, go to the text editor window where you opened the HTML file at the very beginning. Look at the last paragraph: part of the sentence is wrapped in a tag with the emphasis class. This way you have written a style for a single line of text in a paragraph. We'll talk more about classes in the next chapter.

    You should end up with a page like this:



    As a practice, try changing the text size for

    (let's say 1.1em), and also increase the space between

    And the left edge of the content area by another 10 pixels.

    conclusions

    This chapter looked at CSS syntax and how to create a basic style sheet. You learned how to incorporate CSS into an HTML page and how to create simple styles. Let's highlight the main things you need to remember from this chapter:

    Any CSS style consists of several elements: a selector, a style property, and the value of this property.

    All properties and their values ​​are written in a declaration block between two curly braces () after specifying the selector.

    You need to carefully follow the signs: two curly braces (opening at the beginning of the ad block and closing at the end). Without these brackets, CSS will not work correctly.

    It is required to place a colon after the property and a semicolon after the value.

    For convenience and better readability of your CSS code, write each property on a new line, and don't skimp on spaces and tabs.

    Now it is difficult to imagine changing the appearance and formatting of HTML documents without using CSS style sheets, since HTML has long ceased to be a self-sufficient language for design and began to perform its original functions of structuring and marking up web documents. In this article, we'll detail the different ways you can incorporate CSS into an HTML document.

    Briefly about CSS and HTML

    Previously, web pages were designed exclusively using HTML. Nowadays this approach is not practiced, and CSS tools are used for styling, which have very wide possibilities for creating stunning designs.

    In order for the site design to be displayed correctly, you need to connect CSS to the HTML document; these tools work inseparably from each other - HTML creates the structure, and style sheets are responsible for the appearance.

    There are several basic ways in which you can customize the display of styles in your HTML code, each with its own pros and cons.

    Connecting the CSS file

    This is the main method that is considered by developers as the most practical and convenient.

    Using this method, you can quickly change the design of a web page if there is a given structure of the HTML document - for example, for the same site you can write several design options and connect them depending on the corresponding need.

    In order to include a file with styles, you must first configure the file structure - this is done so that you can write the correct path to the desired document directly in the code.

    Create a directory where the main HTML document will be located, in the same folder create a file called style in a text editor and save it in .css resolution. It will contain CSS code with all the specified document styling rules.

    The CSS connection is done using an HTML tag with the href attribute. It looks like this:

    Here the code is located in what is considered optimal, but not required. It can be located anywhere in the document.

    This method is convenient because all changes to the style sheet are made in a separate file, which makes the code easier to understand and readability and makes the document neater.

    If you make changes to style.css and open index.html in the browser, you will be able to see all the changes that have been entered.

    In the same way, you can set not only the path to the file in the site structure, but also a link to the page with the style located on the Internet. In this case, it also fits in quotation marks after the href attribute.

    The method of including a style sheet from a separate file optimizes the performance of the site, as it allows the browser to load data from the cache, as a result of which pages load faster.

    Style sheets inside an HTML document

    Sometimes the value of a style parameter is set directly in the body of the HTML document using the style attribute.

    Syntax:

    The text in this paragraph is red

    The obvious drawback is the lack of universality; you will have to specify a value for each tag.

    Also, connecting using internal style sheets does not allow the browser to cache information, unlike the previous method.

    Global style

    If you need to style a specific element throughout an HTML document, use the tag

    The specified style will be applied to the tag

    , as soon as it is registered on the page.

    Including CSS this way will be read in higher priority by the browser than the external style sheet.

    How to add a font to a website

    Font is one of the main design elements of any web page. The impression that a website makes on a user directly depends on the font used. Fortunately, you don’t have to limit yourself to standard headsets; you can connect any others - we’ll tell you how this is done.

    Using CSS, fonts are connected as follows:

    • Find and download a suitable headset.
    • Open the CSS file and write the following code in it:
    @font-face ( font-family: "Open Sans"; src: url("../fonts/OpenSans.ttf") format("truetype"); font-style: normal; font-weight: normal; )

    First, the name of the font is specified, then the path to it, and finally the parameters. Please note that in this example, the font file is located in the fonts folder, which, in turn, is located in the root directory. For convenience, it is better to create separate folders for various files and elements (images, scripts, style sheets, etc.).

    So, in the fonts folder we have a file called OpenSans.ttf, with the usual parameters. It will now be displayed in the browser.

    Connecting the font via Google Fonts

    One of the most common ways to include fonts in CSS and HTML is the Google Fonts service.

    The interface is intuitive - you need to find a suitable font by name or specified parameters, click the Select this font button, and the service instantly generates a code that is inserted into the tag field HTML document, as well as the corresponding CSS file with styles.

    How it should look in HTML:

    And in the CSS file with styles:

    Font-family: "Open Sans", sans-serif;

    This method is convenient because it allows you to quickly find the desired font from a very large database and saves a lot of time, as well as eliminates problems that arise due to incorrect display of fonts in some browsers.

    Let's sum it up

    So, we looked at the main ways to connect CSS styles to HTML documents. Based on the tasks set before the developer in each specific case, you can choose the highest priority option.

    Designing web pages is a creative process that requires, however, a careful approach. Take advantage of the ability to comment on code and don’t forget about website optimization.