Search for Courses, Topics

CSS Syntax

Learn about Basic Syntax.

9 May 2022-16 mins read

Overview

CSS is an acronym for Cascading Style Sheets. It's a style sheet language that describes how a document written in a markup language should look and be formatted.

The Syntax of CSS mainly consists of three components. The selector is the first part of the CSS syntax, and it is responsible for picking different HTML elements to apply the style to them. The other two parts are property and values. CSS rule accepts a property value pair for each selector and alters the look of the selected element.

Scope of article

  • In this article, We will cover the basic syntax rule of CSS.
  • Then, We will learn about the syntax the syntax of a number of css properties with the help of examples.

Basic CSS Syntax

CSS is a style sheet language that is used to change the appearance of a document produced in a markup language such as HTML by changing aspects such as colors, placement, and decorations.

The following are the basic building components of CSS syntax:

  1. property: The property is an identifier that specifies which feature, such as color or font size, is taken into account.
  2. values: CSS values are allocated to CSS Properties and saved in the CSS declaration block, which is part of the CSS rule/statement. For example, the color is set to black.

CSS values are assigned to the properties in the property value pair, with COLON (**' : '**) acting as a separator.

Property: value; 

A property and value pair is called a declaration. For example, see the color property declaration below.

  • css declaration

CSS selector: A CSS selector is the initial portion of a CSS syntax rule. It's a collection of HTML elements that tells the browser which HTML elements should get the rule's CSS property values applied to them.

Now we're in a position to define the structure of a CSS statement, which appears like this:

Selector { property : value; }

The example below shows a complete CSS rule and highlights its build blocks.

css rule and its build blocks

CSS Syntax — How to Code CSS

We've previously seen the basic structure of CSS syntax, but if we wish to code CSS for any project, we should keep a few things in mind.

1. How to group multiple selectors? A selector is a part of the CSS syntax rule that specifies the HTML element to which CSS style should be applied. We've already seen how to apply CSS to a single selector, which is as follows:

h1 { background-color: yellow; } 
/* setting background-color of all h1 elements, to yellow */

The code above selects all of the h1 tags in the Html page in question and changes their background color to yellow.

If we want to apply the same CSS style to several selectors, we can group them in a single statement rather than creating one CSS statement for each selector. We can group several selectors while keeping the original rule structure by using a comma (**','**) as a separator between two selectors.

For a better understanding, look at the example below:

h1, h2, p { background-color: yellow;}
/* changes background-color of all h1,h2 and p tags 
in the page's html to yellow */

The CSS code in the above example selects all h1, h2, and p tags in the HTML document and sets their background color to yellow.

2. How to apply multiple properties? The CSS property is the feature that is expected to be updated by the value supplied to it in the CSS Syntax rule. We can list all of the properties. To apply multiple properties to one or more selectors, use property-value pairs separated by a semi-colon (;).

p,h1{background-color:yellow;color:green;text-align:center;}
/* updating background-color and text color 
and making text alignment centre 
for all h1 headings and paragraphs */

3. How to Increase CSS Readability? Spreading your style declarations across numerous lines will improve the readability of your CSS code. You can also indent your code and utilize whitespaces at appropriate places if you like. This has no effect on how your code is presented; it only improves readability.

For example, we can make the code used in the previous example much more readable by writing each declaration in a separate line and adding some space in between.

Below we have written the same code in a more readable form.

p, h1 {
background-color : yellow;
color : green;
text-align : center;
}

CSS Syntax Examples

In this section, we'll go over some CSS attributes and look at the syntax for using them with examples.

Color Syntax:

Color property in CSS is responsible for assigning the user-specified color to the text on the web page.

The color property, often known as color syntax, in CSS follows the basic syntax guideline we mentioned earlier.

The general CSS syntax for color is:

selector {color:color_name;}

The value of the color property can be assigned in different ways:

  1. Using color keywords We can use the commonly used color names for assigning value to the CSS color property. for eg-
