How to set up smartphones and PCs. Informational portal

Correct css. Inline CSS - style attribute

CSS, like any language, has its own syntax. It has no elements, no parameters, no tags. It has rules. A rule consists of a selector and a style declaration block enclosed in curly braces:

The style declaration block itself consists of properties and their values, separated by semicolons:

Let's try it in practice. Open the html page and css page created in the last tutorial. Let's give our page a blue background. As you remember, the tag is responsible for this. , so go to the style.css page and write the following code:

body (background: blue;)

Open your html page in a browser and make sure its background turns blue. Now, let's make the text on the page white:

body (background: blue; color: white;)

Refresh the html page in the browser (Ctrl + F5) and make sure all the text is now white... Now let's make the heading colors red (for h1) and yellow (for h2):

body (background: blue; color: white;) h1 (color: red;) h2 (color: yellow;)

Refresh the page in your browser again and make sure everything is as intended.

I think the principle is already clear: we specify the selector, i.e. the element to which the style is applied, and in curly braces- its properties and their meanings. Properties and values ​​will be devoted to separate lessons, while we are considering general principle compiling a style sheet.

CSS selectors

ID selectors

In our example, the page elements were used as selectors: body, h1, h2. But what if our html page has several identical elements (for example, paragraphs), and we want the text of all paragraphs to be black, and one of them - pink... Then we need to specify a unique identifier for this paragraph and create a style for it.

In HTML, the element identifier is set using the parameter id, the value of which is a unique name. For instance:

The text of the paragraph with the identifier (id).

You can give any names, except for reserved words (these include the names of tags and parameters of HTML and CSS elements), for example, you cannot give an identifier the name body. Let's add a couple of paragraphs to our html page and assign an identifier to one of them: If you look at our page in a browser now, our paragraphs are both white. Let's add the styles for our paragraphs to the stylesheet (style.css):

body (background: blue; color: white;) h1 (color: red;) h2 (color: yellow;) p (color: black;) p # pink (color: pink;)

