Author: Saim Khalid

  • CSS Text

    Formatting Text with CSS

    CSS provides several properties that allows you to define various text styles such as color, alignment, spacing, decoration, transformation, etc. very easily and effectively.

    The commonly used text properties are: text-aligntext-decorationtext-transformtext-indentline-heightletter-spacingword-spacing, and more. These properties give you precise control over the visual appearance of the characterswordsspaces, and so on.

    Let’s see how to set these text properties for an element in more detail.

    Text Color

    The color of the text is defined by the CSS color property.

    The style rule in the following example will define the default text color for the page

    Example

    body {
    
    color: #434343;
    }

    Although, the color property seems like it would be a part of the CSS text, but it is actually a standalone property in CSS. See the tutorial on CSS color to learn more about the color property.


    Text Alignment

    The text-align property is used to set the horizontal alignment of the text.

    Text can be aligned in four ways: to the left, right, centre or justified (straight left and right margins).

    Let’s take a look at an example to understand how this property basically works.

    Example

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

    Note: When text-align is set to justify, each line is stretched so that every line has equal width (except the last line), and the left and right margins are straight. This alignment is generally used in publications such as magazines and newspapers.

    Let’s take a look at the following illustration to understand what these values actually mean.

    Text Align Illustration

    Text Decoration

    The text-decoration property is used to set or remove decorations from text.

    This property typically accepts one of the following values: underlineoverlineline-through, and none. You should avoid underline text that is not a link, as it might confuse the visitor.

    Let’s try out the following example to understand how it basically works:

    Example

    h1 {
    
    text-decoration: overline;
    } h2 {
    text-decoration: line-through;
    } h3 {
    text-decoration: underline;
    }

    Removing the Default Underline from Links

    The text-decoration property is extensively used to remove the default underline from the HTML hyperlinks. You can further provide some other visual cues to make it stand out from the normal text, for example, using dotted border instead of solid underline.

    Let’s take a look at the following example to understand how it basically works:

    Example

    a {
    
    text-decoration: none;
    border-bottom: 1px dotted;
    }

    Note: When you create an HTML link, browsers built in style sheet automatically underline it and applies a blue color, so that the readers can clearly see which text is clickable.


    Text Transformation

    The text-transform property is used to set the cases for a text.

    Text are often written in mixed case. However, in certain situations you may want to display your text in entirely different case. Using this property you can change an element’s text content into uppercase or lowercase letters, or capitalize the first letter of each word without modifying the original text.

    Let’s try out the following example to understand how it basically works:

    Example

    h1 {
    
    text-transform: uppercase;
    } h2 {
    text-transform: capitalize;
    } h3 {
    text-transform: lowercase;
    }

    Text Indentation

    The text-indent property is used to set the indentation of the first line of text within a block of text. It is typically done by inserting the empty space before the first line of text.

    The size of the indentation can be specified using percentage (%), length values in pixels, ems, etc.

    The following style rule will indent the first line of the paragraphs by 100 pixels.

    Example

    p {
    
    text-indent: 100px;
    }

    Note: Whether the text is indented from the left or from the right depends on the direction of text inside the element, defined by the CSS direction property.


    Letter Spacing

    The letter-spacing property is used to set extra spacing between the characters of text.

    This property can take a length value in pixels, ems, etc. It may also accept negative values. When setting letter spacing, a length value indicates spacing in addition to the default inter-character space.

    Let’s check out the following example to understand how it really works:

    Example

    h1 {
    
    letter-spacing: -3px;
    } p {
    letter-spacing: 10px;
    }

    Word Spacing

    The word-spacing property is used to specify additional spacing between the words.

    This property can accept a length value in pixels, ems, etc. Negative values are also allowed.

    Let’s try out the following example to understand how this property works:

    Example

    p.normal {
    
    word-spacing: 20px;
    } p.justified {
    word-spacing: 20px;
    text-align: justify;
    } p.preformatted {
    word-spacing: 20px;
    white-space: pre;
    }

    Note: Word spacing can be affected by text justification. Also, even though whitespace is preserved, spaces between words are affected by the word-spacing property.


    Line Height

    The line-height property is used to set the height of the text line.

    It is also called leading and commonly used to set the distance between lines of text.

    The value of this property can be a number, a percentage (%), or a length in pixels, ems, etc.

    Example

    p {
    
    line-height: 1.2;
    }

    When the value is a number, the line height is calculated by multiplying the element’s font size by the number. While, percentage values are relative to the element’s font size.

    Note: Negative values for the line-height property are not allowed. This property is also a component of the CSS font shorthand property.

    If the value of the line-height property is greater than the value of the font-size for an element, this difference (called the “leading”) is cut in half (called the “half-leading”) and distributed evenly on the top and bottom of the in-line box. Let’s check out an example:

    Example

    p {
    
    font-size: 14px;
    line-height: 20px;
    background-color: #f0e68c;
    }

    See the tutorial on CSS3 text overflow in the advanced section to learn how to handle overflowed text. Also see the CSS3 text shadow section to learn how to apply shadow effect on text.

  • CSS Fonts

    Styling Fonts with CSS

    Choosing the right font and style is very crucial for the readability of text on a page.

    CSS provide several properties for styling the font of the text, including changing their face, controlling their size and boldness, managing variant, and so on.

    The font properties are: font-familyfont-stylefont-weightfont-size, and font-variant.

    Let’s discuss each of these font properties one by one in more detail.

    Font Family

    The font-family property is used to specify the font to be used to render the text.

    This property can hold several comma-separated font names as a fallback system, so that if the first font is not available on the user’s system, browser tries to use the second one, and so on.

    Hence, list the font that you want first, then any fonts that might fill in for the first if it is not available. You should end the list with a generic font family which are five — serifsans-serifmonospacecursive and fantasy. A typical font family declaration might look like this:

    Example

    body {
    
    font-family: Arial, Helvetica, sans-serif;
    }

    Note: If the name of a font family contains more than one word, it must be placed inside quotation marks, like "Times New Roman""Courier New""Segoe UI", etc.

    The most common font families used in web design are serif and sans-serif, because they are more suitable for reading. While monospace fonts are commonly used to display code, because in this typeface each letter takes up the same space which looks like typewritten text.

    The cursive fonts look like cursive writing or handwriting. The fantasy font represents artistic font, but they’re not used widely because of poor availability across the operating systems.

    Difference Between Serif and Sans-serif Fonts

    Serif fonts have small line or stroke at the extremities of characters, whereas sans-serif fonts are straighter and do not have these small strokes. See the following illustration.

    Serif vs Sans-serif Font

    To learn about commonly used font combinations, please check out the reference on web safe fonts.


    Font Style

    The font-style property is used to set the font face style for the text content of an element.

    The font style can be normalitalic or oblique. The default value is normal.

    Let’s try out the following example to understand how it basically works:

    Example

    p.normal {
      font-style: normal;
    }
    p.italic {
      font-style: italic;
    }
    p.oblique {
      font-style: oblique;
    }

    Note: At first glance both oblique and italic font styles appear the same thing, but there is a difference. The italic style uses an italic version of the font while oblique style on the other hand is simply a slanted or sloped version of the normal font.


    Font Size

    The font-size property is used to set the size of font for the text content of an element.

    There are several ways to specify the font size values e.g. with keywords, percentage, pixels, ems, etc.

    Setting Font Size with Pixels

    Setting the font size in pixel values (e.g. 14px, 16px, etc.) is a good choice when you need the pixel accuracy. Pixel is an absolute unit of measurement which specifies a fixed length.

    Let’s try out the following example to understand how it basically works:

    Example

    h1 {
    
    font-size: 24px;
    } p {
    font-size: 14px;
    }

    Defining the font sizes in pixel is not considered very accessible, because the user cannot change the font size from the browser settings. For instance, users with limited or low vision may wish to set the font size much larger than the size specified by you.

    Therefore, you should avoid using the pixels values and use the values that are relative to the user’s default font size instead if you want to create an inclusive design.

    Tip: The text can also be resized in all browsers using the zoom feature. However, this feature resizes the entire page, not just the text. The W3C recommends using the em or percentage (%) values in order to create more robust and scalable layouts.

    Setting Font Size with EM

    The em unit refers to the font size of the parent element. When defining the font-size property, 1em is equal to the size of the font that applies to the parent of the element.

    So, if you set a font-size of 20px on the body element, then 1em = 20px and 2em = 40px.

    However, if you haven’t set the font size anywhere on the page, then it is the browser default, which is normally 16px. Therefore, by default 1em = 16px, and 2em = 32px.

    Let’s take a look at the following example to understand how it basically works:

    Example

    h1 {
    
    font-size: 2em;    /* 32px/16px=2em */
    } p {
    font-size: 0.875em;    /* 14px/16px=0.875em */
    }

    Using the Combination of Percentage and EM

    As you’ve observed in the above example the calculation of em values doesn’t look straightforward. To simplify this, a popular technique is to set the font-size for the body element to 62.5% (that is 62.5% of the default 16px), which equates to 10px, or 0.625em.

    Now you can set the font-size for any elements using em units, with an easy-to-remember conversion, by dividing the px value by 10. This way 10px = 1em12px = 1.2em14px = 1.4em16px = 1.6em, and so on. Let’s take a look at the following example:

    Example

    body {
    
    font-size: 62.5%;    /* font-size 1em = 10px */
    } p {
    font-size: 1.4em;    /* 1.4em = 14px */
    } p span {
    font-size: 2em;    /* 2em = 28px */
    }

    Setting Font Size with Root EM

    To make things even more simpler CSS3 has introduced rem unit (short for “root em”) which is always relative to the font-size of the root element (html), regardless of where the element lies in the document (unlike em which is relative to parent element’s font size).

    This means that 1rem is equivalent to the font size of the html element, which is 16px by default in most browsers. Let’s try out an example to understand how it actually works:

    Example

    html {
    
    font-size: 62.5%;    /* font-size 1em = 10px */
    } p {
    font-size: 1.4rem;    /* 1.4rem = 14px */
    } p span {
    font-size: 2rem;    /* 2rem = 20px (not 28px) */
    }

    Setting Font Size with Keywords

    CSS provide several keywords that you can use to define font sizes.

    An absolute font size can be specified using one of the following keywords: xx-smallx-smallsmallmediumlargex-largexx-large. Whereas, a relative font size can be specified using the keywords: smaller or larger. Let’s try out an example and see how it works:

    Example

    body {
    
    font-size: large;
    } h1 {
    font-size: larger;
    } p {
    font-size: smaller;
    }

    Note: The keyword medium is equivalent to the browsers default font-size, which is normally 16px. Likewise, xx-small is the equivalent of 9 pixels, x-small is 10 pixels, small is 13 pixels, large is 18 pixels, x-large is 24 pixels, and xx-large is 32 pixels.

    Tip: By setting a font size on the body element, you can set the relative font sizing everywhere else on the page, giving you the ability to easily scale the font size up or down accordingly.

    Setting Font Size with Viewport Units

    The font sizes can be specified using viewport units such as vw or vh.

    Viewport units refer to a percentage of the browser’s viewport dimensions, where 1vw = 1% of viewport width, and 1vh = 1% of viewport height. Hence, if the viewport is 1600px wide, 1vw is 16px.

    Try out the following example by resizing the browser window and see how it works:

    Example

    body {
    
    font-size: 1vw;
    } h1 {
    font-size: 3vw;
    }

    However, there is a problem with the viewport units. On small screens fonts become so small that they are hardly readable. To prevent this you can utilize CSS calc() function, like this:

    Example

    html { 
    
    font-size: calc(1em + 1vw); 
    } h1 {
    font-size: 3rem;
    }

    In this example, even if the viewport width becomes 0, the font-size would be at least 1em or 16px.

    You further utilize CSS media queries to create better responsive and fluid typography.


    Font Weight

    The font-weight property specifies the weight or boldness of the font.

    This property can take one of the following values: normalboldbolderlighter100200300400500600700800900 and inherit.

    • The numeric values 100900 specify the font weights, where each number represents a weight greater than its predecessor. 400 is same as normal & 700 is same as bold.
    • The bolder and lighter values are relative to the inherited font weight, while the other values such as normal and bold are absolute font weights.

    Let’s try out an example to understand how this property basically works:

    Example

    p {
    
    font-weight: bold;
    }

    Note: Most of the fonts are only available in a limited number of weights; often they are available only in normal and bold. In case, if a font is not available in the specified weight, an alternate will be chosen that is the closest available weight.


    Font Variant

    The font-variant property allows the text to be displayed in a special small-caps variation.

    Small-caps or small capital letters are slightly different to normal capital letters, in which lowercase letters appear as smaller versions of the corresponding uppercase letters.

    Try out the following example to understand how this property actually works:

    Example

    p {
    
    font-variant: small-caps;
    }

    The value normal removes small caps from the text which is already formatted that way.

  • CSS Background

    Setting Background Properties

    Background plays an important role in the visual presentation of a web page.

    CSS provide several properties for styling the background of an element, including coloring the background, placing images in the background and managing their positioning, etc.

    The background properties are background-colorbackground-imagebackground-repeatbackground-attachment and background-position.

    In the following section we will discuss each of these properties in more detail.

    Background Color

    The background-color property is used to set the background color of an element.

    The following example demonstrates how to set the background color of the whole page.

    Example

    body {
    
    background-color: #f0e68c;
    }

    Color values in CSS are most often specified in the following formats:

    • a color name – like “red”
    • a HEX value – like “#ff0000”
    • an RGB value – like “rgb(255, 0, 0)”

    Please check out the tutorial on CSS color to learn more about specifying color values.


    Background Image

    The background-image property set an image as a background of an HTML element.

    Let’s check out the following example which sets the background image for the whole page.

    Example

    body {
    
    background-image: url("images/tile.png");
    }

    Note: When applying the background image to an element, make sure that the image you choose does not affect the readability of the element’s text content.

    Tip: By default browser repeats or tiles the background image both horizontally and vertically to fill the entire area of an element. You can control this with background-repeat property.


    Background Repeat

    The background-repeat property allows you to control how a background image is repeated or tiled in the background of an element. You can set a background image to repeat vertically (y-axis), horizontally (x-axis), in both directions, or in neither direction.

    Let’s try out the following example which demonstrates how to set the gradient background for a web page by repeating the sliced image horizontally along the x-axis.

    Example

    body {
    
    background-image: url("images/gradient.png");
    background-repeat: repeat-x;
    }

    Similarly, you can use the value repeat-y to repeat the background image vertically along the y-axis, or the value no-repeat to prevent the repetition altogether.

    Example

    body {
    
    background-image: url("images/texture.png");
    background-repeat: no-repeat;
    }

    Let’s take a look at the following illustration to understand how this property actually works.

    Background Repeat Illustration

    Background Position

    The background-position property is used to control the position of the background image.

    If no background position has been specified, the background image is placed at the default top-left position of the element i.e. at (0,0), let’s try out the following example:

    Example

    body {
    
    background-image: url("images/robot.png");
    background-repeat: no-repeat;
    }

    In the following example, the background image is positioned at top-right corner.

    Example

    body {
    
    background-image: url("images/robot.png");
    background-repeat: no-repeat;
    background-position: right top;
    }

    Note: If two values are specified for the background-position property, the first value represents the horizontal position, and the second represents the vertical position. If only one value is specified, the second value is assumed to be center.

    Besides keywords, you can also use percentage or length values, such as px or em for this property.

    Let’s take a look at the following illustration to understand how this property actually works.

    Background Position Illustration

    Background Attachment

    The background-attachment property determines whether the background image is fixed with regard to the viewport or scrolls along with the containing block.

    Let’s try out the following example to understand how it basically works:

    Example

    body {
    
    background-image: url("images/bell.png");
    background-repeat: no-repeat;
    background-attachment: fixed;
    }

    The Background Shorthand Property

    As you can see in the examples above, there are many properties to consider when dealing with the backgrounds. However, it is also possible to specify all these properties in one single property to shorten the code or avoid extra typing. This is called a shorthand property.

    The background property is a shorthand property for setting all the individual background properties, i.e., background-colorbackground-imagebackground-repeatbackground-attachment and the background-position property at once. Let’s see how this works:

    Example

    body {
    
    background-color: #f0e68c;
    background-image: url("images/smiley.png");
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: 250px 25px;
    }

    Using the shorthand notation the above example can be written as:

    Example

    body {
    
    background: #f0e68c url("images/smiley.png") no-repeat fixed 250px 25px;
    }

    When using the background shorthand property the order of the property values should be.

    background: color image repeat attachment position;

    If the value for an individual background property is missing or not specified while using the shorthand notation, the default value for that property will be used instead, if any.

    Note: The background properties do not inherit like the color property, but the parent element’s background will be visible through by default, because of the initial or default transparent value of the background-color CSS property.

  • CSS Color

    Setting Color Property

    The color property defines the text color (foreground color in general) of an element.

    For instance, the color property specified in the body selector defines the default text color for the whole page. Let’s try out the following example to see how it works:

    Example

    body {
    
    color: #ff5722;
    }

    Note: The color property normally inherits the color value from their parent element, except the case of anchor elements. For example, if you specify color for the body element it will automatically be passed down to the headings, paragraphs, etc.


    Defining Color Values

    Colors in CSS most often specified in the following formats:

    • a color keyword – like “red”, “green”, “blue”, “transparent”, etc.
    • a HEX value – like “#ff0000”, “#00ff00”, etc.
    • an RGB value – like “rgb(255, 0, 0)”

    CSS3 has introduced several other color formats such as HSL, HSLA and RGBA that also support alpha transparency. We’ll learn about them in greater detail in CSS3 color chapter.

    For now, let’s stick to the basic methods of defining the color values:

    Color Keywords

    CSS defines the few color keywords which lets you specify color values in an easy way.

    These basic color keywords are: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow. The color names are case-insensitive.

    Example

    h1 {
    
    color: red;
    } p {
    color: purple;
    }

    Modern web browsers however practically support many more color names than what are defined in the CSS standard, but to be on the safer side you should use hex color values instead.

    See the reference on CSS color names, for a complete list of possible color names.


    HEX Color Values

    Hex (short for Hexadecimal) is by far the most commonly used method of defining color on the web.

    Hex represent colors using a six-digit code, preceded by a hash character, like #rrggbb, in which rrgg, and bb represents the red, green and blue component of the color respectively.

    The value of each component can vary from 00 (no color) and FF (full color) in hexadecimal notation, or 0 and 255 in decimal equivalent notation. Thus #ffffff represents white color and #000000 represents black color. Let’s take a look the following example:

    Example

    h1 {
    
    color: #ffa500;
    } p {
    color: #00ff00;
    }

    Note: Hexadecimal or Hex refers to a numbering scheme that uses 16 characters as its base. It uses the numbers 0 through 9 and the letters A, B, C, D, E and F which corresponds to the decimal numbers 10, 11, 12, 13, 14 and 15 respectively.

    Tip: If hexadecimal code of a color has value pairs, it can also be written in shorthand notation to avoid extra typing, for example, the hex color value #ffffff can be also be written as #fff, #000000 as #000, #00ff00 as #0f0, #ffcc00 as #fc0, and so on.


    RGB Color Values

    Colors can be defined in the RGB model (Red, Green, and Blue) using the rgb() functional notation.

    The rgb() function accepts three comma-separated values, which specify the amount of red, green, and blue component of the color. These values are commonly specified as integers between 0 to 255, where 0 represent no color and 255 represent full or maximum color.

    The following example specifies the same color as in the previous example but in RGB notation.

    Example

    h1 {
    
    color: rgb(255, 165, 0);
    } p {
    color: rgb(0, 255, 0);
    }

    Note: You can also specify RGB values inside the rgb() function in percentage, where 100% represents full color, and 0% (not simply 0) represents no color. For example, you can specify the red color either as rgb(255, 0, 0) or rgb(100%, 0%, 0%).

    Tip: If R, G, and B are all set to 255, i.e. rgb(255, 255, 255), the color would be white. Likewise, if all channels are set to 0, i.e. rgb(0, 0, 0), the color would be black. Play with the RGB values in the following demonstration to understand how it actually works.

    rgb(127, 127, 127)

    Red: 127

    Green: 127

    Blue: 127


  • CSS Syntax

    Understanding CSS Syntax

    A CSS stylesheet consists of a set of rules that are interpreted by the web browser and then applied to the corresponding elements such as paragraphs, headings, etc. in the document.

    A CSS rule have two main parts, a selector and one or more declarations:

    CSS Selector Syntax Illustration

    The selector specifies which element or elements in the HTML page the CSS rule applies to.

    Whereas, the declarations within the block determines how the elements are formatted on a webpage. Each declaration consists of a property and a value separated by a colon (:) and ending with a semicolon (;), and the declaration groups are surrounded by curly braces {}.

    The property is the style attribute you want to change; they could be font, color, background, etc. Each property has a value, for example color property can have value either blue or #0000FF etc.

    h1 {color:blue; text-align:center;}

    To make the CSS more readable, you can put one declaration on each line, like this:

    Example

    h1 {
    
    color: blue;
    text-align: center;
    }

    In the example above h1 is a selector, color and text-align are the CSS properties, and the given blue and center are the corresponding values of these properties.

    Note: A CSS declaration always ends with a semicolon “;“, and the declaration groups are always surrounded by the curly brackets “{}“.


    Writing Comments in CSS

    Comments are usually added with the purpose of making the source code easier to understand. It may help other developer (or you in the future when you edit the source code) to understand what you were trying to do with the CSS. Comments are significant to programmers but ignored by browsers.

    A CSS comment begins with /*, and ends with */, as shown in the example below:

    Example

    /* This is a CSS comment */
    h1 {
    
    color: blue;
    text-align: center;
    } /* This is a multi-line CSS comment that spans across more than one line */ p {
    font-size: 18px;
    text-transform: uppercase;
    }

    You can also comment out part of your CSS code for debugging purpose, as shown here:

    Example

    h1 {
    
    color: blue;
    text-align: center;
    } /* p {
    font-size: 18px;
    text-transform: uppercase;
    } */

    Case Sensitivity in CSS

    CSS property names and many values are not case-sensitive. Whereas, CSS selectors are usually case-sensitive, for instance, the class selector .maincontent is not the same as .mainContent.

    Therefore, to be on safer side, you should assume that all components of CSS rules are case-sensitive.

    You will learn about the various types of CSS selectors in the next chapter.

  • CSS Getting Started

    Getting Started with CSS

    In this tutorial you’ll learn how easy it is to add style and formatting information to the web pages using CSS. But, before we begin, make sure that you have some working knowledge of HTML.

    If you’re just starting out in the world of web development, start learning from here »

    Without further ado, let’s get started with the Cascading Style Sheets (CSS).

    Including CSS in HTML Documents

    CSS can either be attached as a separate document or embedded in the HTML document itself. There are three methods of including CSS in an HTML document:

    • Inline styles — Using the style attribute in the HTML start tag.
    • Embedded styles — Using the <style> element in the head section of a document.
    • External style sheets — Using the <link> element, pointing to an external CSS file.

    In this tutorial we will cover all these three methods for inserting CSS one by one.

    Note: The inline styles have the highest priority, and the external style sheets have the lowest. It means if you specify styles for an element in both embedded and external style sheets, the conflicting style rules in the embedded style sheet would override the external style sheet.

    Inline Styles

    Inline styles are used to apply the unique style rules to an element by putting the CSS rules directly into the start tag. It can be attached to an element using the style attribute.

    The style attribute includes a series of CSS property and value pairs. Each "property: value" pair is separated by a semicolon (;), just as you would write into an embedded or external style sheets. But it needs to be all in one line i.e. no line break after the semicolon, as shown here:

    Example

    <h1 style="color:red; font-size:30px;">This is a heading</h1>
    <p style="color:green; font-size:22px;">This is a paragraph.</p>
    <div style="color:blue; font-size:14px;">This is some text content.</div>

    Using the inline styles are generally considered as a bad practice. As style rules are embedded directly inside the HTML tag, it causes the presentation to become mixed with the content of the document; which makes the code hard to maintain and negates the purpose of using CSS.

    Note: It’s become impossible to style pseudo-elements and pseudo-classes with inline styles. You should, therefore, avoid the use of style attributes in your code. Using external style sheets is the preferred way to add styles to the HTML documents.


    Embedded Style Sheets

    Embedded or internal style sheets only affect the document they are embedded in.

    Embedded style sheets are defined in the <head> section of an HTML document using the <style> element. You can define any number of <style> elements in an HTML document but they must appear between the <head> and </head> tags. Let’s take a look at an example:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;title&gt;My HTML Document&lt;/title&gt;
    &lt;style&gt;
        body { background-color: YellowGreen; }
        p { color: #fff; }
    &lt;/style&gt;
    </head> <body>
    &lt;h1&gt;This is a heading&lt;/h1&gt;
    &lt;p&gt;This is a paragraph of text.&lt;/p&gt;
    </body> </html>

    Tip: The type attribute of the <style> and <link> tag (i.e. type="text/css") defines the language of the style sheet. This attribute is purely informative. You can omit this since CSS is the standard and default style sheet language in HTML5.


    External Style Sheets

    An external style sheet is ideal when the style is applied to many pages of the website.

    An external style sheet holds all the style rules in a separate document that you can link from any HTML file on your site. External style sheets are the most flexible because with an external style sheet, you can change the look of an entire website by changing just one file.

    You can attach external style sheets in two ways — linking and importing.

    Linking External Style Sheets

    Before linking, we need to create a style sheet first. Let’s open your favorite code editor and create a new file. Now type the following CSS code inside this file and save it as “style.css”.

    Example

    body {
    
    background: lightyellow;
    font: 18px Arial, sans-serif;
    } h1 {
    color: orange;
    }

    An external style sheet can be linked to an HTML document using the <link> tag. The <link> tag goes inside the <head> section, as you can see in the following example:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;title&gt;My HTML Document&lt;/title&gt;
    &lt;link rel="stylesheet" href="css/style.css"&gt;
    </head> <body>
    &lt;h1&gt;This is a heading&lt;/h1&gt;
    &lt;p&gt;This is a paragraph of text.&lt;/p&gt;
    </body> </html>

    Tip: Among all the three methods, using external style sheet is the best method for defining and applying styles to the HTML documents. As you can clearly see with external style sheets, the affected HTML file require minimal changes in the markup.

    Importing External Style Sheets

    The @import rule is another way of loading an external style sheet. The @import statement instructs the browser to load an external style sheet and use its styles.

    You can use it in two ways. The simplest is within the header of your document. Note that, other CSS rules may still be included in the <style> element. Here’s an example:

    Example

    <style>
    
    @import url("css/style.css");
    p {
        color: blue;
        font-size: 16px;
    }
    </style>

    Similarly, you can use the @import rule to import a style sheet within another style sheet.

    Example

    @import url("css/layout.css");
    @import url("css/color.css");
    body {
    
    color: blue;
    font-size: 14px;
    }
  • CSS Tutorial

    CSS stands for Cascading Style Sheets. CSS is a standard style sheet language used for describing the presentation (i.e. the layout and formatting) of the web pages.

    Prior to CSS, nearly all of the presentational attributes of HTML documents were contained within the HTML markup (specifically inside the HTML tags); all the font colors, background styles, element alignments, borders and sizes had to be explicitly described within the HTML.

    As a result, development of the large websites became a long and expensive process, since the style information were repeatedly added to every single page of the website.

    To solve this problem CSS was introduced in 1996 by the World Wide Web Consortium (W3C), which also maintains its standard. CSS was designed to enable the separation of presentation and content. Now web designers can move the formatting information of the web pages to a separate style sheet which results in considerably simpler HTML markup, and better maintainability.

    CSS3 is the latest version of the CSS specification. CSS3 adds several new styling features and improvements to enhance the web presentation capabilities.

    Note: Our CSS tutorial will help you to learn the fundamentals of the latest CSS3 language, from the basic to advanced topics step-by-step. If you’re a beginner, start with the basic section and gradually move forward by learning a little bit every day.


    What You Can Do with CSS

    There are lot more things you can do with CSS.

    • You can easily apply same style rules on multiple elements.
    • You can control the presentation of multiple pages of a website with a single style sheet.
    • You can present the same page differently on different devices.
    • You can style dynamic states of elements such as hover, focus, etc. that isn’t possible otherwise.
    • You can change the position of an element on a web page without changing the markup.
    • You can alter the display of existing HTML elements.
    • You can transform elements like scale, rotate, skew, etc. in 2D or 3D space.
    • You can create animations and transitions effects without using any JavaScript.
    • You can create print friendly version of your web pages.

    The list does not end here, there are many other interesting things that you can do with CSS. You will learn about all of them in detail in upcoming chapters.


    Advantages of Using CSS

    The biggest advantage of CSS is that it allows the separation of style and layout from the content of the document. Here are some more advantages, why one should start using CSS?

    • CSS Save Lots of Time — CSS gives lots of flexibility to set the style properties of an element. You can write CSS once; and then the same code can be applied to the groups of HTML elements, and can also be reused in multiple HTML pages.
    • Easy Maintenance — CSS provides an easy means to update the formatting of the documents, and to maintain the consistency across multiple documents. Because the content of the entire set of web pages can be easily controlled using one or more style sheets.
    • Pages Load Faster — CSS enables multiple pages to share the formatting information, which reduces complexity and repetition in the structural contents of the documents. It significantly reduces the file transfer size, which results in a faster page loading.
    • Superior Styles to HTML — CSS has much wider presentation capabilities than HTML and provide much better control over the layout of your web pages. So you can give far better look to your web pages in comparison to the HTML presentational elements and attributes.
    • Multiple Device Compatibility — CSS also allows web pages to be optimized for more than one type of device or media. Using CSS the same HTML document can be presented in different viewing styles for different rendering devices such as desktop, cell phones, etc.

    Tip: Now most of the HTML attributes are being deprecated and it’s not recommended to use. So it’s a good idea to use as much CSS as possible to increase the adaptability your website and make them compatible to future browsers, as well.


    What This Tutorial Covers

    This CSS tutorial series covers all the fundamentals of CSS, including the idea of selectors, methods of setting colors and backgrounds, way of formatting fonts and text, styling UI elements such as hyperlinks, lists, tables, etc. as well as the concept of CSS box model, and so on.

    Once you’re comfortable with the basics, you’ll move on to next level that explains the way of setting dimension and alignment of elements, methods for positioning elements on a web page, using image sprites, as well as the concept of relative and absolute units, visual formatting model, display and visibility, layers, pseudo classes and elements, media dependent style sheets, and so on.

    Finally, you’ll explore some advanced features introduced in CSS3 like gradient colors, drop shadow effect, 2D and 3D transforms, alpha transparency, as well as the method of creating transition and animation effect, flex layouts, filter effect, the concept of media queries, and more.

    Tip: Every chapter in this tutorial contains lots of real-world examples that you can try and test using an online editor. These examples will help you to better understand the concept or topic. It also contains smart workarounds as well as useful tips and important notes.

  • HTML JavaScript

    A Script is a small program which is used with HTML to make web pages more attractive, dynamic and interactive, such as an alert popup window on mouse click. Currently, the most popular scripting language is JavaScript used for websites.

    Example:

    <!DOCTYPE html>  
    
    <html>  
    
    <body>  
    
    <h1>JavaScript Date and Time example</h1>  
    
    <button type="button"  
    
    onclick="document.getElementById('demo').innerHTML = Date()">  
    
    Click me to display Date and Time.</button>  
    
    <p id="demo"></p>  
    
    </body>  
    
    </html>

    HTML <script> Tag

    The HTML <script> tag is used to specify a client-side script. It may be an internal or external JavaScript which contains scripting statements, hence we can place <script> tag within <body> or <head> section.

    It is mainly used to manipulate images, form validation and change content dynamically. JavaScript uses document.getElementById() method to select an HTML element.

    Example:

    
    
    1. <!DOCTYPE html>  
    2. <html>  
    3. <body>  
    4. <h2>Use JavaScript to Change Text</h2>  
    5. <p id="demo"></p>  
    6. <script>  
    7. document.getElementById("demo").innerHTML = "Hello JavaTpoint";  
    8. </script>  
    9. </body>  
    10. </html>

    HTML events with JavaScript

    An event is something which user does, or browser does such as mouse click or page loading are examples of events, and JavaScript comes in the role if we want something to happen on these events.

    HTML provides event handler attributes which work with JavaScript code and can perform some action on an event.

    Syntax:

    <element event = "JS code">   

    Example:

    <input type="button" value="Click" onclick="alert('Hi, how are you')"> 

    Output:

    Click Event Example

    Click on the button and you csn see a pop-up window with a message

    HTML can have following events such as:

    • Form events: reset, submit, etc.
    • Select events: text field, text area, etc.
    • Focus event: focus, blur, etc.
    • Mouse events: select, mouseup, mousemove, mousedown, click, dblclick, etc.

    Following are the list for Window event attributes:

    Event Event NameHandler NameOccurs when
    onBlurblurWhen form input loses focus
    onClickclickWhen the user clicks on a form element or a link
    onSubmitsubmitWhen user submits a form to the server.
    onLoadloadWhen page loads in a browser.
    onFocusfocusWhen user focuses on an input field.
    onSelectselectWhen user selects the form input filed.

    Note: You will learn more about JavaScript Events in our JavaScript tutorial.

    Let’s see what JavaScript can do:

    1) JavaScript can change HTML content.

    Example:

    <!DOCTYPE html>  
    
    <html>  
    
    <body>  
    
    <p>JavaScript can change the content of an HTML element:</p>  
    
    <button type="button" onclick="myFunction()">Click Me!</button>  
    
    <p id="demo"></p>  
    
    <script>  
    
    function myFunction() {   
    
        document.getElementById("demo").innerHTML = "Hello JavaTpoint!";  
    
    }  
    
    </script>  
    
    </body>  
    
    </html>

    2) JavaScript can change HTML style

    Example:

    <!DOCTYPE html>  
    
    <html>  
    
    <body>  
    
    <p id="demo">JavaScript can change the style of an HTML element.</p>  
    
    <script>  
    
    function myFunction() {  
    
        document.getElementById("demo").style.fontSize = "25px";   
    
        document.getElementById("demo").style.color = "brown";  
    
        document.getElementById("demo").style.backgroundColor = "lightgreen";         
    
    }  
    
    </script>  
    
    <button type="button" onclick="myFunction()">Click Me!</button>  
    
    </body>  
    
    </html>

    3) JavaScript can change HTML attributes.

    Example:

    <!DOCTYPE html>  
    
    <html>  
    
    <body>  
    
    <script>  
    
    function light(sw) {  
    
        var pic;  
    
        if (sw == 0) {  
    
            pic = "pic_lightoff.png"  
    
        } else {  
    
            pic = "pic_lighton.png"  
    
        }  
    
        document.getElementById('myImage').src = pic;  
    
    }  
    
    </script>  
    
    <img id="myImage" src="pic_lightoff.png" width="100" height="180">  
    
    <p>  
    
    <button type="button" onclick="light(1)">Light On</button>  
    
    <button type="button" onclick="light(0)">Light Off</button>  
    
    </p>  
    
    </body>  
    
    </html>

    Use External Script

    Suppose, you have various HTML files which should have same script, then we can put our JavaScript code in separate file and can call in HTML file. Save JavaScript external files using .js extension.

    Note: Do not add <script> tag in the external file, and provide the complete path where you have put the JS file.

    Syntax:

    1. <script type=”text/javascript” src=”URL “></script>  

    Example:

    <!DOCTYPE html>  
    
    <html>  
    
       <head>  
    
        <script type="text/javascript" src="external.js"></script>  
    
        </head>  
    
         <body>  
    
          <h2>External JavaScript Example</h2>  
    
           <form onsubmit="fun()">  
    
             <label>Enter your name:</label><br>  
    
          <input type="text" name="uname" id="frm1"><br>  
    
           <label>Enter your Email-address:</label><br>    
    
          <input type="email" name="email"><br>  
    
          <input type="submit">  
    
      </form>  
    
     </body>  
    
     </html>

    JavaScript code:

    function fun() {  
    
           var x = document.getElementById("frm1").value;  
    
            alert("Hi"+" "+x+ "you have successfully submitted the details");  
    
        }

    Output:

    HTML JavaScript

    HTML <noscript> Tag

    HTML <noscript> tag is used to write disabled script in the browser. The text written within <noscript></noscript> tag is not displayed on the browser.

    Example:

    <!DOCTYPE html>  
    
    <html>  
    
    <body>  
    
    <p id="demo"></p>  
    
    <script>  
    
    document.getElementById("demo").innerHTML = "Hello JavaScript!";  
    
    </script>  
    
    <noscript>This text is not visible in the browser.</noscript>  
    
    </body>  
    
    </html>
  • HTML iframes

    HTML Iframe is used to display a nested webpage (a webpage within a webpage). The HTML <iframe> tag defines an inline frame, hence it is also called as an Inline frame.

    An HTML iframe embeds another document within the current HTML document in the rectangular region.

    The webpage content and iframe contents can interact with each other using JavaScript.

    Iframe Syntax

    An HTML iframe is defined with the <iframe> tag:

    <iframe src="URL"></iframe>  

    Here, “src” attribute specifies the web address (URL) of the inline frame page.

    Set Width and Height of iframe

    You can set the width and height of iframe by using “width” and “height” attributes. By default, the attributes values are specified in pixels but you can also set them in percent. i.e. 50%, 60% etc.

    Example: (Pixels)

    <!DOCTYPE html>    
    
    <html>    
    
    <body>    
    
    <h2>HTML Iframes example</h2>    
    
    <p>Use the height and width attributes to specify the size of the iframe:</p>    
    
    <iframe src="https://www.javatpoint.com/" height="300" width="400"></iframe>    
    
    </body>    
    
    </html>

    Example: (Percentage)

    <!DOCTYPE html>    
    
    <html>    
    
    <body>    
    
    <h2>HTML Iframes</h2>    
    
    <p>You can use the height and width attributes to specify the size of the iframe:</p>    
    
    <iframe src="https://www.javatpoint.com/" height="50%" width="70%"></iframe>    
    
    </body>    
    
    </html>

    You can also use CSS to set the height and width of the iframe.

    Example:

    
    
    1. <!DOCTYPE html>    
    2. <html>    
    3. <body>    
    4. <h2>HTML Iframes</h2>    
    5. <p>Use the CSS height and width properties to specify the size of the iframe:</p>    
    6. <iframe src="https://www.javatpoint.com/" style="height:300px;width:400px"></iframe>    
    7. </body>    
    8. </html> 

    Remove the border of iframe

    By default, an iframe contains a border around it. You can remove the border by using <style> attribute and CSS border property.

    Example:

    
    
    1. <!DOCTYPE html>    
    2. <html>    
    3. <body>    
    4. <h2>Remove the Iframe Border</h2>    
    5. <p>This iframe example doesn't have any border</p>     
    6. <iframe src="https://www.javatpoint.com/" style="border:none;"></iframe>    
    7. </body>    
    8. </html> 

    You can also change the size, color, style of the iframe’s border.

    Example:

    <!DOCTYPE html>    
    
    <html>    
    
    <body>    
    
    <h2>Custom Iframe Border</h2>    
    
    <iframe src="https://www.javatpoint.com/" style="border:2px solid tomato;"></iframe>    
    
    </body>    
    
    </html>

    Iframe Target for a link

    You can set a target frame for a link by using iframe. Your specified target attribute of the link must refer to the name attribute of the iframe.

    Example:

    <!DOCTYPE html>  
    
    <html>  
    
    <body>  
    
      
    
    <h2>Iframe - Target for a Link</h2>  
    
    <iframe height="300px" width="100%" src="new.html" name="iframe_a"></iframe>  
    
    <p><a href="https://www.javatpoint.com" target="iframe_a">JavaTpoint.com</a></p>  
    
    <p>The name of iframe and link target must have same value else link will not open as a frame. </p>  
    
      
    
    </body>  
    
    </html>
    HTML iframes

    new.hmtl output code:

    <!DOCTYPE html> <html> <head> <style> p{ font-size: 50px; color: red;} </style> </head> <body style="background-color: #c7f15e;"> <p>This is a link below the ifarme click on link to open new iframe. </p> </body> </html>

    Embed YouTube video using iframe

    You can also add a YouTube video on your webpage using the <iframe> tag. The attached video will be played at your webpage and you can also set height, width, autoplay, and many more properties for the video.

    Following are some steps to add YouTube video on your webpage:

    • Goto YouTube video which you want to embed.
    • Click on SHARE ➦ under the video.
    • Click on Embed <> option.
    • Copy HTML code.
    • Paste the code in your HTML file
    • Change height, width, and other properties (as per requirement).

    Example:

    1. <iframe width=”550″ height=”315″ src=”https://www.youtube.com/embed/JHq3pL4cdy4″ frameborder=”0″ allow=”accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture” allowfullscreen style=”padding:20px;”></iframe>  
    2.         <iframe width=”550″ height=”315″ src=”https://www.youtube.com/embed/O5hShUO6wxs” frameborder=”0″ allow=”accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture” style=”padding:20px;”>></iframe> 

    Output:

    HTML iframes

    Attributes of <iframe>

    Attribute nameValueDescription
    allowfullscreenIf true then that frame can be opened in full screen.
    heightPixelsIt defines the height of the embedded iframe, and the default height is 150 px.
    nametextIt gives the name to the iframe. The name attribute is important if you want to create a link in one frame.
    frameborder1 or 0It defines whether iframe should have a border or not. (Not supported in HTML5).
    WidthPixelsIt defines the width of embedded frame, and default width is 300 px.
    srcURLThe src attribute is used to give the path name or file name which content to be loaded into iframe.
    sandbox
    This attribute is used to apply extra restrictions for the content of the frame
    allow-formsIt allows submission of the form if this keyword is not used then form submission is blocked.
    allow-popupsIt will enable popups, and if not applied then no popup will open.
    allow-scriptsIt will enable the script to run.
    allow-same-originIf this keyword is used then the embedded resource will be treated as downloaded from the same source.
    srcdocThe srcdoc attribute is used to show the HTML content in the inline iframe. It overrides the src attribute (if a browser supports).
    scrolling
    It indicates that browser should provide a scroll bar for the iframe or not. (Not supported in HTML5)
    autoScrollbar only shows if the content of iframe is larger than its dimensions.
    yesAlways shows scroll bar for the iframe.
    noNever shows scrollbar for the iframe.
  • HTML Id Attribute

    The id attribute is used to specify the unique ID for an element of the HTML document. It allocates the unique identifier which is used by the CSS and the JavaScript for performing certain tasks.

    Note: In the Cascading Style sheet (CSS), we can easily select an element with the specific id by using the # symbol followed by id.

    Note: JavaScript can access an element with the given ID by using the getElementById() method.

    Syntax

    <tag id="value">  

    Example 1: The following example describes how to use the id attribute in CSS document:

    <!DOCTYPE html>  
    
    <html>  
    
    <head>  
    
    <title>  
    
    Example of Id attribute in CSS  
    
    </title>  
    
    <style>  
    
    #Cars {  
    
    padding: 40px;  
    
    background-color: lightblue;  
    
    color: black;      
    
    text-align: center;  
    
    }   
    
      
    
    #Bikes  
    
    {  
    
    padding: 50px;  
    
    background-color: lightGreen;  
    
    text-align: center;  
    
    }  
    
    </style>  
    
    </head>  
    
    <body>  
    
    <p> Use CSS to style an element with the id: </p>  
    
    <h1 id="Cars"> Cars </h1>  
    
    <h1 id="Bikes"> Bikes </h1>  
    
    </body>  
    
    </html>

    Output:

    HTML Id Attribute

    Example 2: The following example describes how to use the ID attribute in JavaScript.

    <!DOCTYPE html>  
    
    <html>   
    
    <head>   
    
    <title> Date Attribute </title>   
    
    <script>   
    
    function viewdate() {   
    
    var x = document.getElementById("dob").value;   
    
    document.getElementById("demo").innerHTML = x;   
    
    </script>   
    
    </head>   
    
    <body>   
    
    Employee Name: <input type="text" placeholder="Your Good name"/>   
    
    <br>  
    
    <br>  
    
    Date of Joining:   
    
    <input type="date" id="dob">  
    
    <br>   
    
    <button onclick="viewdate()"> Submit   
    
    </button>   
    
    <br>  
    
    <h2 id="demo"> </h2>   
    
    </body>   
    
    </html>

    Output:

    HTML Id Attribute