h1 {color: red;}
// this code will change the color of the text inside 
// h1 tag to "red"
  1. Using RGB Color Values RGB color code is the combination of the proportion of Red, Green, and Blue colors in the resultant color. CSS color property accepts it as a color value.

    • RGB colors have three values that represent: red, green, and blue.
    • Each value can be a number between 0 and 255 or a percentage from 0 to 100%.
    • A value of 0 means none of that color is being used.
    • A value of 255 or 100% means all of that color is being used.
    • A 0 for all three color values will be black.
    • A 255 or 100% for all three color values will be white.

    The CSS syntax for using RGB colors is a little different than we've seen before. See the example below.

p { color: rgb(0, 0, 0); }              /*assign color black to text in paragraph  */
h1 { color: rgb(255, 255, 255); }       /* white  to text in h1 */
ul { color: rgb(128, 80, 200); }        /* purple */

/* Percentages work, too */
h1 { color: rgb(100%, 100%, 100%); }    /* white */

Background Color Syntax:

CSS background-color property sets the color of the background of the page. It is quite similar to color property. The only difference is that it changes the background color only.

In the example below, we're making the div tag's background transparent.

div {
     background-color:transparent;
 }

Margin Syntax:

CSS margin property is used to define the space around the HTML element. It is completely transparent and does not have any background color.

  • It is possible to use negative margin values that are not inherited by child elements.
  • Notice that adjacent vertical margins (top and bottom) will collapse into each other so that the distance between the blocks is not the sum of the margins but only greater of those two.
  • We can assign values to margin property in form of pixels (px), percentages (%), and em values.
  • CSS Margin Property Specifies a Shorthand for Setting the Margin Property in one Declaration.
    • One value assigned to margin property is accepted in terms of top, right, bottom, and left margins. CSS syntax for the same is given below.

      •  h1 {margin : 10px;} /* assigns top right bottom and left margins to 10 px*/
        
    • Two space-separated values assigned to margin property indicates vertical (top and bottom ) and horizontal (left and right) margins, respectively. CSS syntax for the same is given below.

      • h2 {margin : 5% 10px;} /* 5% (top and bottom) margin and 10px for left and right */
        
    • Three space-separated values represent the top, horizontal (left and right), and bottom margin, respectively. CSS syntax for the same is given below.

      •    h2{ margin: 10px 4% 3em; }
        
    • Four space-separated values represent the top, left, right, and bottom margin, respectively. CSS syntax for the same is given below.

      •  h2 { margin: 2px 1em 0 auto;}
        
  • CSS also has margin-bottom, margin-top, margin-left, and margin-right for specifying the respective margins as indicated by property names.

White Space Syntax:

The white-space CSS attribute affects how text is treated on the element to which it is applied. For this, the CSS syntax is:

selector {white-space : value;}

CSS white-space property can have different values, as discussed below.

  • normal: This is the default setting. The text is wrapped when necessary in this value. White space sequences will collapse into a single whitespace.
  • nowrap: White space sequences will be collapsed into a single whitespace. Text will never wrap to the next line in this value and will only break when the <br> tag is used.
  • pre: The browser creates whitespace for you. It functions similarly to the HTML <pre> tag. Only line breaks will cause text to wrap.
  • pre-line: White space sequences will be collapsed into a single whitespace. When necessary, and on a line break, messages are wrapped.
  • pre-wrap: The browser keeps track of whitespace. When necessary, and on a line break, messages are wrapped.
  • initial: It sets this property to its default value.
  • inherit: It inherits this property from its parent element.

These values for white space can be demonstrated in CSS syntax as per the Syntax rule.

For Example:

h1{ white-space: normal;}
// modifying white-space property for h1 tag
// as per the value given.

Syntax for CSS Pseudo Classes:

In CSS, a pseudo-class is used to define an element's special state. It can be used in conjunction with a CSS selector to give existing elements a state-based effect. As demonstrated below, the CSS syntax for pseudo-classes includes a colon (':') between the selector and the pseudo-class name.

selector: pseudo-class {  
property: value;  
}  

The most commonly used pseudo-classes are as follows −

  1. :link Use this class to give an unvisited link a unique look.
  2. :visited Use this class to add a unique look to a previously visited link.
  3. :hover When you hover over an element, you may use this class to add a custom style to it.
  4. :active Use this class to add a special style to an active element.
  5. :focus Use this class to apply a unique style to an element while it is in focus.
  6. :first-child Use this class to apply a unique style to an element that is a child of another element.
  7. :lang This class is used to indicate a language to be used in a specific element.

