CSS Interview Questions

28 Questions
HTML & CSS

HTML & CSS

Web DevelopmentFrontend

Question 2

Explain the difference between inline, internal, and external CSS.

Answer:

CSS (Cascading Style Sheets) is used to style and format HTML documents. There are three main ways to apply CSS to HTML: inline, internal, and external. Here's a breakdown of each method:

1. Inline CSS

  • Definition: Inline CSS is applied directly within an HTML element using the style attribute.
  • Usage: It's used to apply a unique style to a single element.
  • Syntax Example:
    <p style="color: blue; font-size: 14px;">This is a paragraph.</p>
  • Pros:
    • Quick to apply for small changes or testing.
    • No need to create or reference a separate stylesheet.
  • Cons:
    • Hard to maintain for large projects.
    • Does not allow for CSS reuse across multiple elements.
    • Increases HTML file size and complexity.

2. Internal (Embedded) CSS

  • Definition: Internal CSS is defined within the <style> tag in the <head> section of an HTML document.
  • Usage: It's used when you want to style a single HTML document without creating an external stylesheet.
  • Syntax Example:
    <head>
        <style>
            p {
                color: blue;
                font-size: 14px;
            }
        </style>
    </head>
    <body>
        <p>This is a paragraph.</p>
    </body>
  • Pros:
    • Easier to manage and apply styles across multiple elements within the same document.
    • Keeps styles centralized in the document.
  • Cons:
    • Styles are not reusable across multiple HTML documents.
    • Can clutter the HTML document if there are many styles.

3. External CSS

  • Definition: External CSS is written in a separate .css file and linked to an HTML document using the <link> tag.
  • Usage: It's the most common and recommended way to apply styles, especially in larger websites.
  • Syntax Example:
    • CSS File (styles.css):
      p {
          color: blue;
          font-size: 14px;
      }
    • HTML File:
      <head>
          <link rel="stylesheet" href="styles.css">
      </head>
      <body>
          <p>This is a paragraph.</p>
      </body>
  • Pros:
    • Allows for global styles across multiple pages.
    • Easier to maintain and update as all styles are in one file.
    • Keeps HTML files cleaner and more manageable.
    • Reduces page load time by caching the CSS file.
  • Cons:
    • Requires an extra HTTP request to fetch the CSS file (though it’s cached after the first load).
    • Slightly more complex setup compared to inline or internal CSS.

Summary

  • Inline CSS is best for quick, one-off styles.
  • Internal CSS is suitable for single-page applications or prototypes.
  • External CSS is ideal for maintaining consistent, reusable styles across a multi-page website.

Recent job openings