Blog

  • CSS Sprites

    What is a Sprite

    Sprites are two-dimensional images which are made up of combining small images into one larger image at defined X and Y coordinates.

    To display a single image from the combined image, you could use the CSS background-position property, defining the exact position of the image to be displayed.

    Advantage of Using CSS Image Sprite

    A web page with many images, particularly many small images, such as icons, buttons, etc. can take a long time to load and generates multiple server requests.

    Using the image sprites instead of separate images will significantly reduce the number of HTTP requests a browser makes to the server, which can be very effective for improving the loading time of web pages and overall site performance.

    Note: Reducing the number of HTTP requests has the major impact on reducing response time that makes the web page more responsive for the user.

    Checkout the following examples and you will see one visible difference; when you place the mouse pointer over the browser icons in non-sprite version for the first time the hover image will appear after some time, it happens because the hover image is loaded from the server on mouse hover, since the normal and hover images are two different images.

    Whereas in sprite version, since all images are combined in a single image the hover image is displayed immediately on mouse hover that results in smooth hover effect.

    FirefoxChromeExplorerSafariOperaExample A
    FirefoxChromeExplorerSafariOperaExample B

    Using CSS sprite technique demonstrated in the: [EXAMPLE – B]; we were able to reduce the number of HTTP requests by 9 and the total file size of the image(s) by 38.2 KB as compared to the [EXAMPLE – A];. That’s a pretty huge improvement for such a small example. Imagine what you could do on a complete website.

    The whole process of creating this example is explained below.


    Making the Image Sprite

    We made this sprite image by combining 10 separate images in a single image (mySprite.png). You can create your own sprite using any image editing tool you like.

    Sprite Image Illustration

    Tip: For the sake of simplicity, we have used all icons of same size, and place them closely to each other for easy offset calculation.


    Display an Icon from Image Sprite

    Finally, utilizing CSS, we can display just the part of an image sprite we need.

    First of all, we will create the class .sprite that will load our sprite image. This is to avoid repetition, because all items share the same background-image.

    Example

    .sprite {
    
    background: url("images/mySprite.png") no-repeat;
    }

    Now, we must define a class for each item we want to display. For example, to display Internet Explorer icon form the image sprite the CSS code would be.

    Example

    .ie {
    
    width: 50px; /* Icon width */
    height: 50px; /* Icon height */
    display: inline-block; /* Display icon as inline block */
    background-position: 0 -200px; /* Icon background position in sprite */
    }

    Now the question arises, how did we get those pixel values for background-position? Let’s find out. The first value is the horizontal position, and second is the vertical position of background. As the upper-left corner of Internet Explorer icon touches the left edge so its horizontal distance from the starting point i.e. top-left corner of the image sprite is 0, and since it is placed on the 5th position so its vertical distance from the starting point of image sprite is 4 X 50px = 200px, because height of each icon is 50px.

    To show the Internet Explorer icon we have to move its upper-left corner to the starting point i.e. top-left corner of image sprite (mySprite.png). Also, since this icon is placed at the vertical distance of 200px, we will need to shift the whole background-image (mySprite.png) vertically up by 200px, which requires us to apply the value as a negative number that is -200px, because the negative value makes it go vertically up whereas a positive value would move it down. However, it doesn’t require a horizontal offset, since there are no pixels before the upper-left corner of the Internet Explorer icon.

    Tip: Just play around with the value of background-position property in the upcoming examples and you will quickly learn how the offsets work.


    Creating a Navigation Menu Using CSS Image Sprite

    In the previous section we have learned, how to display an individual icon from an image sprite. This is the easiest way to use image sprites, now we are going one step ahead by building a navigation menu with rollover effect as demonstrated in [EXAMPLE – B].

    Here we will use the same sprite image (mySprite.png) to create our navigation menu.

    Foundation HTML for Navigation

    We will start by creating our navigation menu with an HTML unordered list.

    Example

    <ul class="menu">
    
    &lt;li class="firefox"&gt;&lt;a href="#"&gt;Firefox&lt;/a&gt;&lt;/li&gt;
    &lt;li class="chrome"&gt;&lt;a href="#"&gt;Chrome&lt;/a&gt;&lt;/li&gt;
    &lt;li class="ie"&gt;&lt;a href="#"&gt;Explorer&lt;/a&gt;&lt;/li&gt;
    &lt;li class="opera"&gt;&lt;a href="#"&gt;Opera&lt;/a&gt;&lt;/li&gt;
    &lt;li class="safari"&gt;&lt;a href="#"&gt;Safari&lt;/a&gt;&lt;/li&gt;
    </ul>

    Applying the CSS on Navigation

    The following sections will describes you how to convert the simple unordered list given in example above to a spite image based navigation using the CSS.

    Step 1: Resetting the List Structure

    By default, HTML unordered lists are displayed with bullets. We’ll need to remove the default bullets by setting the list-style-type attribute to none.

    Example

    ul.menu {
    
    list-style-type: none;
    } ul.menu li {
    padding: 5px;
    font-size: 16px;
    font-family: "Trebuchet MS", Arial, sans-serif;
    }

    Step 2: Setting Common Properties for Each Links

    In this step we will set all the common CSS properties that all links are going to share. Such as, colorbackground-imagedisplaypadding, etc.

    Example

    ul.menu li a {
    
    height: 50px;
    line-height: 50px;
    display: inline-block;
    padding-left: 60px; /* To sift text off the background-image */
    color: #3E789F;
    background: url("images/mySprite.png") no-repeat; /* As all link share the same background-image */
    }

    Step 3: Setting Default State of Each Links

    Now, we must define a class for each menu item, because every item in the image sprite has different background-position. For example, Firefox icon is placed at the starting point i.e. top-left corner of the image sprite, so there is no need to shift the background-image. Hence the vertical and horizontal position of the background in this case would be 0. Similarly, you can define background-position for other icons within the image sprite.

    Example

    ul.menu li.firefox a {
    
    background-position: 0 0;
    } ul.menu li.chrome a {
    background-position: 0 -100px;
    } ul.menu li.ie a {
    background-position: 0 -200px;
    } ul.menu li.safari a {
    background-position: 0 -300px;
    } ul.menu li.opera a {
    background-position: 0 -400px;
    }

    Step 4: Adding Hover States of Links

    Adding hover states owns the same principle as adding the above links. Just move their upper-left corner to the starting point (i.e. top-left corner) of the image sprite as we have done above. You can simply calculate the background-position using the following formula:

    Vertical position of hover state = Vertical position of normal state - 50px

    As rollover images are just below the default state and height of each icon is equal to 50px. The hover state of icons also doesn’t require a horizontal offset, since there are no pixels before the upper-left corner of them.

    Example

    ul.menu li.firefox a:hover {
    
    background-position: 0 -50px;
    } ul.menu li.chrome a:hover {
    background-position: 0 -150px;
    } ul.menu li.ie a:hover {
    background-position: 0 -250px;
    } ul.menu li.safari a:hover {
    background-position: 0 -350px;
    } ul.menu li.opera a:hover {
    background-position: 0 -450px;
    }

    Done! Here is our final HTML and CSS code after combining the whole process:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Example of Sprite Navigation Menu</title>
    <style>
    
    ul.menu {
        list-style-type: none;
    }
    ul.menu li {
        padding: 5px;
        font-size: 16px;
        font-family: "Trebuchet MS", Arial, sans-serif;
    }
  • CSS Media Types

    Introduction to Media Types

    One of the most important features of style sheets is that, you can specify separate style sheets for different media types. This is one of the best ways to build printer friendly Web pages — Just assign a different style sheet for the “print” media type.

    Some CSS properties are only designed for certain media. For example, the page-break-after property only applies to paged media. However there are several properties that may be shared by different media types, but may require different values for that property. The font-size property for example can be used for both screen and print media, but possibly with different values.

    A document usually needs a larger font on a computer screen as compared to the paper for better readability, also sans-serif fonts are considered easier to read on the screen, while serif fonts are popular for printing. Therefore it is necessary to specify that a style sheet, or a set of style rules, applies to certain media types.

    Creating Media Dependent Style Sheets

    Three methods are commonly used to specify the media dependencies for style sheets:

    Method 1: Using the @media At-rules

    The @media rule is used to define different style rules for different media types in a single style sheet. It is usually followed by a comma-separated list of media types and the CSS declarations block containing the styles rules for target media.

    The style declaration in the example below tells the browser to display body content in 14 pixels Arial font on the screen, but in case of printing it will be in a 12 points Times font. However the value of line-height property is set to 1.2 for both of them:

    Example

    @media screen{
    
    body {
        color: #32cd32;
        font-family: Arial, sans-serif;
        font-size: 14px;
    }
    } @media print {
    body {
        color: #ff6347;
        font-family: Times, serif;
        font-size: 12pt;
    }
    } @media screen, print {
    body {
        line-height: 1.2;
    }
    }

    Note: Style rules outside of @media rules apply to all media types that the style sheet applies to. At-rules inside @media are invalid in CSS2.1.


    Method 2: Using the @import At-rules

    The @import rule is another way of setting style information for a specific target media — Just specify the comma-separated media types after the URL of the imported style sheets.

    Example

    @import url("css/screen.css") screen;
    @import url("css/print.css") print;
    body {
    
    background: #f5f5f5;
    line-height: 1.2;
    }

    The print media type in the @import statement instructs the browser to load an external style sheet (print.css) and use its styles only for print media.

    Note: All @import statements must occur at the beginning of a style sheet, before any declarations. Any style rule specified in the style sheet itself override the conflicting style rules in the imported style sheets.


    Method 3: Using the <link> element

    The media attribute on the <link> element is used to specify the target media for an external style sheet within the HTML document.

    Example

    <link rel="stylesheet" media="all" href="css/common.css">
    <link rel="stylesheet" media="screen" href="css/screen.css">
    <link rel="stylesheet" media="print" href="css/print.css">

    In this example the media attribute instructs the browser to load an external style sheet “screen.css” and use its styles only for screen while “print.css” for printing purpose.

    Tip: You can also specify multiple media types (each separated with comma e.g. media="screen, print") as well as media quires to the <link> element.


    Different Media Types

    The following table lists the various media types that may used to target different types of devices such as printers, handheld devices, computer screens etc.

    Media TypeDescription
    allUsed for all media type devices.
    auralUsed for speech and sound synthesizers.
    brailleUsed for braille tactile feedback devices.
    embossedUsed for paged braille printers.
    handheldUsed for small or handheld devices — usually small screen devices such as mobile phones or PDAs.
    printUsed for printers.
    projectionUsed for projected presentations, for example projectors.
    screenUsed primarily for color computer screens.
    ttyUsed for media using a fixed-pitch character grid — such as teletypes, terminals, or portable devices with limited display capabilities.
    tvUsed for television-type devices — low resolution, color, limited-scrollability screens, sound available.
  • CSS Pseudo-elements

    What is Pseudo-element

    The CSS pseudo-elements allow you to style the elements or parts of the elements without adding any IDs or classes to them. It will be really helpful in the situations when you just want to style the first letter of a paragraph to create the drop cap effect or you want to insert some content before or after an element, etc. only through style sheet.

    CSS3 introduced a new double-colon (::) syntax for pseudo-elements to distinguish between them and pseudo-classes. The new syntax of the pseudo-element can be given with:

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

    These are the following most commonly used pseudo-elements:

    The ::first-line Pseudo-element

    The ::first-line pseudo-element applies special style to the first line of a text.

    The style rules in the following example formats the first line of text in a paragraph. The length of first line depends on the size of the browser window or containing element.

    Example

    p::first-line {
    
    color: #ff0000;
    font-variant: small-caps;
    }

    Note: The CSS properties that can be applied to the ::first-line pseudo-element are: font properties, background properties, color, word-spacing, letter-spacing, text-decoration, vertical-align, text-transform, line-height.


    The ::first-letter Pseudo-element

    The ::first-letter pseudo-element is used to add a special style to the first letter of the first line of a text. The style rules in the following example formats the first letter of the paragraph of text and create the effect like drop cap.

    Example

    p::first-letter {
    
    color: #ff0000;
    font-size: xx-large;
    }

    Note: The CSS properties that can be applied to the ::first-letter pseudo-element are: font properties, text-decoration, text-transform, letter-spacing, word-spacing, line-height, float, vertical-align (only if ‘float’ is ‘none’), color, margin and padding properties, border properties, background properties.


    The ::before and ::after Pseudo-element

    The ::before and ::after pseudo-elements can be used to insert generated content either before or after an element’s content. The content CSS property is used in conjunction with these pseudo-elements, to insert the generated content.

    This is very useful for further decorating an element with rich content that should not be part of the page’s actual markup. You can insert regular strings of text or an embedded object such as image and other resources using these pseudo-elements.

    Example

    h1::before {
    
    content: url("images/marker-left.gif");
    } h1::after {
    content: url("images/marker-right.gif");
    }

    Pseudo-elements and CSS Classes

    Generally we need to style only a certain paragraph of text or other block-level elements with these pseudo-elements. That’s where declaring a class to the pseudo-element comes into play. The pseudo-elements can be combined with the CSS classes to produce the effect particularly for the elements having that class.

    The style rules in the following example will display the first letter of all paragraphs with the class="article", in green and size of xx-large.

    Example

    p.article::first-letter {
    
    color: #00ff00;
    font-size: xx-large;
    }
  • CSS Pseudo-classes

    What is Pseudo-class

    The CSS pseudo-classes allow you to style the dynamic states of an element such as hover, active and focus state, as well as elements that are existing in the document tree but can’t be targeted via the use of other selectors without adding any IDs or classes to them, for example, targeting the first or last child elements.

    A pseudo-class starts with a colon (:). Its syntax can be given with:

    selector:pseudo-class { property: value; }

    The following section describes the most commonly used pseudo-classes.

    Anchor Pseudo-classes

    Using anchor pseudo-classes links can be displayed in different ways:

    These pseudo-classes let you style unvisited links differently from visited ones. The most common styling technique is to remove underlines from visited links.

    Example

    a:link {
    
    color: blue;
    } a:visited {
    text-decoration: none;
    }

    Some anchor pseudo-classes are dynamic — they’re applied as a result of user interaction with the document like on hover, or on focus etc.

    Example

    a:hover {
    
    color: red;
    } a:active {
    color: gray;
    } a:focus {
    color: yellow;
    }

    These pseudo-classes change how the links are rendered in response to user actions.

    • :hover applies when a user places cursor over the element, but does not select it.
    • :active applies when the element is activated or clicked.
    • :focus applies when the element has keyboard focus.

    Note: To make these pseudo-classes work perfectly, you must define them in the exact order — :link:visited:hover:active:focus.


    The :first-child Pseudo-class

    The :first-child pseudo-class matches an element that is the first child element of some other element. The selector ol li:first-child in the example below select the first list item of an ordered list and removes the top border form it.

    Example

    ol li:first-child {
    
    border-top: none;
    }

    Note: To make :first-child to work in Internet Explorer 8 and earlier versions, a <!DOCTYPE> must be declared at the top of document.


    The :last-child Pseudo-class

    The :last-child pseudo-class matches an element that is the last child element of some other element. The selector ul li:last-child in the example below select the last list item from an unordered list and removes the right border from it.

    Example

    ul li:last-child {
    
    border-right: none;
    }

    Note: The CSS :last-child selector does not work in Internet Explorer 8 and earlier versions. Supports in Internet Explorer 9 and above.


    The :nth-child Pseudo-class

    The CSS3 introduces a new :nth-child pseudo-class that allows you to target one or more specific children of a given parent element. The basic syntax of this selector can be given with :nth-child(N), where N is an argument, which can be a number, a keyword (even or odd), or an expression of the form xn+y where x and y are integers (e.g. 1n2n2n+1, …).

    Example

    table tr:nth-child(2n) td {
    
    background: #eee;
    }

    The style rules in the example above simply highlight the alternate table row, without adding any IDs or classes to the <table> elements.

    Tip: The CSS :nth-child(N) selector is very useful in the situations where you have to select the elements that appears inside the document tree in a specific interval or pattern like at even or odd places, etc.


    The :lang Pseudo-class

    The language pseudo-class :lang allows constructing selectors based on the language setting for specific tags. The :lang pseudo-class in the example below defines the quotation marks for <q> elements that are explicitly given a language value of no.

    Example

    q:lang(no) {
    
    quotes: "~" "~";
    } /* HTML code snippet */ <p>Some text <q lang="no">A quote in a paragraph</q> Some text.</p>

    Note: Internet Explorer up to version 7 does not support the :lang pseudo-class. IE8 supports only if a <!DOCTYPE> is specified.


    Pseudo-classes and CSS Classes

    Pseudo-classes can be combined with CSS classes.

    The link with class="red", in the example below will be displayed in red.

    Example

    a.red:link {    /* style rule */
    
    color: #ff0000;
    } <a class="red" href="#">Click me</a> /* HTML code snippet */
  • CSS Alignment

    Text Alignment

    Text inside the block-level elements can aligned by setting the text-align properly.

    Example

    h1 {
    
    text-align: center;
    } p {
    text-align: left;
    }

    See tutorial on CSS Text to learn more about text formatting.


    Center Alignment Using the margin Property

    Center alignment of a block-level element is one of the most important implications of the CSS margin property. For example, the <div> container can be aligned horizontally center by setting the left and right margins to auto.

    Example

    div {
    
    width: 50%;
    margin: 0 auto;
    }

    The style rules in the above example center align the <div> element horizontally.

    Note: The value auto for the margin property will not work in Internet Explorer 8 and earlier versions, unless a <!DOCTYPE> is specified.


    Aligning Elements Using the position Property

    The CSS position in conjunction with the leftrighttop and bottom property can be used to align elements with respect to the document’s viewport or containing parent element.

    Example

    .up {
    
    position: absolute;
    top: 0;
    } .down {
    position: absolute;
    bottom: 0;
    }

    To learn more about positioning elements, see the tutorial on CSS positioning.


    Left and Right Alignment Using the float Property

    The float CSS property can be used to align an element to the left or right of its containing block in such a way that other content may flow along its side.

    Hence, if an element is floated to the left, content will flow along its right side. Conversely, if the element is floated to the right, content will flow along its left side.

    Example

    div {
    
    width: 200px;
    float: left;
    }

    Clearing Floats

    One of the most confusing things about working with the float-based layouts is the collapsing parent. The parent element doesn’t stretch up automatically to accommodate the floated elements. Though, this isn’t always obvious if the parent doesn’t contain any visually noticeable background or borders, but it is important to be aware of and must dealt with to prevent strange layout and cross-browser problem. See the illustration below:

    CSS Collapsed Parent

    You can see the <div> element doesn’t stretch up automatically to accommodate the floated images. This problem can be fixed by clearing the float after the floated elements in the container but before the closing tag of the container element.


    Fixing the Collapsed Parent

    There are several ways to fix the CSS collapsing parent issue. The following section will describe you these solutions along with the live examples.

    Solution 1: Float the Container

    The easiest way to fix this problem is to float the containing parent element.

    Example

    .container {
    
    float: left;
    background: #f2f2f2;
    }

    Warning: This fix will only work in a limited number of circumstances, since floating the parent may produce unexpected results.

    Solution 2: Using the Empty Div

    This is an old fashioned way but is an easy solution and works across every browser.

    Example

    .clearfix {
    
    clear: both;
    } /* html code snippet */ <div class="clearfix"> </div>

    You could also do this by means of a <br> tag. But this method is not recommended since it adds nonsemantic code to your markup.

    Solution 3: Using the :after Pseudo-Element

    The :after pseudo-element in conjunction with the content property has been used quite extensively to resolve float-clearing issues.

    Example

    .clearfix:after {
    
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
    }

    The class .clearfix is applied to any container that has floating children.

  • CSS Float

    Floating Elements with CSS

    You can float elements to the left or right, but only applies to the elements that generate boxes that are not absolutely positioned. Any element that follows the floated element will flow around the floated element on the other side.

    The float property may have one of the three values:

    ValueDescription
    leftThe element floats on the left side of its containing block.
    rightThe element floats on the right side of its containing block.
    noneRemoves the float property from an element.

    How Elements Float

    A floated element is taken out of the normal flow and shifted to the left or right as far as possible in the space available of the containing element.

    Other elements normally flow around the floated items, unless they are prevented from doing so by their clear property. Elements are floated horizontally, which means that an element can only be floated left or right, not up or down.

    Example

    img {
    
    float: left;
    }

    If several floating elements are placed adjacently, they will float next to each other if there is horizontal room. If there is not enough room for the float, it is shifted downward until either it fits or there are no more floating elements present.

    Example

    .thumbnail {
    
    float: left;
    width: 125px;
    height: 125px;
    margin: 10px;
    }

    Turning off Float Using Clear Property

    Elements that comes after the floating element will flow around it. The clear property specifies which sides of an element’s box other floating elements are not allowed.

    Example

    .clear {
    
    clear: left;
    }

    Note: This property can clear an element only from floated boxes within the same block. It doesn’t clear the element from floated child boxes within the element itself. To learn more about clearing float see tutorial on CSS Alignment.

  • CSS Layers

    Stacking Elements in Layers Using z-index Property

    Usually HTML pages are considered two-dimensional, because text, images and other elements are arranged on the page without overlapping. However, in addition to their horizontal and vertical positions, boxes can be stacked along the z-axis as well i.e. one on top of the other by using the CSS z-index property. This property specifies the stack level of a box whose position value is one of absolutefixed, or relative.

    The z-axis position of each layer is expressed as an integer representing the stacking order for rendering. An element with a larger z-index overlaps an element with a lower one.

    z-index property can help you to create more complex webpage layouts. Following is the example which shows how to create layers in CSS.

    Example

    .box {
    
    position: absolute;
    left: 10px;
    top: 20px;
    z-index: 2;
    }

  • CSS Visibility

    Controlling the Visibility of Elements

    You can use the visibility property to control whether an element is visible or not. This property can take one of the following values listed in the table below:

    ValueDescription
    visibleDefault value. The box and its contents are visible.
    hiddenThe box and its content are invisible, but still affect the layout of the page.
    collapseThis value causes the entire row or column to be removed from the display. This value is used for row, row group, column, and column group elements.
    inheritSpecifies that the value of the visibility property should be inherited from the parent element i.e. takes the same visibility value as specified for its parent.

    The style rule visibility: collapse; however removes the internal table elements, but it does not affect the layout of the table in any other way. The space normally occupied by the table elements will be filled by the subsequent siblings.

    Note: If the style rule visibility: collapse; is specified for other elements rather than the table elements, it causes the same behavior as hidden.


    CSS Visibility vs Display

    The display and visibility CSS properties appear to be the same thing, but they are in fact quite different and often confuse those new to web development.

    • visibility: hidden; hides the element, but it still takes up space in the layout. Child element of a hidden box will be visible if their visibility is set to visible.
    • display: none; turns off the display and removes the element completely from the document. It does not take up any space, even though the HTML for it is still in the source code. All child elements also have their display turned off, even if their display property is set to something other than none.

    Check out the following demo to find out how display and visibility affect the layouts.


    CSS Visibility vs Display DemoReset All

    Click on me i will removed
    Click on me i will hide
    Click on me i will removed
    Click on me i will hide
  • CSS Display

    CSS Display Property

    The CSS specification defines the default display value for all the elements, e.g. the <div> element is rendered as block, while the <span> element is displayed inline.

    Changing the Default Display Value

    Overriding the default display value of an element is an important implication of the display property. For example, changing an inline-level element to be displayed as block-level element or changing the block-level element to be displayed as an inline-level element.

    Note: The CSS display property is one of the most powerful and useful properties in all the CSS. It can be very useful for creating web pages that looks in a different way, but still follow the web standards.

    The following section describes you the most commonly used CSS display values.

    Display Block

    The block value of the display property forces an element to behave like block-level element, like a <div> or <p> element. The style rules in the following example displays the <span> and <a> elements as block-level elements:

    Example

    span {
    
    display: block;
    } a {
    display: block;
    }

    Note: Changing the display type of an element only changes the display behavior of an element, NOT the type of element it is. For example, an inline element set to display: block; is not allowed to have a block element nested inside of it.


    Display Inline

    The inline value of the display property causes an element to behave as though it were an inline-level element, like a <span> or an <a> element. The style rules in the following example displays the <p> and <li> elements as inline-level elements:

    Example

    p {
    
    display: inline;
    } ul li {
    display: inline;
    }

    Display Inline-Block

    The inline-block value of the display property causes an element to generate a block box that will be flowed with surrounding content i.e. in the same line as adjacent content. The following style rules displays the <div> and <span> elements as inline-block:

    Example

    div {
    
    display: inline-block;
    } span {
    display: inline-block;
    }

    Display None

    The value none simply causes an element to generate no boxes at all. Child elements do not generate any boxes either, even if their display property is set to something other than none. The document is rendered as though the element did not exist in the document tree.

    Example

    h1 {
    
    display: none;
    } p {
    display: none;
    }
  • CSS Visual Formatting

    CSS Visual Formatting Model

    The CSS visual formatting model is the algorithm that is used to process the documents for visual media. In the visual formatting model, each element in the document tree generates zero or more boxes according to the box model.

    The layout of these boxes is depends on the following factors:

    • box dimensions.
    • type of the element (block or inline).
    • positioning scheme (normal flow, float, and absolute positioning).
    • relationships between elements in the document tree.
    • external information e.g. viewport size, built-in dimensions of images, etc.

    Note: The document tree is the hierarchy of elements encoded in the source document. Every element in the document tree has exactly one parent, with the exception of the root element, which has none.


    Type of Boxes Generated in CSS

    Every element displayed on a web page generates a rectangular box. The following section describes the types of boxes that may be generated by an element.

    Block-level Elements and Block Boxes

    Block-level elements are those elements that are formatted visually as blocks (i.e. takes up the full width available), with a line break before and after the element. For example, paragraph element (<p>), headings (<h1> to <h6>), divisions (<div>) etc.

    Generally, block-level elements may contain inline elements and other block-level elements.


    Inline-level Elements and Inline Boxes

    Inline-level elements are those elements of the source document that do not form new blocks of content; the content is distributed in lines. For example, emphasized pieces of text within a paragraph (<em>), spans (<span>), strong element (<strong>) etc.

    Inline elements typically may only contain text and other inline elements.

    Note: Unlike block-level elements, an inline-level element only takes up as much width as necessary, and does not force line breaks.

    You can change how an element will be displayed on a web page using the CSS display property. You will learn about the display property in next chapter.