We first indicated to make the text of all paragraphs black, and the text of the paragraph with id "pink" make it pink. Our selector is in this case from element ( p), separator ( # ) and identifier name ( pink).

It is important to remember that there can be only one identifier (id) on a page. Those. for our example, you cannot create two paragraphs with id "pink", a paragraph with such id there can be only one. But each paragraph can have its own identifier, for example, you can create a paragraph with id = "green" and set the style for this paragraph in the stylesheet.

Class selectors

In the example above, we created a paragraph with pink text color and indicated that there can only be one such id. But what if we want to pink color the text had two or three paragraphs. For this in HTML there is a parameter class, the value of which is its name.

Let's add a couple more paragraphs to our html page and assign them class = "pink": In order to specify the style for this class, in the style sheet we will write a rule where the element will again be used as a selector p and name pink, but in this case it is the class name, so a period (.) will be used as a separator:

body (background: blue; color: white;) h1 (color: red;) h2 (color: yellow;) p (color: black;) p # pink (color: pink;) p.pink (color: pink;)

There can be as many paragraphs with such a class.

Let's summarize:

  • if all similar elements (for example, all h1 headers) must have the same style, then the selector consists only of that element (for example, p (color: black;))
  • if an element (any: paragraph, heading ...) should be different from all the others, then it is assigned an identifier ( id) and the separator in the style sheet is the pound sign ( # ), For example, p # pink (color: pink;) .
  • if there are several elements on the page with the same style, then they are assigned the class ( class) and the style sheet separator is a period (.), for example p.pink (color: pink;).
  • the identifier takes precedence over the class. Therefore, if both the class and the identifier are specified for any element (which does not contradict CSS principles), then the style of the identifier will be applied.
As already mentioned, identifiers and classes can be set on any html element. But it often happens that we want to highlight several different elements with one style, for example, in green... In this case, you can use unified selector... In such selectors, the element name is not specified, a period or pound is specified as a class or identifier attribute and a name. For instance:

Red (color: red;) #yellow (color: yellow;)

Thus, no matter which element we set class = "red"(heading, paragraph or link), its text color will turn red. We can set one element on the page (any) id = "yellow" and the text color of that element turns yellow.

Context selector

Suppose we have an html page with the following code: We want the italics to be highlighted in green as well. Then we will write an element selector to the stylesheet, i.e.

i (color: green;)

Now our page looks like this in the browser:

But what if we want not all italicized text to be highlighted in green, but only the one that is in the paragraphs. To do this, we will make changes to the stylesheet:

p i (color: green;)

So we indicated, apply given style to the elements i that are in elements p... The names of the elements are separated by a space. Such selectors are called contextual... Our browser page now looks like this:

Selector grouping

If the style declaration blocks for several selectors are the same (for example, we want the headings of the first three levels to be green), then they can be grouped. To do this, the selectors to which the same style will be applied must be listed separated by commas. Example:

h1, h2, h3 (color: green;)

Let's say that in addition to color, we want to give our titles a size. Then we can just add to our stylesheet:

h1, h2, h3 (color: green;) h1 (font-size: 18px;) h2 (font-size: 16px;) h3 (font-size: 14px;)

Our headers will have indicated size, but they will all be green.

Actually, there are disagreements about the factions. Some consider the above code to be correct, since grouping helped avoid replay the same property for three elements, this shortens the code.

Others believe that in this way the consistency of the code deteriorates. Since, having found a selector for the h3 heading, it is not immediately clear why the text in it is green. Proponents of logic recommend grouping only elements in which the blocks of descriptions completely coincide.

In general, whether to group or not is a matter of your taste. But you must remember about different approaches when you read someone else's code, for example, in templates.

This concludes the tutorial on selectors. In the next lesson, we will introduce concepts such as pseudo-elements and pseudo-classes.

Exists four ways to connect styles to your HTML document. The most commonly used methods are inline CSS and external CSS.

Inline CSS in HTML - element

Below is an example CSS injection based on the above syntax:

Heading

Paragraph.

We get the following result:

Attributes

Inline CSS - style attribute

You can use the attribute on any HTML element to define style rules. These rules will only apply to this element... Here's the general syntax:

<элемент style = "...правила стиля...">

Attributes

Example

Below is an example of inline CSS based on the above syntax:

Inline CSS

We get the following result:

External CSS Styles - Element

Element can be used to connect external CSS file s into your HTML document.

External table CSS styles is a separate text file with extension .css... You define all the style rules in this text file, and then you can include the CSS file in any HTML document using the element .

Here is the general syntax for including an external CSS file:

Attributes

Attributes are associated with elements or the rules defined in any external file style sheets.

  • Any rule defined in tags, overrides rules defined in any external CSS file.
  • Any rule defined in an external style sheet file has the lowest priority in CSS, and rules defined in that file will only apply when the two preceding rules do not apply.
  • Handling by older browsers

    There are many older browsers out there that don't support CSS. Therefore, we have to take care of writing inline CSS in our HTML document. The following code snippet shows how comment tags can be used to hide CSS from older browsers:

    CSS rules

    CSS, like any other computer language, has a strictly defined syntax, i.e. the rules by which style sheets are created. In the previous chapter, you have already seen several examples of different stylesheets, and you may have noticed that the syntax of CSS is different from that of HTML. There are no elements, no attributes, no tags in CSS. It contains rules, each of which describes the appearance of one or a group of HTML elements. The rule determines how a specific element will look. Let's give a definition.

    A CSS rule is a structural unit of a style sheet that describes the styles for a specific element. The rule consists of a selector, which is always on the left, and a style declaration block, which is enclosed in curly braces and immediately follows the selector (figure). Each declaration, in turn, consists of a property and its value. It is the property that determines the type of style that will be applied to the element.

    A rule can contain multiple declarations, separated by semicolons. You don't have to put a semicolon after the last announcement.

    For ease of reading and editing style sheets, its rules are usually written in such a way that each declaration appears on a separate line. For instance:

    It will be perceived in the same way, it will even give additional savings in the size of the code by removing extra characters spaces and newlines. But this kind of writing makes the code difficult to read. You can make a compromise: first write the rules, breaking them into lines, and after the stylesheet is finally ready, remove unnecessary insignificant characters. But there is no guarantee that after that you will not want to fix something else, then you will have to suffer a little before you find the desired property and edit it.

    For each property CSS the spec specifies the many values ​​that this property can take, as well as the default and scope! properties, i.e. those elements to which it can be applied. It also indicates whether this property is inheritable, i.e. whether it will apply to descendant elements. The output devices to which these properties apply. Since we will consider computer design, then we will mention only those properties that are applicable in our case, i.e. are designed to control the display on the monitor screen, and are also supported by modern browsers.

    Consider the main CSS rules for registration text elements On the page.

    • font-family: font family | font type. One caveat: if the name of the font contains a space, then this name must be enclosed in quotes.
    • font-size: value |%. This is the font size. It can be specified in pixels, percentages, em. Moreover, the percentage is calculated from the font size that this element has inherited.
    • font-weight: normal | bold | bolder | lighter | number between 100 and 900. This is the font weight. 400 = normal, 700 = bold.
    • font-style: normal | italic. This is the slant of your font. The default is normal.
    • font-variant: normal | small-caps. This is an outline of lowercase letters.
    • team rules font... They allow you to specify separate rules, separated by spaces. In most prefab rules, order is not important, but in the font rule it does.
    • font: font-style font-variant font-weigth font-size font-family... We write the rules only in this order. It is mandatory to specify the font-size and font-family rules (since they have no default values), other rules can be omitted.
    font- family: Arial, Geneva, Helvetica, sans- serif; font- size: 10px; font- weight: bold; font- style: italic; font- variant: small- caps; font: bold 10px Arial;

    Rules for working with text in CSS

    • text-align: left | right | center | justify. This is a replacement the align attribute, it horizontal alignment lines. Applies to block elements only.
    • text-decoration: none | overline (|) underline (|) line-through. This clearance horizontal line(no line, line above the line of text, below the line of text, strikethrough).
    • text-indent: value |%. This is a red line. Percentages are calculated from the size of the area where the same text is. Applies to block elements only.
    • text-transform: none | capitalize | uppercase | lowercase (characters do not change, each word with a capital letter, transform to lowercase or capital letters). This is a transformation of symbols.
    • letter-spacing: normal | magnitude. This is the distance between characters. Cannot be specified as a percentage.
    • word-spacing: normal | magnitude. This is the distance between words. Cannot be specified as a percentage.
    • vertical-align: baseline | sub | super | top | text-top | middle | bottom | text-bottom |%. Vertical alignment. This alignment inline elements between themselves. But for table elements “td” and “th” vertical alignment aligns all content that is inside.
    • line-height: normal | value |%. The height of the line where the text is.
    • white-space: normal | pre | nowrap. How to handle whitespace characters in our element (normal - they are shortened and automatic hyphenation is performed on them, nowrap - whitespace characters are shortened, but they are not wrapped, pre - spaces are not processed in any way, i.e. they are not canceled and there is no hyphenation either).
    text-align: right; text- decoration: underline; text- indent: 10px; text- transform: uppercase; letter- spacing: 10px; word- spacing: 10px; vertical- align: top; line- height: 5%; white- space: pre;

    Styling lists in CSS

    The rules for formatting lists in css can be applied both for the entire list and for individual elements list.

    • list-style-type: none | circle | disc | square | decimal | lower-alpha | upper-alpha | lower-roman | upper-roman. This is the type of marking: no marker, circle, disc, square, Arabic numerals, letters in different registers, Roman numbering in different registers.
    • list-style-position: outside | inside (outside, inside). This is the placement of the area with a marker. A special area is formed for the marker: outside the “li” element or inside it (by default, outside the element).
    • list-style-image: none | url. The picture for the marker design. We can specify the url of the image so that it is displayed instead of a marker.
    • list-style: list-style-type list-style-position list-style-image. Those. here we write all three rules above into one, collective rule. The order doesn't matter here.
    list- style- type: square; list- style- position: inside; list-style-image: url ("ball.gif"); list- style: decimal inside;

    CSS color and background properties

    • color: color.
    • background-color: color | transparent. This is the background color. It is transparent by default.
    • background-image: none | url. Background picture... You can put a picture by specifying its url.
    • background-position: top | bottom | center | left | right | magnitude |%. Positioning the picture in the element.
    • background-attachment: fixed | scroll (anchor to element, viewport). This is a question of attaching a picture, from which the coordinate is calculated. Fixed is to read coordinates from the viewport.
    • background-repeat: repeat | repeat-x | repeat-y | no-repeat. Repeat: Both axes, repeat x-axis (horizontal), y-axis (vertical), no repeat.
    • background: transparent background-color background-image background-repeat background-attachment background-position. The collective rule combines all the background rules.
    color: red; background- color: # 330033; background- image: url ("fon.gif"); background- position: top right; background- attachment: fixed; background- repeat: repeat- x; background: #ffffff no- repeat url (fon.gif);

    CSS (Cascading Style Sheets), or Cascading Style Sheets are used to describe appearance document written in markup language. Typically CSS styles are used to create and modify the style of web page elements and user interfaces written in HTML languages and XHTML, but can also be applied to any kind of XML document, including XML, SVG, and XUL.

    Cascading style sheets describe the rules for formatting elements using properties and acceptable values these properties. For each element, you can use a limited set of properties, the rest of the properties will not have any effect on it.

    A style declaration consists of two parts: the web page element - selector, and the formatting commands are - ad block... The selector tells the browser which element to format, and the declaration block (code in curly braces) lists the formatting commands - properties and their values.


    Rice. 1. Structure of a CSS-style declaration

    Types of cascading style sheets and their specifics

    1. Types of style sheets

    1.1. External style sheet

    External style sheet is a text file with a .css extension that contains a set of CSS element styles. The file is created in a code editor, just like an HTML page. The file can contain only styles, no HTML markup. An external style sheet is connected to a web page using the tag located inside the section ... These styles work for all pages on the site.

    Multiple style sheets can be attached to each web page by adding multiple tags in sequence by specifying the purpose of this style sheet in the media tag attribute. rel = "stylesheet" indicates the type of link (style sheet link).

    The type = "text / css" attribute is optional in the HTML5 standard and can be omitted. If the attribute is absent, the default is type = "text / css".

    1.2. Internal Styles

    Internal Styles embedded in the section HTML document and are defined inside the tag... Inner styles take precedence over external styles, but are inferior to inline styles (specified using the style attribute).

    ...

    1.3. Inline Styles

    When we write inline styles, we write the CSS code to an HTML file, directly inside the element tag using the style attribute:

    Pay attention to this text.

    These styles only affect the element for which they are specified.

    1.4. @Import rule

    @Import rule allows loading external style sheets. For the @import directive to work, it must appear in the stylesheet (external or internal) before all other rules:

    The @import rule is also used to include web fonts:

    @import url (https://fonts.googleapis.com/css?family=Open+Sans&subset=latin,cyrillic);

    2. Types of selectors

    Selectors represent the structure of the web page. They are used to create rules for formatting elements of a web page. Selectors can be elements, their classes and identifiers, as well as pseudo-classes and pseudo-elements.

    2.1. Universal selector

    Matches any HTML element. For example, * (margin: 0;) will zero out outer padding for all elements of the site. Also, the selector can be used in combination with the pseudo-class or pseudo-element: *: after (CSS styles), *: checked (CSS styles).

    2.2. Element selector

    Element selectors allow you to format all elements of this type on all pages of the site. For example, h1 (font-family: Lobster, cursive;) will set the general formatting style for all h1 headings.

    2.3. Class selector

    Class selectors allow you to style one or more elements with the same name class placed in different places on the page or on different pages site. For example, to create a headline with the headline class, add a class attribute with the value headline to the opening tag

    and set the style for the specified class. Styles created with the class can be applied to other elements, not necessarily of this type.

    Instructions for use personal computer

    .headline (text-transform: uppercase; color: lightblue;)

    2.4. Identifier selector

    The id selector allows you to format one specific item. The id must be unique and can only appear once on one page.

    #sidebar (width: 300px; float: left;)

    2.5. Descendant selector

    Descendant selectors apply styles to elements within a container element. For example, ul li (text-transform: uppercase;) will select all li elements that are descendants of all ul elements.

    If you want to format the descendants of a specific element, you need to set a style class for that element:

    p.first a (color: green;) - this style will be applied to all links, descendants of the paragraph with the first class;

    p .first a (color: green;) - if you add a space, then links located inside any class tag .first, which is a child of the element, will be styled

    First a (color: green;) - this style will be applied to any link located inside another element designated by the .first class.

    2.6. Child selector

    A child element is a direct child of its containing element. One element can have multiple children, and each element can have only one parent. The child selector allows you to apply styles only if the child element immediately follows the parent element and there are no other elements between them, that is, the child is no longer nested.
    For example, p> strong will select all strong elements that are children of the p element.

    2.7. Sister selector

    A sisterly relationship arises between elements with a common parent. Sibling selectors let you select items from a group of siblings.

    h1 + p - will select all first paragraphs immediately following any tag

    without affecting the rest of the paragraphs;

    h1 ~ p - selects all paragraphs that are siblings to any h1 heading and immediately after it.

    2.8. Attribute selector

    Attribute selectors select elements based on an attribute name or attribute value:

    [attribute] - all elements containing the specified attribute - all elements for which the alt attribute is set;

    selector [attribute] - elements of this type containing the specified attribute, img - only images for which the alt attribute is set;

    selector [attribute = "value"] - elements of this type containing the specified attribute with a specific value, img - all pictures whose names contain the word flower;

    selector [attribute ~ = "value"] - elements partially containing given value, for example, if several classes are specified for an element separated by a space, p - paragraphs, the class name of which contains feature;

    selector [attribute | = "value"] - elements whose attribute values ​​list begins with the specified word, p - paragraphs whose class name is feature or begins with feature;

    selector [attribute ^ = "value"] - elements whose attribute value starts with the specified value, a - all links starting with http: //;

    selector [attribute $ = "value"] - elements whose attribute value ends specified value, img - all pictures in png format;

    selector [attribute * = "value"] - elements whose attribute value contains the specified word anywhere, a - all links whose name contains book.

    2.9. Pseudo class selector

    Pseudo-classes are classes that are not actually attached to HTML tags. They allow you to apply CSS rules to elements on event or submissive a certain rule... Pseudo-classes characterize elements with the following properties:

    : hover - any element that the mouse cursor is hovering over;

    : focus - an interactive element that has been navigated to using the keyboard or activated using the mouse;

    : active - an element that was activated by the user;

    : valid - form fields whose content has been checked in the browser for compliance with the specified data type;

    : invalid - form fields whose content does not match the specified data type;

    : enabled - all active form fields;

    : disabled - disabled form fields, i.e., in an inactive state;

    : in-range - form fields whose values ​​are in the specified range;

    : out-of-range - form fields whose values ​​are not included in the specified range;

    : lang () - elements with text in the specified language;

    : not (selector) - elements that do not contain the specified selector - class, identifier, name or type of the form field -: not ();

    : target - the element with the # symbol that is referenced in the document;

    : checked - selected (selected by the user) form elements.

    2.10. Structural pseudo-class selector

    Structural pseudo-classes select children according to the parameter specified in parentheses:

    : nth-child (odd) - odd children;

    : nth-child (even) - even children;

    : nth-child (3n) - every third element among children;

    : nth-child (3n + 2) - selects every third element starting with the second child (+2);

    : nth-child (n + 2) - selects all elements starting from the second;

    : nth-child (3) - selects the third child;

    : nth-last-child () - in the list of children selects the element with specified location, similar to: nth-child (), but starting from the last one in the opposite direction;

    : first-child - allows you to style only the very first child of the tag;

    : last-child - allows you to format the last child of the tag;

    : only-child - selects the element that is the only child;

    : empty - selects elements that have no children;

    : root - selects the element that is the root of the document - html element.

    2.11. Selector of structural type pseudo-classes

    Indicates a specific type of child tag:

    : nth-of-type () - selects elements by analogy with: nth-child (), while taking into account only the element type;

    : first-of-type - selects the first child of the given type;

    : last-of-type - selects last element of this type;

    : nth-last-of-type () - selects an element given type in the list of items according to the specified location, starting from the end;

    : only-of-type - selects the only element of the specified type among the children parent element.

    2.12. Pseudo element selector

    Pseudo-elements are used to add content that is generated using the content property:

    : first-letter - selects the first letter of each paragraph, applies only to block elements;

    : first-line - selects the first line of the element's text, applies only to block elements;

    : before - inserts generated content before the element;

    : after - adds generated content after the element.

    3. Combination of selectors

    For a more precise selection of elements for formatting, you can use combinations of selectors:

    img: nth-of-type (even) - selects all even pictures, alternative text which contains word css.

    4. Grouping of selectors

    The same style can be applied to multiple elements at the same time. To do this, on the left side of the declaration, list the required selectors separated by commas:

    H1, h2, p, span (color: tomato; background: white;)

    5. Inheritance and cascade

    Inheritance and cascade are two fundamental concepts in CSS that are closely related. Inheritance means that elements inherit properties from their parent (the element that contains them). The cascade is manifested in the way different types style sheets are applied to the document, and how conflicting rules override each other.

    5.1. Inheritance

    Inheritance is the mechanism by which certain properties are passed from an ancestor to its descendants. The CSS specification provides for inheritance of properties related to the text content of a page, such as color, font, letter-spacing, line-height, list-style, text-align, text-indent, text-transform, visibility, white-space, and word- spacing. This is convenient in many cases because you do not need to set the font size and font family for every element on the web page.

    Block formatting properties are not inherited. These are background, border, display, float and clear, height and width, margin, min-max-height and -width, outline, overflow, padding, position, text-decoration, vertical-align and z-index.

    Forced inheritance

    Via keyword inherit You can force an element to inherit any property value from the parent element. This even works for properties that are not inherited by default.

    How CSS styles are set and work

    1) Styles can be inherited from the parent element (inherited properties or using the inherit value);

    2) Styles located in the style sheet below override the styles located in the table above;

    3) One element can be styled from different sources... You can check which styles are being applied in the browser developer mode. To do this, click above the element. right click mouse and select "View Code" (or something similar). The right column will list all properties that are set for this element or inherited from the parent element, as well as the style files in which they are specified, and serial number lines of code.


    Rice. 2. Developer mode in Google browser Chrome

    4) When defining a style, you can use any combination of selectors - element selector, element pseudo-class, class or element identifier.

    div (border: 1px solid #eee;) #wrap (width: 500px;) .box (float: left;) .clear (clear: both;)

    5.2. Cascade

    Cascading Is a mechanism that controls the end result when different CSS rules are applied to the same element. There are three criteria that determine the order in which properties are applied - the! Important rule, the specificity, and the order in which the style sheets are included.

    The! Important rule

    Rule weight can be set using the! Important keyword, which is added immediately after the property value, for example, span (font-weight: bold! Important;). The rule must be placed at the end of the declaration, before the closing parenthesis, without a space. Such announcement will take precedence over all other rules. This rule allows you to cancel the property value and set a new one for an element from an element group in the case when there is no direct access to the file with styles.

    Specificity

    For each rule, the browser computes selector specificity and if the element has conflicting property declarations, the rule with the most specificity is taken into account. The specificity value has four parts: 0, 0, 0, 0. The specificity of a selector is determined as follows:

    for id, add 0, 1, 0, 0;
    0, 0, 1, 0 is added for class;
    0, 0, 0, 1 is added for each element and pseudo-element;
    for inline style added directly to an element - 1, 0, 0, 0;
    the universal selector has no specificity.

    H1 (color: lightblue;) / * specificity 0, 0, 0, 1 * / em (color: silver;) / * specificity 0, 0, 0, 1 * / h1 em (color: gold;) / * specificity: 0, 0, 0, 1 + 0, 0, 0, 1 = 0, 0, 0, 2 * / div # main p.about (color: blue;) / * specificity: 0, 0, 0, 1 + 0 , 1, 0, 0 + 0, 0, 0, 1 + 0, 0, 1, 0 = 0, 1, 1, 2 * / .sidebar (color: gray;) / * specificity 0, 0, 1, 0 * / #sidebar (color: orange;) / * specificity 0, 1, 0, 0 * / li # sidebar (color: aqua;) / * specificity: 0, 0, 0, 1 + 0, 1, 0, 0 = 0, 1, 0, 1 * /

    As a result, those rules will be applied to the element, the specificity of which is greater. For example, if an item has two specificities with values ​​0, 0, 0, 2 and 0, 1, 0, 1, then the second rule wins.

    The order of the attached tables

    You can create multiple external style sheets and connect them to one web page. If in different tables will meet different meanings properties of one element, then as a result the rule found in the style sheet in the list below will be applied to the element.

    Top related articles