In the example below, we will be styling anchor tag for different pseudo-states.

/* unvisited link styles using :link pseudo-class*/
a:link {
  color: #FF00aa;
}

/*style link if it is visited*/
a:visited {
  color: #00FFaa;
}

/* mouse over link react style */
a:hover {
  color: #FF0aFF;
}

/* selected link style*/
a:active {
  color: #b0b0FF;
}

Pseudo-element Syntax:

A CSS pseudo-element is a keyword that can be used as a selector to style a specific area of the specified element (s).

The CSS syntax of pseudo-elements:

selector::pseudo-element {
  property: value;
}
Or single colon (:) also works

selector:pseudo-element {
  property: value;
}

Note: Double colons, rather than single colons, should be used as a general rule. Pseudo-classes are distinguished from pseudo-elements by this. However, because this distinction did not exist in previous versions of the W3C spec, most browsers accept both syntaxes for the original pseudo-elements.

The most commonly used pseudo-elements are as follows:

  1. ::first-line This element is used to apply special styling to the first line of text in a selector.
  2. ::first-letter This element is used to apply a distinctive style to the first letter of the text in a selector.
  3. ::before Use this element to place content before another element.
  4. :after Use this element to add content after another element.

The following example formats the first line of the text in all paragraph ( p ) elements:

p::first-line {
  color: black;
  font-weight: bold; /* make fonts bold*/
}

Attribute Selector Syntax:

When we wish to style several HTML elements that have the same attribute or attribute values, we utilize the CSS attribute selector. It is an extremely convenient method of styling many elements by grouping them according to comparable characteristics. The attribute selector finds all components that have a specific attribute and styles them all. The attribute selectors are case sensitive by default and can be written in square brackets [].

There are several types of attribute selectors, which are given below:

  • [attribute] This attribute selector selects all items with the specified attribute and applies the CSS property to that attribute. For example, the selector [class] will select all the elements with the style attribute.
[class] {
        text-align:left;
        Color:blue;
    }
  • [attribute="value"] This selector is used to find all elements whose attribute has the same value as the supplied value. In continuation with the previous examples, instead of picking every element of the class attribute, choose elements with the class name as scaler, and apply some random CSS to them.
 [class = "scaler"] {
            color:black;
            font-size:40px;
            font-weight:100;
            text-align:left;
        }

Similarly, other CSS selectors are given below.

  • [attribute~="value"] This selector finds all items whose attribute value is a list of space-separated values, one of which is exactly equal to the provided value.
  • [attribute|="value"] This selection selects all items whose attribute contains a hyphen-separated list of values starting with the provided value. The value must be a whole word, either alone or preceded by a hyphen.
  • [attribute^="value"] This selector is used to select all items whose attribute value begins with the provided value. The value does not have to be a complete word.
  • [attribute*="value"] This selector finds all elements whose attribute value contains the provided value and is present somewhere. The value does not have to be a full word.
  • [attribute$="value"] This selection selects all items whose attribute value ends with the provided value. The value does not have to be a full word.

Example: Update the color of all the links that starts with "https" and ends with ".com", to blue.

To address this, we can use a combination of two attribute selectors, as shown in the CSS syntax below.

   a[href^="https"][href$=".com"] {
     color: blue;
   }

Borders Syntax:

CSS's border property styles an element's border. This property combines three other properties: border-width, border-style, and border-color, and can be used as a shorthand notation for these three. The border-width, border-style, and border-color properties are set or returned by this method.

  • border-width specifies the weight or the width of the border.
  • border-style specifies a style for the border, that is, whether the border will be dotted, dashed, solid, etc.
  • border-color specifies the color of the border.

To set all of these properties in one declaration, we can use the border property. Using the Syntax in the table below.

selector {
    border: width style color;
}

Example: Let's wrap a border around paragraph "This is example text".

<p style="border:2px solid">
    This is an example text.
</p>

Now make this a 5px width, red color dashed border.

