Author: Saim Khalid

  • Printing

    CSS printing involves using specific CSS rules and properties to control how a webpage is formatted when printed. Generally for any printable versions of webpage, the styling will be done with light colors. Because the dark color like black, red will consume more ink from printer. In this tutorial we will learn how to design a printer friendly webpage using CSS.

    Table of Contents

    • Styles For Printer-Friendly Pages
    • Using a Print Style Sheet
    • Using Media Queries and @page
    • Detecting Print Requests

    Styles For Printer-Friendly Pages

    Here are the key styles that can be applied for creating printer-friendly pages:

    • Simplify the Layout: Remove unnecessary elements like sidebars, navigation menus, advertisement sections and interactive content by setting display as none
    • Remove Background Colors: It is recommended to remove background color (or set light color) and set text color as black for printable version of pages. This helps to save ink.
    • Adjust Font Sizes and Styles: Use readable font sizes and styles, typically larger and more legible fonts like serif fonts.
    • Display URLs for Links: When you print a page containing hyperlinks, the exact URL for that will not be visible. So you need to replace this with exact link on printable version.
    • Manage Page Breaks: Make sure to control where content breaks between pages to avoid splitting important sections or headings across pages.

    There are multiple ways we can style printer version of pages. We can explicitly declare an external stylesheet for printer version or we can use media queries inside internal stylesheet. Let’s look into that.

    Using a Print Style Sheet

    You can have a external stylesheet explicitly for printing needs and link it to your code. You just need to set the value for media attribute as “print” for link tag. Add the following tag to head section of your HTML document.

    <link href="/path/to/print.css" media="print" rel="stylesheet" />

    The print.css will look like this:

    body{background-color: white;color: black;}.navbar{display: none;}

    Using Media Queries and @page

    CSS media queries can be used to style printable versions in internal stylesheet itself.

    @media print{body{background-color: white;color: black;}.navbar{display: none;}}

    CSS @page rule is used to control aspects like the size, orientation, and margins of the printed content. This can be useful for setting a consistent page size and margin for all printed pages and creating booklets or documents with specific page layouts.

    @page{size: A4 portrait;/* A4 size, portrait orientation */margin: 2cm;/* 2cm margins on all sides */}/* First page has different styling */@page :first{margin: 5cm;}

    Let see an example for this two.

    Example

    <!DOCTYPE html><html><head><style>
    
        body{
            background-color: black;
            color: white;
            padding: 10px;
        }
        @media print {
            body { 
                background-color: white;
                color: black;
                padding: 10px;
            }
        }
        @page {
            size: A4 portrait; 
            margin: 2cm; 
        }
        button {
            background-color: aqua;
            padding: 5px;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h3&gt; Tutorialspoint &lt;/h3&gt;&lt;p&gt;CSS Media Type - Print&lt;/p&gt;&lt;p&gt;
        Background is white for printable version of this page.
        Check out...
    &lt;/p&gt;&lt;button onclick="printPage()"&gt;Print Page&lt;/button&gt;&lt;script&gt;
        function printPage() {
            window.print();
        }
    &lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Detecting Print Requests

    Browsers trigger 'beforeprint' and 'afterprint' events to identify when printing is about to happen or has just occurred. You can use these events to modify the user interface during the print process, such as showing or hiding specific elements while printing, or even change style after printing.

    <script>
    
    window.addEventListener("afterprint", () =&gt; self.close);   
    </script>

    The above declaration will automatically close the current window, after printing its contents. Let's see an example for this.

    Example

    <!DOCTYPE html><html><head><style>
    
        button{
            background-color: green; 
            color: white; 
            font-size: 1em;
        }
        @media screen {
            h2 {
                font-size: large;
                font-family: sans-serif;
                color: blue;
                font-style: normal;
            }
        }
        @media print {
            h2 {
                font-family: cursive;
                font-style: italic;
                color: red;
            }
        }
        @media print {
            button {display: none;}
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;article&gt;&lt;section&gt;&lt;h2&gt;Header1&lt;/h2&gt;&lt;p&gt;
            Section one
        &lt;/p&gt;&lt;/section&gt;&lt;/article&gt;&lt;button &gt;Print&lt;/button&gt;&lt;script&gt;
        const button = document.querySelector("button");
        button.addEventListener("click", () =&gt; {
        window.print();
        });
        window.addEventListener("afterprint", () =&gt; self.close);
    &lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
  • Paged Media

    CSS paged media refers to a set of properties, @rules and pseudo-class selectors that are used for styling of documents for printing.

    • CSS paged media provides additional features and properties specifically made for printed documents.
    • With these properties we can control page breaks, margins, headers, footers, and more.
    • Some of the key properties of paged media are @page, orphans, widows, break-after, break-before, and break-inside.
    • Paged Media properties prevent uneven and awkward printing of webpages.

    CSS Paged Media Related Properties

    Following is the list of CSS properties related to paged media:

    PropertyDescriptionExample
    break-afterUsed to forcefully break the page after a section in print document.Try It
    break-beforeUsed to forcefully break the page before a section in print document.Try It
    break-insideUsed to forcefully break the page or avoid breaking of page inside a section in print documentTry It
    orphansSpecify minimum number of lines placed at the bottom of a page when whole paragraph can’t be placed at bottom of the page.Try It
    widowsSpecify minimum number of lines placed at the top of a page when whole paragraph can’t be placed at top of the page.Try It

    CSS Paged Media @rules

    Following is the list of CSS at-rules related to paged media:

    PropertyDescriptionExample
    @pageThis is media query, used to specify different css styles for printed pages.Try It

    CSS Paged Media Pseudo-Classes

    Following is the list of CSS pseudo-classes related to paged media:

    PropertyDescriptionExample
    :firstThis pseudo class selects first page of a document for styling separately.Try It
    :leftThis pseudo class selects all the left-handed pages of a document for styling separately.Try It
    :rightThis pseudo class selects all the right-handed pages of a document for styling separately.Try It
  • Text Effects

    CSS text effects are used to manage styles of text by setting overflow rules, wrapping rules, line-breaking rules and writing modes to text. The text effects allow us to apply different types of effects on text used in an HTML document. In this chapter, we will learn how to add effects to texts in CSS.

    What are Text Effects in CSS?

    The following are the text effects commonly used in CSS:

    1. text-overflow: It specifies how to manage the text that is overflowing the container.
    2. word-wrap: It specifies to break the long words that are overflowing from the container.
    3. word-break: It specifies to break the words that are separated by the hyphens when the text is overflowing container.
    4. writing-mode: It specifies the horizontal and vertical writing modes of the text.

    We will see examples for all of these properties in upcoming sections. There are several other properties related to the text in CSS, we have covered all of those in the CSS Text Styling chapter.

    Text Overflow

    The text-overflow property is used to control the text that exceeds the parent’s width. You can clip the text that exceeds the width of the parent or add an ellipsis(…) to indicate text continues.

    Syntax

    The syntax for the CSS text-overflow property is as follows:

    p{text-overflow: clip | ellipsis;}

    Example

    The following example demonstrates the use of text-overflow property with clip and ellipsis values on the paragraph element.

    <html><head><style>
    
        p{
            white-space: nowrap; 
            border: 2px solid;
            width: 40%; 
            overflow: hidden;
            padding: 2%;
        }
        .txt1{
            text-overflow: clip;
        }
        .txt2 {
            text-overflow: ellipsis;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h3&gt; Text overflow clip &lt;/h3&gt;&lt;p class="txt1"&gt; 
        This is some large amount of text to understand text 
        overflow property
    &lt;/p&gt;&lt;h3&gt; Text overflow ellipsis &lt;/h3&gt;&lt;p class="txt2"&gt; 
        This is some large amount of text to understand text 
        overflow property 
    &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Word Wrap

    The word-wrap property is used to allow long words to be able to be broken and wrapped onto the next line. This ensures that the content fits within its container, preventing overflow.

    Syntax

    The syntax for the CSS word-wrap property is as follows:

    p{word-wrap: normal | break-word;}

    Example

    In this example, we have used word-wrap property with normal and break-word. The text with normal overflows the container, while with word-break, the word is broken to fit the container.

    <html><head><style>
    
        p{
            border: 2px solid;
            width: 40%; 
            padding: 2%;
        }
        .txt1{
            word-wrap: normal;
        }
        .txt2 {
            word-wrap: break-word;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h3&gt; Word wrap normal &lt;/h3&gt;&lt;p class="txt1"&gt; 
        ThisIsAVeryLongWordThatWillNotBreakAndWillOverflowItsContainer 
    &lt;/p&gt;&lt;h3&gt; Word wrap break-word &lt;/h3&gt;&lt;p class="txt2"&gt; 
        ThisIsAVeryLongWordThatWillBreakAndWrapOntoTheNextLine 
    &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Word Break

    The word-break property is used to specify how words should break when reaching the end of a line. This property is particularly useful for handling text that doesn't naturally wrap well, such as long words or URLs.

    Syntax

    The syntax for the CSS word-break property is as follows:

    p{word-break: normal | break-all | keep-all;}

    Example

    In this example, we have used the word-break property with 'normal', 'break-all', and 'keep-all' property values on the paragraph element.

    <html><head><style>
    
        p{
            border: 2px solid;
            width: 40%; 
            padding: 2%;
        }
        .txt1{
            word-break: break-all;
        }
        .txt2 {
            word-break: keep-all;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h3&gt; Word break break-all &lt;/h3&gt;&lt;p class="txt1"&gt; 
        This-paragraph-contains-some-text.-This-line-will-not-
        break-at-hyphens.
    &lt;/p&gt;&lt;h3&gt; Word break keep-all &lt;/h3&gt;&lt;p class="txt2"&gt; 
        This-paragraph-contains-some-text.-This-line-will-break
        -at-hyphens.
    &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Writing Mode

    The writing-mode property is used to define the direction in which text is written within a block. This property is especially useful for supporting languages that are written vertically or for creating rotated text effects.

    Syntax

    The syntax for the CSS writing-mode property is as follows:

    p{writing-mode: horizontal-tb | vertical-rl | vertical-lr;}

    Example

    The following example uses the writing-mode property to define the direction of the text of the paragraph element.

    <html><head><style>
    
        p{
            border: 2px solid;
            width: 200px; 
            padding: 2%;
        }
        .txt1{
            writing-mode: horizontal-tb;
        }
        .txt2 {
            writing-mode: vertical-rl;
        }
        .txt3 {
            writing-mode: vertical-lr;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h3&gt; Writing mode horizontal-tb &lt;/h3&gt;&lt;p class="txt1"&gt; 
        This text is written in the traditional horizontal 
        direction from left to right
    &lt;/p&gt;&lt;h3&gt; Writing mode vertical-rl &lt;/h3&gt;&lt;p class="txt2"&gt; 
        This text is written vertically from top to bottom, 
        with lines stacked right to left
    &lt;/p&gt;&lt;h3&gt; Writing mode vertical-lr &lt;/h3&gt;&lt;p class="txt3"&gt; 
        This text is written vertically from top to bottom, 
        with lines stacked left to right
    &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Text Effects Related Properties

    Following is the list of CSS properties of styling text:

    PropertyDescriptionExample
    text-overflowSpecifies how to manage the text that are overflowing the container.Try It
    word-wrapSpecifies to break the long words that are overflowing container.Try It
    word-breakSpecifies to break the words that are separated by the hyphens when text is overflowing container.Try It
    writing-modeSpecifies horizontal and vertical writing modes of text.Try It
    text-justifySpecifies the justification method of text when text-align is set to "justify".Try It
  • Rules

    CSS at-rules are special instructions or statements beginning with the “@” symbol. They are used to control or modify the behavior of the stylesheet and are typically used for tasks such as defining media queries, importing external stylesheets, or specifying font faces.

    CSS at-rules improves the CSS capabilities beyond basic selectors and property-value pairs. An at-rule begins with an at (@) sign, followed by an identifier, and further includes everything up to the next semicolon (;) or next CSS block.

    Syntax

    /* General structure */
    @identifier (RULE);
    

    Types of @ Rules

    Regular

    CSS provides different regular at-rules, based on the identifier and each has a different syntax.

    • @charset: Specifies the character encoding of an external stylesheet.
    • @import: Used to import an external CSS file into the current stylesheet.
    • @namespace: Used to declare and define XML namespaces within a CSS stylesheet.

    Nested

    A subset of nested statements that serve as both standalone style sheet statements and components within conditional group rules.

    • @media: Content of conditional group rule gets applied, if the device meets the criteria of the condition defined using media query.
    • @supports: Content of conditional group rule gets applied, if the given condition is met by the browser.
    • @page: Defines the layout of printed pages.
    • @font-face: Defines custom fonts to be used in a web page.
    • @keyframes: Defines the aspect of intermediate steps in a CSS animation sequence.
    • @counter-style: Defines the different custom counter styles that are not predefined.
    • @font-feature-values: Defines the common names in font-variant-alternates for feature activated in OpenType. It deals with the usage of alternate glyphs and these glyphs are defined in @font-feature-values
    • @property: Defines the usage of custom properties and variables.
    • @layer: Defines a layer and sets the order of precedence, when there are multiple cascade layers.

    CSS @ Rules – @page Example

    Here is an example of usage of @page:

    <html><head><style>
       @page :first {
    
      margin-left: 80%;
      margin-top: 80%;
    } p { page-break-after: always; } </style></head><body><p>Page One.</p><p>Page Two.</p><button>Print</button><script>
      document.querySelector("button").addEventListener("click", () =&gt; {
      window.print();
      });
    </script></body></html>

    CSS @ Rules – @keyframes Example

    Here is an example of usage of @keyframes:

    <html><head><style>
       p {
    
      animation-duration: 3s;
      animation-name: slidein;
    } @keyframes slidein {
      from {
         margin-left: 100%;
         width: 300%;
      }
      to {
         margin-left: 0%;
         width: 100%;
      }
    } </style></head><body><p>
      The text appears from right to left
      &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS @ Rules - @property Example

    Here is an example of usage of @property:

    <html><head><style>
       @property --item-size {
    
      syntax: "&lt;percentage&gt;";
      inherits: true;
      initial-value: 40%;
    } .container {
      display: flex;
      height: 100px;
      border: 3px dotted black;
    /* set custom property values on parent */
      --item-size: 50%;
      --item-color: tomato;
      --item-border: 5px solid green;
    } /* use custom properties to set item size and background color */ .item {
      width: var(--item-size);
      height: var(--item-size);
      border: var(--item-border);
      background-color: var(--item-color);
    } /* set custom property values on element itself */ .second {
      --item-size: initial;
      --item-color: inherit;
    } </style></head><body><div class="container"><div class="first item">First Item</div><div class="second item">Second Item</div></div><script>
      window.CSS.registerProperty({
      name: "--item-color",
      syntax: "&lt;color&gt;",
      inherits: false,
      initialValue: "peachpuff",
    }); </script></body></html>

    CSS @ Rules - Rule List

    The table given below lists all the CSS @ Rules:

    @RuleExample
    @charset@charset "UTF-8";
    @container@container (width > 400px) { h1 {font-size: 2em;} }
    @counter-style@counter-style sample {}
    @font-face@font-face { font-family: "CustomFont"; src: url("customfont.woff2") format("woff2"); }
    @font-feature-value@font-feature-values "CustomFont" {@swash { fancy: 2; }}
    @font-palette-values@font-palette-values One { font-family: "Bungee Spice";}
    @import@import ur();
    @keyframes@keyframes sample-slide { from { transform: translateY(100%) } }
    @layer@layer sample-layer{ .margin-lg { margin: 5px; } }
    @media@media screen and (max-width: 600px) {}
    @namespace@namespace svg url();
    @page@page { size: 5in 6in; margin-left: 4in }
    @property@property sample-property { rules }
    @supports@supports (transform-origin: 10% 10%) {}

  • Pseudo Elements

    CSS pseudo-elements are used to style specified parts of an element. While browsing a webpage, you might have noticed that the first letter of some paragraphs is larger than rest of letters. This type of styling for a specific part of elements is done using pseudo-elements in CSS. In this tutorial we will explain all the pseudo-elements and their functioning.

    Table of Contents

    • What is Pseudo-Element?
    • Insertion Pseudo-Elements
    • CSS Backdrop Pseudo-Element
    • CSS Cue Pseudo-Element
    • CSS First-Letter Pseudo-Element
    • CSS First-Line Pseudo-Element
    • CSS File-Selector-Button
    • CSS Marker Pseudo-Element
    • CSS Placeholder Pseudo-Element
    • CSS Selection Pseudo-Element
    • Multiple Pseudo-elements
    • All CSS Pseudo-Elements

    What is Pseudo-Element?

    A pseudo-element in CSS, is used to style a specific part of an element that are not the part of the DOM (Document Object Model) and do not exist in the HTML markup. For Example first letter of a paragraph, placeholder text inside input element or selected part in a document.

    • Pseudo-elements are denoted by a double colon (::) notation.
    • Only one pseudo-element can be used in a selector.
    • A pseudo-element in a selector must appear after all the other components. For example, p::last-line:hover is invalid.
    • Pseudo-elements can be used to add decorative styles, create special effects, and modify the appearance of certain parts of an element, that has a state already applied to it. For example, p:hover::last-line is a valid statement and selects the last line of the paragraph when the paragraph is hovered

    Syntax

    selector::pseudo-element{property: value;}

    The single colon syntax is supported by the browsers for the four original pseudo-elements, i.e., ::before, ::after, ::first-line, and ::first-letter.

    Content Insertion Pseudo-Elements

    In CSS, pseudo-elements ::before and ::after are used to insert text contents or images before and after any element.

    Example

    This example shows how to insert text and images at start and end of a paragraph using CSS.

    <!DOCTYPE html><html><head><style>
    
        p:before {
            content: "NOTE:";
            font-weight: bold;
        }
        p:after {
            content: url(/css/images/smiley.png);
        }       
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;
        We inserted intro at start and emoji at end.
    &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Backdrop Pseudo-Element

    In CSS the ::backdrop pseudo-element is used to style the backdrop of an element that is in a modal context, such as the backdrop behind a <dialog> element when it is shown.

    Example

    Following example demonstrates use of ::backdrop pseudo-element.

    <!DOCTYPE html><html><head><style>
    
        body{
            height: 200px;
        }
        dialog {
            padding: 20px;
            border: 2px solid black;
            border-radius: 10px;
        }
        dialog::backdrop {
            /* Semi-transparent black */
            background-color: rgba(0, 0, 0, 0.5); 
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h3&gt; Backdrop Example &lt;/h3&gt;&lt;dialog id="myDialog"&gt;&lt;p&gt; This is a dialog with a styled backdrop. &lt;/p&gt;&lt;button id="closeButton"&gt; Close &lt;/button&gt;&lt;/dialog&gt;&lt;button id="openButton"&gt;Open Dialog&lt;/button&gt;&lt;script&gt;
        const dialog = document.getElementById('myDialog');
        const openButton = document.getElementById('openButton');
        const closeButton = document.getElementById('closeButton');
        openButton.addEventListener('click', () =&gt; {
            dialog.showModal();
        });
        closeButton.addEventListener('click', () =&gt; {
            dialog.close();
        });
    &lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Cue Pseudo-Element

    In CSS, the pseudo-element ::cue is used with Web Video Text Tracks to style specific parts of text tracks, such as subtitles or captions, for media elements like <video> and <audio>.

    Example

    Following example demonstrates use of ::cue pseudo-element

    <!DOCTYPE html><html><head><style>
    
    video {
        width: 100%;
    }
    video::cue {
        font-size: 1rem;
        color: peachpuff;
    }
    </style></head><body><video controls src="/css/foo.mp4"><track default kind="captions"
               srclang="en" src="/css/cue-sample.vtt" /&gt;&lt;/video&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS First-Letter Pseudo-Element

    In CSS, the ::first-letter pseudo-element is used to target the first letter of text content of any elements like divparagraphspan etc

    Example

    Following example demonstrates use of ::first-letter pseudo-element:

    <!DOCTYPE html><html><head><style>
    
        p::first-letter { 
            text-transform: uppercase;
            font-size: 2em;
            color: darkred;
            font-style: italic;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;
        this is a paragraph with first letter in lowercase, 
        we used ::first-letter pseudo-element to capitalize
        first-letter of paragraph with a larger font size 
        and a different color. 
    &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS First-Line Pseudo-Element

    In CSS, the ::first-line pseudo-element is used to target the first line of text content of any elements like divparagraphspan etc

    Example

    Following example demonstrates use of ::first-line pseudo-element:

    <!DOCTYPE html><html><head><style>
    
        p::first-line { 
            background-color: #f0f0f0;
            color: darkred;
            font-style: italic;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;
        This is a normal paragraph with no stylings, we used 
        ::first-line pseudo-element to only style first-line of 
        paragraph by adding a background color, font-style and 
        text color
    &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS File-Selector-Button Pseudo-Element

    In CSS, the ::file-selector-button pseudo-element is used to style the button of a file input element (<input type="file">) in modern browsers.

    Example

    Following example demonstrates use of ::file-selector-button pseudo-element:

    <!DOCTYPE html><html><head><style>
    
        body {
            display: block;
            height: 100px;
        }
        input::file-selector-button {
            background-image:url(/css/images/border.png);
            background-size: 200%;
            border: 2px solid black;
            border-radius: 8px;
            font-weight: 600;
            color: rgb(6, 1, 9);
            padding: 15px;
            transition: all 0.25s;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h2&gt; Select a file &lt;/h2&gt;&lt;input type="file"&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Marker Pseudo-Element

    In CSS, the ::marker pseudo-element is used to style the marker of ordered list and unordered list.

    Example

    Following example demonstrates use of ::marker pseudo-element:

    <!DOCTYPE html><html><head><style>
    
        ol li::marker {
            color: rgb(11, 38, 241);
            font-weight: bold;
        }
        ul li::marker {
            content: url('/css/images/smiley.png')
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h2&gt;Numbered list&lt;/h2&gt;&lt;ol&gt;&lt;li&gt;One&lt;/li&gt;&lt;li&gt;Two&lt;/li&gt;&lt;li&gt;Three&lt;/li&gt;&lt;/ol&gt;&lt;h2&gt;Bulleted list&lt;/h2&gt;&lt;ul&gt;&lt;li&gt;One&lt;/li&gt;&lt;li&gt;Two&lt;/li&gt;&lt;li&gt;Three&lt;/li&gt;&lt;/ul&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Placeholder Pseudo-Element

    In CSS, the ::placeholder pseudo-element is used to style the default text inside text input element (<input type="text">).

    Example

    Following example demonstrates use of ::placeholder pseudo-element:

    <!DOCTYPE html><html><head><style>
    
        .form {
            border: 2px solid black;
            background: lightgray;
            padding: 25px;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        input{
            padding: 10px;
            background-color: cornsilk;
        }
        input::placeholder { 
            color: grey; 
            font-style: italic;
            font-size: 20px;
        } 
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="form"&gt;&lt;h2&gt; Your Details:&lt;/h2&gt;&lt;input type="text" placeholder="First Name"&gt;&lt;input type="text" placeholder="Last Name"&gt;&lt;input type="text" placeholder="Address"&gt;&lt;input type="text" placeholder="Phone"&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Selection Pseudo-Element

    In CSS, the ::selection pseudo-element is used to style the user selected text inside any elements like divparagraphspan etc

    Example

    Following example demonstrates use of ::selection pseudo-element:

    <!DOCTYPE html><html><head><style>
    
        .highlight::selection { 
            color: yellow;
            background: brown;
        } 
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p class="highlight"&gt;
        Select Me!!! to see the effect.
    &lt;/p&gt;&lt;p&gt; No style applied to me. &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Multiple Pseudo-elements

    We can also add multiple pseudo elements to a selector, Check out the example.

    Example

    Following example demonstrates usage of multiple pseudo-elements (::first-line and ::first-letter).

    <!DOCTYPE html><html><head><style>
    
        p::first-line { 
            text-decoration: underline;
        }
        
        p::first-letter { 
            text-transform: uppercase;
            font-size: 2em;
            color: red;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;
        the first line of this paragraph will be underlined and 
        first letter is uppercase, 2em and red in color, as the
        pseudo-element ::first-line &amp; ::first-letter is applied 
        on p. The other lines are not underlined.
    &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    All CSS Pseudo-Elements

    The following table shows all pseudo-elements in CSS:

    Pseudo-elementDescriptionExample
    ::afterAdds a pseudo-element that is the last child of the selected element.Try It
    ::backdropUsed to style the backdrop of an element like dialog box.Try It
    ::beforeAdds a pseudo-element that is the first child of the selected element.Try It
    ::cueUsed to style the captions and cues in media with video text tracks.Try It
    ::first-letterApplies styles to the first letter of the first line of a block level element.Try It
    ::first-lineApplies styles to the first line of a block level element.Try It
    ::file-selector-buttonRepresents the button of an <input> of type="file".Try It
    ::markerSelects the marker box of a list item.Try It
    ::part()Represents an element within a shadow tree that has a matching part attribute.Try It
    ::placeholderRepresents a placeholder text in an <input> or <textarea> element.Try It
    ::selectionApplies styles to the selected part of the document (selected by clicking and dragging the mouse across text).Try It
    ::slotted()Represents an element that has been placed into a slot inside an HTML template.Try It
    ::grammar-errorUsed to style text that has been identified as grammatically incorrect by the browsers built-in grammar checking tools.Try It
    ::spelling-errorUsed to style text that has been identified as incorrect spelling by the browsers built-in spelling checking tools.Try It
  • Pseudo Classes

    Pseudo-classes in CSS are used to select and style elements based on their state or position within the document tree, without the need for adding extra classes or JavaScript.

    For Example, pseudo-class can be used to change color of element when mouse is hovered over it or Click a button to change color.

    Hover over me!Click me!

    Table of Contents

    • What is Pseudo-class?
    • Pseudo-Class Hover
    • Pseudo-Class Active
    • Pseudo-Class Focus
    • Pseudo-Class nth Child
    • Pseudo-Class First-Child
    • Pseudo-Class Last-Child
    • Pseudo-Class Lang
    • Pseudo-Class not
    • List of CSS Pseudo Classes

    What is Pseudo-class?

    • Pseudo-classes often used along with CSS Selectors by inserting a colon (:) after selector. For example a : hover{}, Here selector a will selects all the anchor tags in document.
    • A functional pseudo-class contains a pair of parentheses to define the arguments. For example: :lang(en).
    • The element to which a pseudo-class is attached, is termed as an anchor element. For example: button:hover, a:focus, etc. Here button and a elements are called the anchor elements.
    • Pseudo-classes apply style to an element as per the content of the document tree.
    • Pseudo-classes also apply a style to an element in relation to the external factors, such as history of the navigation of the element (:visited), status of the content (:checked), or position of mouse (:hover)

    Syntax

    selector:pseudo-class{property: value;}

    Pseudo-Class Hover

    In CSS, pseudo-class :hover is used to specify mouse hovering state of an element. This used to style element while users mouse passes through an element in document.

    Syntax

    tag:hover{property: value;}

    Example

    Following example shows how this can be applied.

    <!DOCTYPE html><html lang="en"><head><style>
    
      a{
         background-color: lightgrey;
         padding: 10px;
      }
      a:hover {
         color: red;
      }
      
      div{
         padding: 10px;
         border: solid 3px;
         background-color: aqua;
      }
      div:hover{
         background-color: lightgreen;
      }
    </style></head><body><h3>Anchor Tag Hovering</h3><a href="#">Hover over me!</a><h3>Div Hovering</h3><div>Hover me</div></body></html>

    Pseudo-Class Active

    The pseudo-class :active will apply style to an element when user activates the element by clicking or tapping on it. This is most commonly used with interactive elements like button and anchor tag, but all the HTML elements can use this pseudo-class.

    Syntax

    tag:active{property: value;}

    Example

    Here is an example that shows different usage of pseudo-class active.

    <!DOCTYPE html><html lang="en"><head><style>
    
      a, p, li {
         color: black;
         background-color: lightgrey;
         padding: 7px;
         border: 3px solid;      
      }
      a:active {
         color: red;
      }
      p:active {
         background-color: gold;
      }
      
      li:active {
         background-color: darkred;
      }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h2&gt;Active Pseudo-Class Example&lt;/h2&gt;&lt;h3&gt;For Button:&lt;/h3&gt;&lt;a href="#"&gt;Click Me&lt;/a&gt;&lt;h3&gt;For paragraph:&lt;/h3&gt;&lt;p&gt;Click me to see the effect.&lt;/p&gt;&lt;h3&gt;For list:&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;Item 1&lt;/li&gt;&lt;li&gt;Item 2&lt;/li&gt;&lt;li&gt;Item 3&lt;/li&gt;&lt;/ul&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Pseudo-Class Focus

    The pseudo-class :focus will apply style to an element when user focused an element like input tag by clicking on it. Before typing text in input element users has to click in input area to enable cursor, this is called focusing.

    Syntax

    tag:focus{property: value;}

    Example

    This example will show how to use pseudo-class focus in HTML.

    <!DOCTYPE html><html lang="en"><head><style>
    
      input{
         padding:3px;
      }
      input:focus {
         border-color: green;
         background-color: lightgrey;
      }
    </style></head><body><h2>Pseudo-Class focus Example</h2><h3>Focus on input text</h3><input type="text"
           placeholder="Type Something!"&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Pseudo-Class nth Child

    The pseudo-class :nth-child(n) will apply style to any specified direct child of an element.

    Syntax

    tag:nth-child(number/ expression / odd / even){property: value;}

    The pseudo-class nth-child can take number, mathematical expression or values like odd, even as parameter. To know about values associated with nth child visit our tutorial on Pseudo Class nth-child().

    <!DOCTYPE html><html lang="en"><head><style>
    
      div{
         border: 2px solid;
         margin: 7px;
         padding: 2px;
      }
      /* Apply Style to 2nd child of div */
      div:nth-child(2){
         background-color:red;
      }
      
      /* Apply Style to all odd children of li */
      li:nth-child(odd) {
         background-color: lightgray;
      }
      
      /* Apply Style to all even children of li */
      li:nth-child(even) {
         background-color: lightblue;
      }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h2&gt;Pseudo-Class nth-child&lt;/h2&gt;&lt;h3&gt;2nd child of Div&lt;/h3&gt;&lt;div&gt;&lt;div&gt;1st div&lt;/div&gt;&lt;div&gt;2nd div&lt;/div&gt;&lt;div&gt;3rd div&lt;/div&gt;&lt;div&gt;4th div&lt;/div&gt;&lt;/div&gt;&lt;h3&gt;Selecting odd and even children&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;First item&lt;/li&gt;&lt;li&gt;Second item&lt;/li&gt;&lt;li&gt;Third item&lt;/li&gt;&lt;li&gt;forth item&lt;/li&gt;&lt;li&gt;Third item&lt;/li&gt;&lt;li&gt;fifth item&lt;/li&gt;&lt;/ul&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Pseudo-Class First-Child

    The pseudo-class first-child used to select first direct child element.

    Syntax

    tag:first-child{property: value;}

    Example

    Following example show how to use first-child pseudo-class in HTML.

    <!DOCTYPE html><html lang="en"><head><style>
    
      div{
         border: solid;
      }
      /* Selects all first child paragraphs */
      p:first-child {
         color: blue;
      }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;
      This paragraph is first child of body 
      element, will be blue.
    </p><p>This paragraph will not be affected.</p><p>Another paragraph that won't be affected.</p><div><p>
         This paragraph is first child of div 
         element will be blue.
      &lt;/p&gt;&lt;p&gt;This paragraph will not be affected.&lt;/p&gt;&lt;p&gt;Another paragraph that won't be affected.&lt;/p&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Pseudo-Class Last-Child

    The pseudo-class last-child used to select last direct child element.

    Syntax

    tag:last-child{property: value;}

    Example

    Following example show how to use last-child pseudo-class in HTML.

    <!DOCTYPE html><html lang="en"><head><style>
    
      div{
         border: solid;
      }
      /* Selects all last child paragraphs */
      p:last-child {
         color: blue;
      }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;This paragraph will not be affected.&lt;/p&gt;&lt;p&gt;Another paragraph that won't be affected.&lt;/p&gt;&lt;div&gt;&lt;p&gt;This paragraph will not be affected.&lt;/p&gt;&lt;p&gt;Another paragraph that won't be affected.&lt;/p&gt;&lt;p&gt;
         This paragraph is last child of div 
         element will be blue.
      &lt;/p&gt;&lt;/div&gt;&lt;p&gt;
      This paragraph is last child of body 
      element, will be blue.
    </p></body></html>

    Pseudo-Class Lang

    The pseudo-class :lang() will apply style to an element based on value of lang attribute set to the element or it's parent.

    Here is an example of :lang() pseudo-class:

    <html><head><style>
       /* Selects all the tags that set english as language */
       :lang(en) {
    
      quotes: '""';
    } /* Selects all the tags that set french as language */ :lang(fr) {
      quotes: ' ' ' ';
    } </style></head><body><h2>:lang() selector example</h2><q lang="en">
      This language is set as english, Here 
      css use double(" ") quotes
    </q><br><q lang="fr">
      This language is set as French, Here 
      css use guillemet( ) quotes
    </q></body></html>

    Pseudo-Class Not

    The pseudo-class :not(selector) is used to apply style on all the elements expect elements that included in mentioned selectors. To know what is a selector in CSS check out our tutorial on CSS Selectors.

    Syntax

    tag:not(selector){property: value;}

    The selector can be a class, id, or tag in html.

    Example

    Following example shows how to use not pseudo-class in CSS

    <!DOCTYPE html><html lang="en"><head><title>CSS :not() Example</title><style>
    
      /*Style all paragraph except class special*/
      p:not(.special) {
         color: red;
      }
      
      /*Style all special paragraph except id superSpecial*/
      .special:not(#superSpecial){
         background-color: lightgrey;
      }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;This is a normal paragraph.&lt;/p&gt;&lt;p class="special" id="superSpecial"&gt;
      This is a super special paragraph.
    </p><p>This is another normal paragraph.</p><p class="special">
      This is special paragraph.
    </p></body></html>

    List of CSS Pseudo Classes

    The table given below lists all the CSS pseudo-classes:

    Pseudo-classDescriptionExample
    :activeRepresents an element that has been activated by the user.Try It
    :any-linkRepresents an element that acts as the source anchor of a hyperlink, independent of whether it has been visited.Try It
    :autofillMatches an element that has its value autofill by the browser.Try It
    :checkedMatches any radio, checkbox or option element that is checked or toggled.Try It
    :defaultSelects form elements that are the default in a group of related elements.Try It
    :definedRepresents any custom element that has been defined.Try It
    :disabledRepresents a disabled element.Try It
    :emptyMatches an element that has no children.Try It
    :enabledRepresents an enabled element, after its has been activated.Try It
    :firstRepresents the first page of a printed document, with the @page at-rule.Try It
    :first-childRepresents the first element among a group of sibling elements.Try It
    :first-of-typeRepresents the first element of its type among a group of sibling elements.Try It
    :fullscreenMatches an element that is currently displayed in fullscreen mode.Try It
    :focusRepresents an element that has received focus.Try It
    :focus-visibleApplies while an element matches the :focus pseudo-class or receives focus.Try It
    :focus-withinMatches an element if the element or any of its descendants are focused.Try It
    :has()This represents an element if any of the relative selectors.Try It
    :hostThis selects the shadow host of the shadow DOM containing the CSS it is used inside.Try It
    :host()This function selects the shadow host of the shadow DOM containing the CSS it is used inside.Try It
    :host-context()This function allows you to style a custom element based on the classes or attributes of its ancestor elements.Try It
    :hoverMatches when the user interacts with an element with a pointing device, like a mouse, but does not necessarily activate it.Try It
    :indeterminateRepresents any form element whose state is indeterminate or unknown.Try It
    :in-rangeRepresents an element whose current value is within the range limits.Try It
    :invalidRepresents any element whose contents fail to validate.Try It
    :is()Takes a selector list as its argument, and selects any element that can be selected by one of the selectors in that list.Try It
    :lang()Matches an element based on the language they are defined to be in.Try It
    :last-childRepresents the last element among a group of sibling elements.Try It
    :last-of-typeRepresents the last element of its type among a group of sibling elements.Try It
    :leftRepresents all left-hand pages of a printed document, used with @page at-rule.Try It
    :linkRepresents an element that has not yet been visited.Try It
    :modalMatches an element that is in a state in which it excludes all interaction with elements outside it until the interaction has been dismissed.Try It
    :not()Represents an element that do not match a list of selectors.Try It
    :nth-child()Selects child elements according to their position among all the sibling elements within a parent element.Try It
    :nth-last-child()Matches elements based on their position among siblings, counting from the last (end)Try It
    :nth-last-of-type()Matches elements based on their position among siblings of the same type, counting from the last (end).Try It
    :nth-of-type()Matches elements based on their position among siblings of the same type.Try It
    :only-childRepresents an element without any siblings.Try It
    :only-of-typeRepresents an element that has no siblings of same type.Try It
    :optionalRepresents an element that does not have a required attribute set on it.Try It
    :out-of-rangeRepresents an element whose current value is outside the range limits.Try It
    :picture-in-pictureMatches an element that is currently in picture-in-picture mode.Try It
    :placeholder-shownRepresents any element that is currently displaying placeholder text.Try It
    :read-onlyRepresents an element that is not editable by the user.Try It
    :read-writeRepresents an element that is editable by the user.Try It
    :requiredRepresents an element that has a required attribute set on it.Try It
    :rightRepresents all right-hand pages of a printed document, used with @page at-rule.Try It
    :rootMatches the root element of a document tree.Try It
    :scopeRepresents elements that are a reference point, or scope, for selectors to match with.Try It
    :targetRepresents the target element with an id matching the URL's fragment.Try It
    :validRepresents any element whose contents validate successfully.Try It
    :visitedApplies once the link has been visited.Try It
    :where()Takes a selector list as its argument and selects any element that matches.Try It

  • Layers

    CSS Layers are a concept that is used to control the stacking order of different DOM elements in a webpage. The z-index property determines the stacking order of elements within a stacking context.

    The elements with a higher z-index are layered above those with a lower z-index and if elements share the same z-index, they stack according to their order in the DOM. We will look more into details and examples of CSS layering in this tutorial.

    Table of Contents

    • CSS Layering With z-index Property
    • Layer Text Above Image
    • Positioning Without z-index Property

    CSS Layering With z-index Property

    As mentioned above the z-index property can be used to decide stacking order of element in a webpage. The following example demonstrates how to create vertically stacked elements using z-index property. The elements with higher z-index value are positioned above the elements of lower z-index value.

    Example

    <html><head><style>
    
        div{
            position: absolute;
            height: 100px;
            width: 100px;
            padding: 5px;
            color: white;
        }
        .box1 {
            background-color: darkred;
            z-index: 1;
            left: 10px;
            top: 10px;
        }
        .box2 {
            background-color: darkblue;
            z-index: 2;
            margin: 10px;
            left: 50px; 
            top: 30px;
        }
        .box3 {
            background-color: darkgreen;
            z-index: 3;
            margin: 20px;
            left: 80px; 
            top: 50px;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="box1"&gt;
        z-index: 1
    &lt;/div&gt;&lt;div class="box2"&gt;
        z-index: 2
    &lt;/div&gt;&lt;div class="box3"&gt;
        z-index: 3
    &lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Layer Text Above Image

    In CSS position property can be used to position text in different locations above an image.

    First we need to set position property for image container as position: relative and position property of text as position: absolute. Now you can position of text elements using CSS inset properties like top, bottom, left and right.

    Example

    <html><head><style>
    
        .container {
            position: relative;
            border: 2px solid #ef2c2c;
        }
        .center {
            position: absolute;
            top: 45%;
            width: 100%;
            text-align: center;
        }
        .top-left {
            position: absolute;
            top: 12px;
            left: 30px;
        }
        .top-right {
            position: absolute;
            top: 12px;
            right: 30px;
        }
        .bottom-left {
            position: absolute;
            bottom: 12px;
            left: 30px;
        }
        .bottom-right {
            position: absolute;
            bottom: 12px;
            right: 30px;
        }
        img {
            width: 100%;
            opacity: 0.7;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="container"&gt;&lt;img src="/css/images/red-flower.jpg" 
                width="1000px" height="350px"&gt;&lt;h3 class="center"&gt;
            Text at Center
        &lt;/h3&gt;&lt;h3 class="top-left"&gt;
            Text at Top Left
        &lt;/h3&gt;&lt;h3 class="top-right"&gt;
            Text at Top Right
        &lt;/h3&gt;&lt;h3 class="bottom-left"&gt;
            Text at Bottom Left&lt;/h3&gt;&lt;h3 class="bottom-right"&gt;
            Text at Bottom Right
        &lt;/h3&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Positioning Without z-index Property

    The following example demonstrates how to create layers without using z-index property.

    Example

    <html><head><style>
    
        div{
            position: absolute;
            height: 100px;
            width: 100px;
            padding: 5px;
            color: white;
        }
        .box1 {
            background-color: darkred;
            padding: 10px;
            left: 10px;
            top: 10px;
        }
        .box2 {
            background-color: lightblue;
            padding: 10px;
            margin: 10px;
            left: 30px; 
            top: 30px;
        }
        .box3 {
            background-color: yellow;
            padding: 5px;
            margin: 10px;
            left: 60px; 
            top: 60px;
        }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="box1"&gt;
        Box 1
    &lt;/div&gt;&lt;div class="box2"&gt;
        Box 2
    &lt;/div&gt;&lt;div class="box3"&gt;
        Box 3
    &lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>
  • Positioning

    CSS Positioning helps to manipulate position of any element in a web page. In this tutorial we will learn position property and values associated with it.

    Table of Contents

    • What is CSS Position?
    • Static Positioned Element
    • Relative Positioned Elements
    • Absolutely Positioned Elements
    • Position Fixed Element
    • Sticky Positioned Element
    • Positioning Text in an Image
    • Position Related Properties

    What is CSS Position?

    In CSS position property is used to create floating elements, floating sidebar, and other interactive features by adjusting position of elements in webpage.

    Along with position property, other properties like top, bottom, right, and left are used to control its exact position on the page. They specify the offsets of an element from its edges. We will see examples for those in this tutorial.

    Syntax

    Following are possible values for css position.

    position: static | relative | absolute | fixed | sticky;

    Static Positioned Element

    When you use the position: static property, the element will be positioned normally in the document flow. The leftrighttopbottom, and z-index properties will not affect the element. This is the default value for position property.

    Example

    In this example we defined two static positioned div elements and one relative positioned element. See the difference.

    <!DOCTYPE html><html lang="en"><head><style>
    
      .container {
         padding: 20px;
         border: 1px solid #ccc;
      }
      .static-element {
         position: static;
         background-color: lightblue;
         padding: 10px;
         margin: 10px 0;
      }
      .non-static-element {
         position: relative; 
         top: 20px;
         background-color: lightgreen;
         padding: 10px;
      }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="container"&gt;&lt;div class="static-element"&gt;
         This is a static element (default position).
      &lt;/div&gt;&lt;div class="non-static-element"&gt;
         This element is not static and is moved 
         20px down.
      &lt;/div&gt;&lt;div class="static-element"&gt;
         This is another static element (default 
         position).
      &lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Relative Positioned Elements

    CSS position: relative property positions the elements relative to their original position in the page. You can use the left, right, top, and bottom properties to move the element around, but it will still take up space in the document flow.

    Example

    In this example we defined one static positioned div element and one relative positioned element. See the difference.

    <!DOCTYPE html><html lang="en"><head><style>
    
      *{
         padding: 15px;
      }
      .container {
         border: 1px solid #ccc;
      }
      .static-element {
         position: static;
         background-color: lightblue;
      }
      .relative-element {
         position: relative;
         top: 20px;  
         left: 30px; 
         background-color: lightgreen;
      }
      .normal-flow {
         background-color: lightcoral;
         margin: 10px 0;
      }
    </style></head><body><div class="container"><div class="static-element">
         This is a static element (default position).
      &lt;/div&gt;&lt;div class="relative-element"&gt;
         This element is relatively positioned 20px 
         down and 30px right.
      &lt;/div&gt;&lt;div class="normal-flow"&gt;
         This element is in the normal document 
         flow, after the relative element.
      &lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Absolutely Positioned Elements

    An element with position: absolute is taken out of the document flow and positioned relative to its nearest positioned ancestor (if any). If there is no positioned ancestor, then the element is positioned relative to the viewport.

    You can use top, right, bottom, and left properties to specify the position of the element relative to its containing block.

    Example

    This example show use of position absolute

    <!DOCTYPE html><html lang="en"><head><style>
    
      *{
         padding: 15px;
      }
      .container {
       /* This makes container positioned ancestor */
         position: relative;
         width: 70%;
         height: 200px;
         border: 1px solid #ccc;
      }
      .static-element {
         position: static;
         background-color: lightblue;
         padding: 10px;
         margin: 10px 0;
      }
      .absolute-element {
         position: absolute;
      /* 50px from top of nearest positioned ancestor */
         top: 50px;
      /* 30px from left of nearest positioned ancestor */
         left: 30px; 
         background-color: lightgreen;
         padding: 10px;
      }
    &lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div class="container"&gt;&lt;div class="static-element"&gt;
         This is a static element (default position).
      &lt;/div&gt;&lt;div class="absolute-element"&gt;
         This element is absolutely positioned 30px 
         from top and 50px from left.
      &lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Position Fixed Element

    In CSS position: fixed property is used to make element stay in the same place on the screen even when the user scrolls. You can then use the left, right, top, and bottom properties to position the element where you want it.

    Example

    In this example you can see that paragraph element remain there when you scroll down.

    <html><head><style>
       div {
    
      width: 100%;
      height: 500px;
      background-color: lightgrey;
      overflow: auto;
      padding: 15px;
    } .fixed-position {
      position: fixed;
      top: 50%;
      left: 20%;
      padding: 5px;
      background-color: white;
    } </style></head><body><div><p>You can Scroll down...</p><p class="fixed-position">
         Tutorialspoint CSS Position Fixed
      &lt;/p&gt;&lt;p&gt;
         White screen will remain at 50% 
         height from top 
      &lt;/p&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Sticky Positioned Element

    In CSS position: sticky property is used to make any element stay at the top of container even when the user scrolls. You can then use the left, right, top, and bottom properties to position the element where you want it.

    The position: sticky property is a combination of the position: relative and position: fixed properties

    Example

    In this example you can see that when you scroll, fixed move to top

    <html><head><style>
       div {
    
      width: 100%;
      height: 500px;
      background-color: lightgrey;
      overflow: auto;
      padding: 15px;
    } .sticky-position {
      position: sticky;
      top: 50%;
      left: 20%;
      padding: 5px;
      background-color: white;
    } </style></head><body><div><p>You can Scroll down...</p><p class="sticky-position">
         TutorialsPoint CSS Position Fixed
      &lt;/p&gt;&lt;p&gt;
         White screen will stick at top of 
         screen when you scroll down.
      &lt;/p&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Positioning Text in an Image

    In following example, you can use the position: absolute property to position text in different directions inside an image. The text elements are positioned at the top left, top right, bottom left, and bottom right corners.

    Example

    In the following example we have positioned text on an image.

    <html><head><style>
       .container {
    
      position: relative;
      border: 2px solid #ef2c2c;
    } .center {
      position: absolute;
      top: 45%;
      width: 100%;
      text-align: center;
    } .top-left {
      position: absolute;
      top: 12px;
      left: 30px;
    } .top-right {
      position: absolute;
      top: 12px;
      right: 30px;
    } .bottom-left {
      position: absolute;
      bottom: 12px;
      left: 30px;
    } .bottom-right {
      position: absolute;
      bottom: 12px;
      right: 30px;
    } img {
      width: 100%;
      opacity: 0.7;
    } </style></head><body><div class="container"><img src="/css/images/red-flower.jpg"
            width="1000px" height="350px"&gt;&lt;h3 class="center"&gt;
         Text at Center
      &lt;/h3&gt;&lt;h3 class="top-left"&gt;
         Text at Top Left
      &lt;/h3&gt;&lt;h3 class="top-right"&gt;
         Text at Top Right
      &lt;/h3&gt;&lt;h3 class="bottom-left"&gt;
         Text at Bottom Left&lt;/h3&gt;&lt;h3 class="bottom-right"&gt;
         Text at Bottom Right
      &lt;/h3&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    CSS Position Related Properties

    Following is the list of all the CSS properties related to position:

    PropertyDescriptionExample
    bottomUsed with the position property to place the bottom edge of an element.Try It
    clipSets the clipping mask for an element.Try It
    leftUsed with the position property to place the left edge of an element.Try It
    overflowDetermines how overflow content is rendered.Try It
    rightUsed with the position property to place the right edge of an element.Try It
    topSets the positioning model for an element.Try It
    vertical-alignSets the vertical positioning of an element.Try It
    z-indexSets the rendering layer for the current element.Try It
  • visibility Property

    The visibility Property

    CSS visibility property allows you to show or hide an element without changing the layout of a document, while hidden elements take up space.

    The visibility property can be used to create a variety of effects, such as hiding elements that are not yet ready to be displayed, or hiding elements that are only relevant to certain users.

    Syntax

    The syntax for the CSS visibility property is as follows:

    visibility: visible | hidden | collapse | initial | inherit;

    Possible Values

    ValueDescription
    visibleIt is the default value where the elements are visible.
    hiddenIt hides the element, but it still takes up space on the page.
    collapseIt removes the table rows, columns, column groups, and row groups from a table. The collapse has the same meaning as hidden if it is used on non-table elements.
    initialIt sets the visibility of an element to its default value.
    inheritIt inherits the visibility property from its parent element.

    Applies to

    The visibility property can be applied to all the HTML elements.

    CSS visibility – visible Value

    You can use the visibility property with visible to make an element visible.

    Example

    The following example uses the visibility property to make the h2 element visible.

    <html><head><style>
       h2 {
    
      visibility: visible;
    } </style></head><body><h2>Tutorials Point CSS visibility</h2></body></html>

    Hide Elements with CSS visibility Property

    To hide any HTML element, you can use the visibility property with the hidden value. It hides the element, but it does not remove it from the document layout. The element will still be accessible to screen readers and will affect the layout of the page, even though it is not visible.

    Example

    In this example, we have hidden the heading of the web page using ‘visibility: hidden;’.

    <html><head><style>
       h2 {
    
      visibility: hidden;
    } </style></head><body><h2>Tutorials Point CSS visibility hidden</h2><p>The hidden heading is still visible to screen readers and takes up space in the page.</p></body></html>

    Collapse Table Cells with CSS visibility

    To remove a table row, column, or any cell without affecting the layout of the table, you can set the visibility property of the row, column, or cell to collapse. This value is only valid for table elements.

    Example 1

    In this example, we have used the ‘visibility: collapse;’ property to collapse the table cell. You can use it to hide any row or column.

    <html><head><style>
       .collapse {
    
      visibility: collapse;
    } table {
      border-collapse: collapse;
      color: #ffffff;
      width: 100%;
      background-color: #35DC5A;
      border: 2px solid black;
    } th, td {
      border: 2px solid black;
      padding: 8px;
      text-align: left;
      font-size: 20px;
    } </style></head><body><table><tr><td>visible</td><td>hidden</td><td class="collapse">collapse</td></tr><tr><td>initial</td><td>inherit</td><td>revert</td></tr></table></body></html>

    Example 2

    In this example, we have used the ‘visibility: collapse;’ property on a non-table element. On a non-table element, it works as hidden value.

    <html><head><style>
       .collapse {
    
      visibility: collapse;
    } </style></head><body><h2>Collapse on non-table elements</h2><p class="collapse">you cant see me</p><p>the above sentence is hidden</p></body></html>

  • Flexbox

    Flexbox organizes elements within a container along a single dimension, which can be either horizontally or vertically aligned.

    What is CSS Flexbox?

    CSS flexbox is a layout model in CSS that provides an efficient and flexible way to arrange and distribute space between items within a container. It arranges elements in a single dimension, either horizontally or vertically, within a container.

    In this article we will cover all the properties for managing the positioning, alignment, and gaps between elements along both the main and cross axes briefly.

    Table of Contents

    • Elements of Flexbox
    • Basic Flexbox Layout
    • Vertical Flexbox Layout
    • Flexbox Justify Content
    • Flexbox Align Items
    • Centering a Div
    • Flexbox Wrap Property
    • Flexbox Align Self
    • Flexbox Container Properties
    • Flexbox Items Properties

    Elements of Flexbox

    • Flexbox Container: The flex container defines the outer element of flexbox, where all the child elements are present. A flexbox container can be defined by setting ‘display: flex’ or ‘display: inline-flex’.
    • Flexbox items: Flexbox items are direct children of flexbox container. This items can be arranged vertically and horizontally inside flexbox container based on need.
    • Main Axis: Main axis is primary axis along which items arranged in a container. By default this is horizontal axis.
    • Cross Axis: >Cross axis is perpendicular axis to primary axis. By default this is vertical axis.

    Following Diagram will demonstrate the CSS Flexbox:

    CSS Flexbox

    Basic Flexbox Layout

    Flexbox is commonly used to create responsive flexbox layout.

    Example

    <!DOCTYPE html><html lang="en"><head><style>
    
      .container {
         display: flex;
         flex-direction: row;
         justify-content: space-between;
         align-items: center;
         height: 100vh;
      }
      .item {
         background-color: lightcoral;
         padding: 20px;
         margin: 10px;
         border: 3px solid #ccc;
      }
    </style></head><body><div class="container"><div class="item">Item 1</div><div class="item">Item 2</div><div class="item">Item 3</div></div></body></html>

    Vertical Flexbox Layout

    In CSS, we can also define vertical flexbox by setting flex-direction: column.

    Example

    <!DOCTYPE html><html lang="en"><head><style>
    
      .container {
         display: flex;
         flex-direction: column;
         justify-content: center;
         align-items: center;
         height: 100vh;
      }
      .item {
         background-color: lightseagreen;
         padding: 20px;
         margin: 10px;
         border: 3px solid #ccc;
      }
    </style></head><body><div class="container"><div class="item">Item 1</div><div class="item">Item 2</div><div class="item">Item 3</div></div></body></html>

    Flexbox Justify Content Property

    The justify-content property is commonly used inside flexbox containers to align flexbox items inside container. There are several values possible for this property, for a complete reference of justify-content property visit our tutorial on justify-content property.

    Some of the commonly used values of justify-content is noted down below. There are lot more values associated with it.

    // Align Item at center of main axis
    justify-content: center; 
    
    // Align Item at start of main axis
    justify-content: flex-start; 
    
    // Align Item at end of main axis
    justify-content: flex-end; 
    
    // Align Item at left side of main axis
    justify-content: left;
    
    // Align Item at right side of main axis
    justify-content: right;

    Flexbox Align Items Property

    The align-items property in CSS is used to align flex items across cross axis (vertical axis in a row layout, horizontal axis in a column layout) of the container. There are several values associated with this property. To learn more about align-items property visit our tutorial on CSS Align Items.

    // Align items at start of cross axis of container
    align-items: flex-start;
    
    // Align items at end of cross axis of container
    align-items: flex-end;
    
    // Align items at center of cross axis of container
    align-items: center;
    
    // Align baselines of items (For items with variable sizes)align-items: baseline;
    
    // Stretch items along cross axis to fill container
    align-items: stretch;

    Centering a Div using Flexbox

    Centering a div element( or any other elements ) is always a challenging and most discussed problem in CSS. With the help of CSS flexbox we can easily center a div element inside a container. We have to use justify-content and align-items properties to center items, following code shows how this is done.

    Example

    <!DOCTYPE html><html lang="en"><head><style>
    
      .flex-container {
         display: flex;
         /* Center horizontally */
         justify-content: center;
         /* Center Vertically */
         align-items: center;
         border: 1px solid #ccc;
         height: 250px;
         background-color: grey;
      }
      .flex-item {
         background-color: lightblue;
         border: 1px solid #333;
         padding: 5px;
         height: 70px;
         width: 70px;
      }  
    </style></head><body><div class="flex-container"><div class="flex-item">
         This div is in center of container
      &lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Flexbox Wrap Property

    Flexbox with wrap property allows items within a container to move to next line when there is no enough space in a single line. This helps to maintain a responsive layout.

    Following code demonstrates how to use flexbox to create a responsive layout that centers its items and wraps them to fit within the available space. For a complete guidance on flex wrap, visit our tutorial on CSS flex-wrap.

    .container{display: flex;flex-wrap: wrap;justify-content: center;align-items: center;}.item{padding: 20px;margin: 10px;/* base size 100px */flex: 1 1 100px;}

    Flexbox Align Self Property

    In CSS, we have align-self property which can be used to override align-items property set on container. This helps to dynamically place each items at special locations inside container.

    Following code shows how to use align-self property. Here we can see that align-items: stretch is not applicable to second and third items, this property is override by align-self property of items.

    .container{display: flex;flex-direction: row;justify-content: space-around;align-items: stretch;height: 250px;}.item{background-color: lightpink;padding: 20px;margin: 10px;border: 1px solid #ccc;}.item:nth-child(2){/* Center 2nd item along the cross axis */align-self: center;}.item:nth-child(3){/* Align 3rd item at the end of the cross axis */align-self: flex-end;}

    CSS Flexbox Container Properties

    Following are all the CSS properties that can be applied to flex container.

    PropertyValueExample
    flex-directionSets the flex direction of the flex items.Try It
    flex-wrapSets whether flex items should wrap onto the next lineTry It
    justify-contentSets the alignment of flex items along the main axis.Try It
    align-itemsSets the alignment of flex items along the cross axis.Try It
    align-contentSets the alignment and spacing of flex lines within the flex container.Try It
    flex-flowSets both the flex-direction and flex-wrap properties.Try It

    CSS Flexbox Items Properties

    Following are all the CSS properties that can be applied to flex items.

    PropertyValueExample
    flex-growSets flex item to grow within a flex container.Try It
    flex-shrinkSets flex item to shrink in size to fit the available space.Try It
    flex-basisSets the initial size of a flex item.Try It
    flexShorthand property, combines three flex-related properties: flex-grow, flex-shrink, and flex-basis.Try It
    align-selfSets the alignment of a specific flex item along the cross-axis.Try It
    orderUsed to specify the order in which flex items appear inside their flex container.Try It