To do this task, we will use the CSS border property using the CSS syntax given below.

p{
    border: 5px dotted red;
}

and the result is..

<p style="border:5px dashed red">
    This is an example text.
</p>

Padding Syntax:

Paddings in CSS are used to add space around an element within a set border. Different paddings can be selected for each side (top, right, bottom, left). To implement padding properties, border properties must be included.

It's a shorthand for establishing paddings in a single declaration, similar to margin. CSS syntax is discussed below-

  • If only one value is given, it will be applied to all vertical and horizontal paddings.

    •  h1 {padding: 1px;}
      
  • If you provide two values, they will be vertical and horizontal paddings, respectively.

    •  h1 { padding: 1px 2px;}
      
  • If three space separated values are given, then they represent top, horizontal and bottom paddings, and four values represent the top, right, bottom, and left paddings in order.

Example: Take the result of the previous example.

<p style="border:5px dashed red;">
    This is an example text.
</p>

As you can see that the text is too close to the left border; make some room here using padding property.

We need to change the left padding here, so CSS syntax for the solution is given below-

p{                    
    padding: 0 0 0 100px;
           /* top right bottom left*/
}

and the result is given below

<p style="border:5px dashed red;padding:0 0 0 100px;">
    This is an example text.
</p>

Height and Width Syntax:

The height and width properties are used to specify an element's height and width. Padding, borders, and margins aren't included in the height and width parameters. It specifies the area's height and width within the padding, border, and margin of the element.

The CSS syntax for changing the height and width of the same selector is given below.

Selector{
    height: value1;
    width: value2;
}

The height and width properties may have the following values:

  • auto - This is the default value. The browser calculates the height and width.
  • length - Defines the height/width in px, cm etc.
  • % - Defines the height/width in percent of the containing block.
  • initial - Sets the height/width to its default value.
  • inherit - The height/width will be inherited from its parent value.

For example, if we want to update the height and width of some paragraph, we can

// updating height in terms of pixels
p {
 height: 10px;
}

// updating width in terms of pixels
p {
 width: 10px;
}

// updating height with width together in one declaration
// in terms of % height, the width of the element.

p {
    height: 90%;
    width: 110%;
}  

Fonts syntax:

The font property in CSS is used to customise the appearance of text. You can modify the text size, colour, style, and more using the CSS font property.

These are some important font properties:

  • Font-color: updates the color of the font.
  • Font-family: This property is used to change the type of the font, like Arial, sans-serif, etc.
  • Font-size: Updates the size of the font.
  • Font-style: The font can be made bold, italic, or oblique with this attribute.
  • Font-variant: You can use the font-variant property to convert the selected text to small capitals.
  • Font-weight: This allows you to change the Boldness and lightness of the font.

Font is a CSS shorthand for combining all of the above properties into a single declaration using the CSS Syntax below.

Selector {
  font: font-style font-variant font-weight font-size font-family;
}

Note: The font-size and font-family values are required. If one of the other values is missing, their default value is used.

For example, update the font properties for the paragraph below as stated in the paragraph itself.

<p style="color:red">
I am a paragraph. Make my font size 20 pixels and the font family Georgia.    
</p>

The solution is given below.

 P {
     font: 20px Georgia; 
     // as instructed, update font size and font family 
 }

<p style="color:red;font-size:20px; font-family:Georgia">
I am a paragraph. Make my font size 20 pixels, and the font family is Georgia.    
</p>

Syntax for links, tables, and lists

  • Links can be styled for their different states as discussed in the pseudo class syntax section.
  • To style CSS tables, we can follow the original syntax structure.

The example below specifies a black border for <table>, <th>, and <td> elements:

table, th, td {
  border: 1px solid black;
}
  • The Syntax for the styling list is as follows
ol / ul { /* for unordered list*/
    properties: values;
}

Conclusion

  • We've seen how to choose numerous selectors, assign multiple values, and make our code more understandable by going over the main building blocks of the CSS syntax rule.
  • We've looked at a variety of CSS properties and their syntax, and we've discovered that the fundamental CSS syntax rule may be used to design any HTML tag (be it lists, tables, or anything else).