diff --git a/README.md b/README.md index db1f2cc..576540e 100644 --- a/README.md +++ b/README.md @@ -1,197 +1,733 @@ -

- Top 50 CSS interview - questions and answers in 2021. -

- You can check all - 50 - CSS interview questions here ๐Ÿ‘‰ - https://devinterview.io/dev/css-interview-questions -



๐Ÿ”น 1. Explain the three main ways to apply CSS styles to a web page

Answer:

Using the inline style attribute on an element

<div>
-    <p style="color: maroon;"></p>
-</div>

Using a <style> block in the <head> section of your HTML

<head>
-    <title>CSS Refresher</title>
-    <style>
-        body {
-            font-family: sans-serif;
-            font-size: 1.2em;
-        }
-    </style>
-</head>

Loading an external CSS file using the <link> tag

<head>
-    <title>CSS Refresher</title>
-    <link rel="stylesheet" href="/css/styles.css" />
-</head>
Source: goskills.com   


๐Ÿ”น 2. What is CSS?

Answer:

CSS stands for Cascading Style Sheets. CSS is used to define styles for your web pages, including the design, layout and variations in display for different devices and screen sizes.

CSS was intended to allow web professionals to separate the content and structure of a website's code from the visual design.

Source: w3schools.com   


๐Ÿ”น 3. How to use variables in Sass?

Answer:

Think of variables as a way to store information that you want to reuse throughout your stylesheet. You can store things like colors, font stacks, or any CSS value you think you'll want to reuse. Sass uses the $ symbol to make something a variable.

$font-stack:    Helvetica, sans-serif;
-$primary-color: #333;
-
-body {
-  font: 100% $font-stack;
-  color: $primary-color;
-}
Source: sass-lang.com   


๐Ÿ”น 4. Explain CSS sprites, and how you would implement them on a page or site.

Answer:

CSS sprites combine multiple images into one single larger image. It is commonly used technique for icons (Gmail uses it).

  • Use a sprite generator that packs multiple images into one and generate the appropriate CSS for it.
  • Each image would have a corresponding CSS class with background-image, background-position and background-size properties defined.
  • To use that image, add the corresponding class to your element.

Advantages:

  • Reduce the number of HTTP requests for multiple images (only one single request is required per spritesheet). But with HTTP2, loading multiple images is no longer much of an issue.
  • Advance downloading of assets that wonโ€™t be downloaded until needed, such as images that only appear upon :hover pseudo-states. Blinking wouldn't be seen.
Source: codeburst.io   


๐Ÿ”น 5. Explain the CSS โ€œbox modelโ€ and the layout components that it consists of

Answer:

The CSS box model is a rectangular layout paradigm for HTML elements that consists of the following:

  • Content - The content of the box, where text and images appear
  • Padding - A transparent area surrounding the content (i.e., the amount of space between the border and the content)
  • Border - A border surrounding the padding (if any) and content
  • Margin - A transparent area surrounding the border (i.e., the amount of space between the border and any neighboring elements)
Source: toptal.com   


๐Ÿ”น 6. What is a CSS rule?

Answer:

Web browsers apply CSS rules to a document to affect how they are displayed. A CSS rule is formed from:

  • A set of properties, which have values set to update how the HTML content is displayed,
  • A selector, which selects the element(s) you want to apply the updated property values to.

A set of CSS rules contained within a stylesheet determines how a webpage should look.

Source: developer.mozilla.org   


๐Ÿ”น 7. Explain what is a @extend directive used for in Sass?

Answer:

Using @extend lets you share a set of CSS properties from one selector to another. It helps keep your Sass very dry.

Consider:

%message-shared {
-  border: 1px solid #ccc;
-  padding: 10px;
-  color: #333;
-}
-
-.message {
-  @extend %message-shared;
-}
-
-.success {
-  @extend %message-shared;
-  border-color: green;
-}
-
-.error {
-  @extend %message-shared;
-  border-color: red;
-}
-
-.warning {
-  @extend %message-shared;
-  border-color: yellow;
-}

CSS output:

.message, .success, .error, .warning {
-  border: 1px solid #cccccc;
-  padding: 10px;
-  color: #333;
-}
-
-.success {
-  border-color: green;
-}
-
-.error {
-  border-color: red;
-}
-
-.warning {
-  border-color: yellow;
-}


๐Ÿ”น 8. Have you played around with the new CSS Flexbox or Grid specs?

Answer:

Yes. Flexbox is mainly meant for 1-dimensional layouts while Grid is meant for 2-dimensional layouts.

Flexbox solves many common problems in CSS, such as vertical centering of elements within a container, sticky footer, etc. Bootstrap and Bulma are based on Flexbox, and it is probably the recommended way to create layouts these days. Have tried Flexbox before but ran into some browser incompatibility issues (Safari) in using flex-grow, and I had to rewrite my code using inline-blocks and math to calculate the widths in percentages, it wasn't a nice experience.

Grid is by far the most intuitive approach for creating grid-based layouts (it better be!) but browser support is not wide at the moment.

Source: codeburst.io   


๐Ÿ”น 9. What is DOM (Document Object Model) and how is it linked to CSS?

Answer:

The Document Object Model (DOM) is a cross-platform and language-independent application programming interface that treats an HTML, XHTML, or XML document as a tree structure wherein each node is an object representing a part of the document.

With the Document Object Model, programmers can create and build documents, navigate their structure, and add, modify, or delete elements and content. The DOM specifies interfaces which may be used to manage XML or HTML documents.

When a browser displays a document, it must combine the document's content with its style information. The browser converts HTML and CSS into the DOM (Document Object Model). The DOM represents the document in the computer's memory. It combines the document's content with its style.

Source: en.wikipedia.org   


๐Ÿ”น 10. What is Sass?

Answer:

Sass or Syntactically Awesome StyleSheets is a CSS preprocessor that adds power and elegance to the basic language. It allows you to use variables, nested rules, mixins, inline imports, and more, all with a fully CSS-compatible syntax. Sass helps keep large stylesheets well-organized, and get small stylesheets up and running quickly.

A CSS preprocessor is a scripting language that extends CSS by allowing developers to write code in one language and then compile it into CSS.

Source: sass-lang.com   


๐Ÿ”น 11. What existing CSS frameworks have you used locally, or in production? How would you change/improve them?

Answer:

  • Bootstrap - Slow release cycle. Bootstrap 4 has been in alpha for almost 2 years. Add a spinner button component, as it is widely used.
  • Semantic UI - Source code structure makes theme customization extremely hard to understand. Its unconventional theming system is a pain to customize. Hardcoded config path within the vendor library. Not well-designed for overriding variables unlike in Bootstrap.
  • Bulma - A lot of non-semantic and superfluous classes and markup required. Not backward compatible. Upgrading versions breaks the app in subtle manners.
Source: codeburst.io   


๐Ÿ”น 12. Describe floats and how they work

Answer:

Float is a CSS positioning property. Floated elements remain a part of the flow of the web page. This is distinctly different than page elements that use absolute positioning. Absolutely positioned page elements are removed from the flow of the webpage.

#sidebar {
-  float: right; // left right none inherit			
-}

The CSS clear property can be used to be positioned below left/right/both floated elements.

Source: css-tricks.com   


๐Ÿ”น 13. What Selector Nesting in Sass is used for?

Answer:

Sass let you nest your CSS selectors in a way that follows the same visual hierarchy of your HTML. CSS, on the other hand, doesn't have any visual hierarchy.

Consider example (scss):

.parent {
-  color: red;
-
-  .child {
-    color: blue;
-  }
-}

Result (css):

.parent {
-  color: red;
-}
-
-.parent .child {
-  color: blue;
-}
Source: sass-lang.com   


๐Ÿ”น 14. List out the key features for Sass?

Answer:

Key features for Sass include

  • Full CSS3-compatible
  • Language extensions such as nesting, variables, and mixins
  • Many useful functions for manipulating colors and other values
  • Advanced features like control directives for libraries
  • Well-formatted, customizable output
Source: career.guru99.com   


๐Ÿ”น 15. What is the difference between classes and IDs in CSS?

Answer:

  • IDsโ€Šโ€”โ€ŠMeant to be unique within the document. Can be used to identify an element when linking using a fragment identifier. Elements can only have one id attribute.

  • Classesโ€Šโ€”โ€ŠCan be reused on multiple elements within the document. Mainly for styling and targeting elements.

Source: codeburst.io   


๐Ÿ”น 16. List out the data types that Sass supports

Answer:

Sass supports seven main data types:

  • Numbers - most of the time they are accompanied by a unit of some sort but they are still technically numbers. You can perform basic mathematical operations on these values.
$size: 18;                  // A number
-$px-unit: $size * 1px;      // A pixel measurement
-$px-string: $size + px;     // A string
-$px-number: $px-unit / 1px; // A number
  • Strings - just like CSS, accepts both quoted and unquoted strings, even if they contain spaces
$website: 'SitePoint'; // Stores SitePoint
-$name: 'Gajendar' + ' Singh';  // 'Gajendar Singh'
-$date:  'Month/Year : ' + 3/2016; // 'Month/Year : 3/2016'
-$date:  'Month/Year : ' + (3/2016); // 'Month/Year : 0.00149' 
-// This is because 3/2016 is evaluated first.
-$variable: 3/2016;      // Evaluated to 0.00149
  • Colors - CSS color expressions come under the color data type. You can refer to the colors in hexadecimal notation, as rgb, rgba, hsl and hsla values or use native keywords like pink, blue, etc.
$color: yellowgreen;           // #9ACD32
-color: lighten($color, 15%);    // #b8dc70
-color: darken($color, 15%);     // #6c9023
-color: saturate($color, 15%);   // #a1e01f
-color: desaturate($color, 15%); // #93ba45
-color: (green + red);           // #ff8000
  • Booleans - has only two possible values: true and false
$i-am-true: true;
-
-body {
-  @if not $i-am-true {
-    background: rgba(255, 0, 0, 0.6);
-  } @else {
-    background: rgba(0, 0, 255, 0.6); // expected
-  }
-}
  • Null - is commonly used to define an empty state, neither true or false. This is typically the value you want to set when defining a variable without a value, only to prevent the parser from crashing.
.foo {
-  content: type-of(null); // null
-  content: type-of(NULL); // string
-  $bar: 'foo' + null; // invalid null operation: "foo plus nullโ€.
-}
  • Lists - are just the Sass version of arrays. You can store multiple types of values in a list.
$font-list: 'Raleway','Dosis','Lato'; // Three comma separated elements
-$pad-list: 10px 8px 12px; // Three space separated elements
-$multi-list: 'Roboto',15px 1.3em; // This multi-list has two lists.
  • Maps - Sass maps are like associative arrays. A map stores both keys and values associated with those keys.
$styling: (
-  'font-family': 'Lato',
-  'font-size': 1.5em,
-  'color': tomato,
-  'background': black
-);
-
-h1 {
-  color: map-get($styling, 'color');
-  background: map-get($styling, 'background');
-}
Source: career.guru99.com   


๐Ÿ”น 17. What is variable interpolation in Sass? Provide some examples.

Answer:

If you want to use variables inside a string, you will have to use a process called variable interpolation. To use it you will have to wrap your variables in #{}.

Consider:

$name: 'Gajendar';
-$author: 'Author : $name'; // 'Author : $name'
-
-$author: 'Author : #{$name}';
-// 'Author : Gajendar'

The interpolation method could be useful in situations where the value of a variable is determined by some conditional statements.

Source: sitepoint.com   


๐Ÿ”น 18. What's the difference between SCSS and Sass?

Answer:

There are two syntaxes available for Sass. The first, known as SCSS (Sassy CSS) and used throughout this reference, is an extension of the syntax of CSS. This means that every valid CSS stylesheet is a valid SCSS file with the same meaning. This syntax is enhanced with the Sass features described below. Files using this syntax have the .scss extension.

The second and older syntax, known as the indented syntax (or sometimes just Sass), provides a more concise way of writing CSS. It uses indentation rather than brackets to indicate nesting of selectors, and newlines rather than semicolons to separate properties. Files using this syntax have the .sass extension.

Consider example.sass:

$color: red
-
-=my-border($color)
-  border: 1px solid $color
-
-body
-  background: $color
-  +my-border(green)

Consider example.scss:

$color: red;
-
-@mixin my-border($color) {
-  border: 1px solid $color;
-}
-
-body {
-  background: $color;
-  @include my-border(green);
-}
Source: stackoverflow.com   


๐Ÿ”น 19. Explain the usage of "table-layout" property

Answer:

The table-layout property defines the algorithm used to lay out table cells, rows, and columns.

table-layout: auto|fixed|initial|inherit;
  • auto - Browsers use an automatic table layout algorithm. The column width is set by the widest unbreakable content in the cells. The content will dictate the layout.
  • fixed - The layout is fixed based on the first row. Set the width of those, and the rest of the table follows. If no widths are present on the first row, the column widths are divided equally across the table, regardless of content inside the cells.
  • initial - Sets this property to its default value.
  • inherit - Inherits this property from its parent element.
Source: w3schools.com   


๐Ÿ”น 20. What's the difference between a relative, fixed, absolute and statically positioned element?

Answer:

A positioned element is an element whose computed position property is either relative, absolute, fixed or sticky.

  • static - The default position; the element will flow into the page as it normally would. The top, right, bottom, left and z-index properties do not apply.
  • relative - The element's position is adjusted relative to itself, without changing layout (and thus leaving a gap for the element where it would have been had it not been positioned).
  • absolute - The element is removed from the flow of the page and positioned at a specified position relative to its closest positioned ancestor if any, or otherwise relative to the initial containing block. Absolutely positioned boxes can have margins, and they do not collapse with any other margins. These elements do not affect the position of other elements.
  • fixed - The element is removed from the flow of the page and positioned at a specified position relative to the viewport and doesn't move when scrolled.
  • sticky - Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned.
Source: codeburst.io   


๐Ÿ”น 21. Have you ever worked with retina graphics? If so, when and what techniques did you use?

Answer:

Retina is just a marketing term to refer to high resolution screens with a pixel ratio bigger than 1. The key thing to know is that using a pixel ratio means these displays are emulating a lower resolution screen in order to show elements with the same size. Nowadays we consider all mobile devices retina defacto displays.

Browsers by default render DOM elements according to the device resolution, except for images.

In order to have crisp, good-looking graphics that make the best of retina displays we need to use high resolution images whenever possible. However using always the highest resolution images will have an impact on performance as more bytes will need to be sent over the wire.

To overcome this problem, we can use responsive images, as specified in HTML5. It requires making available different resolution files of the same image to the browser and let it decide which image is best, using the html attribute srcset and optionally sizes, for instance:

<div responsive-background-image>  
-  <img src="/images/test-1600.jpg"
-    sizes="
-      (min-width: 768px) 50vw,
-      (min-width: 1024px) 66vw,
-      100vw"
-    srcset="
-      /images/test-400.jpg 400w,
-      /images/test-800.jpg 800w,
-      /images/test-1200.jpg 1200w">
-</div>

It is important to note that browsers which don't support HTML5's srcset (i.e. IE11) will ignore it and use src instead. If we really need to support IE11 and we want to provide this feature for performance reasons, we can use a JavaScript polyfill, e.g. Picturefill (link in the references).

For icons, I would also opt to use SVGs and icon fonts where possible, as they render very crisply regardless of resolution.

Source: codeburst.io   


๐Ÿ”น 22. What are the advantages/disadvantages of using CSS preprocessors?

Answer:

Advantages:

  • CSS is made more maintainable.
  • Easy to write nested selectors.
  • Variables for consistent theming. Can share theme files across different projects.
  • Mixins to generate repeated CSS.
  • Splitting your code into multiple files. CSS files can be split up too but doing so will require a HTTP request to download each CSS file.

Disadvantages:

  • Requires tools for preprocessing. Re-compilation time can be slow.
Source: codeburst.io   


๐Ÿ”น 23. How is responsive design different from adaptive design?

Answer:

Both responsive and adaptive design attempt to optimize the user experience across different devices, adjusting for different viewport sizes, resolutions, usage contexts, control mechanisms, and so on.

Responsive design works on the principle of flexibilityโ€Šโ€”โ€Ša single fluid website that can look good on any device. Responsive websites use media queries, flexible grids, and responsive images to create a user experience that flexes and changes based on a multitude of factors. Like a single ball growing or shrinking to fit through several different hoops.

Adaptive design is more like the modern definition of progressive enhancement. Instead of one flexible design, adaptive design detects the device and other features, and then provides the appropriate feature and layout based on a predefined set of viewport sizes and other characteristics. The site detects the type of device used, and delivers the pre-set layout for that device. Instead of a single ball going through several different-sized hoops, youโ€™d have several different balls to use depending on the hoop size.

Source: codeburst.io   


๐Ÿ”น 24. What is CSS selectors? Name some.

Answer:

A CSS selector is the part of a CSS rule set that actually selects the content you want to style.

Consider some types of CSS selectors:

  • Universal selector: *
  • Element type selector: ul, td
  • ID Selector: #id
  • Class selector: .box
  • Descendant combinator: #id .box. The .box element doesnโ€™t have to be an immediate child of #id.
  • Child combinator: #id > .box. Unlike the descendant combinator, there canโ€™t be another element wrapping .box
  • General Sibling Combinator: ~
  • Adjacent Sibling Combinator: +. The difference from general sibling combinaltor is that the targeted element must be an immediate sibling, not just a general sibling.
  • Attribute Selector: input[type="text"]
  • Pseudo-class: a:hover. A pseudo-class uses a colon character to identify a pseudo-state that an element might be in.
  • Pseudo-element: .container::before. This selector inserts an imaginary element into the page, inside the targeted element, before its contents.
Source: sitepoint.com   


๐Ÿ”น 25. What does Accessibility (a11y) mean?

Answer:

Accessibility (a11y) is a measure of a computer system's accessibility is to all people, including those with disabilities or impairments. It concerns both software and hardware and how they are configured in order to enable a disabled or impaired person to use that computer system successfully.

Accessibility is also known as assistive technology.

Source: techopedia.com   


๐Ÿ”น 26. What is CSS preprocessor and why to user one?

Answer:

A CSS preprocessor is a program that lets you generate CSS from the preprocessor's own unique syntax. There are many CSS preprocessors to choose from, however most CSS preprocessors will add some features that don't exist in pure CSS, such as mixin, nesting selector, inheritance selector, and so on. These features make the CSS structure more readable and easier to maintain.

Here are a few of the most popular CSS preprocessors:

  • SASS (SCSS)
  • LESS
  • Stylus
  • PostCSS
Source: developer.mozilla.org   


๐Ÿ”น 27. How would you approach fixing browser-specific styling issues?

Answer:

  • After identifying the issue and the offending browser, use a separate style sheet that only loads when that specific browser is being used. This technique requires server-side rendering though.
  • Use libraries like Bootstrap that already handles these styling issues for you.
  • Use autoprefixer to automatically add vendor prefixes to your code.
  • Use Reset CSS or Normalize.css.
Source: codeburst.io   


๐Ÿ”น 28. Whatโ€™s the difference between โ€œresettingโ€ and โ€œnormalizingโ€ CSS? Which would you choose, and why?

Answer:

  • Resettingโ€Šโ€”โ€Šis meant to strip all default browser styling on elements. For e.g. margins, paddings, font-sizes of all elements are reset to be the same. You will have to redeclare styling for common typographic elements.
  • Normalizingโ€Šโ€”โ€Špreserves useful default styles rather than โ€œunstylingโ€ everything. It also corrects bugs for common browser dependencies.

It's a good idea to choose resetting when you have very a customized or unconventional site design such that I need to do a lot of my own styling do not need any default styling to be preserved.

Source: codeburst.io   


๐Ÿ”น 29. Explain your understanding of the box model and how you would tell the browser in CSS to render your layout in different box models.

Answer:

The CSS box model is responsible for calculating:

  • How much space a block-level element takes up.
  • Whether or not borders and/or margins overlap, or collapse.
  • A boxโ€™s dimensions
div {
-    width: 300px;
-    border: 25px solid green;
-    padding: 25px;
-    margin: 25px;
-}

The box model has the following rules:

  • The dimensions of a block element are calculated by width, height, padding, borders, and margins.
  • If no height is specified, a block element will be as high as the content it contains, plus padding (unless there are floats, for which see below).
  • If no width is specified, a non-floated block element will expand to fit the width of its parent minus padding.
  • The height of an element is calculated by the content's height.
  • The width of an element is calculated by the content's width.
  • By default, paddings and borders are not part of the width and height of an element.
Source: codeburst.io   


๐Ÿ”น 30. Describe pseudo-elements and discuss what they are used for.

Answer:

A CSS pseudo-element is a keyword added to a selector that lets you style a specific part of the selected element(s). They can be used for decoration (:first-line, :first-letter) or adding elements to the markup (combined with content: ...) without having to modify the markup (:before, :after).

Example of usage:

  • :first-line and :first-letter can be used to decorate text.
  • Used in the .clearfix hack to add a zero-space element with clear: both.
  • Triangular arrows in tooltips use :before and :after. Encourages separation of concerns because the triangle is considered part of styling and not really the DOM, but not really possible to draw a triangle with just CSS styles.
Source: codeburst.io   


๐Ÿ”น 31. How does CSS actually work (under the hood of browser)?

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 32. What is a Grid System in CSS?

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 33. What is a Mixin and how to use on?

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 34. How to create a zebra striped table with CSS?

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 35. Explain the purpose of clearing floats in CSS

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 36. What does * { box-sizing: border-box; } do? What are its advantages?

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 37. Can you explain the difference between coding a website to be responsive versus using a mobile-first strategy?

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 38. Explain the basic rules of CSS Specificity

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 39. How do you optimize your webpages for print?

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 40. Have you ever used a grid system, and if so, what do you prefer?

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 41. What are the different ways to visually hide content (and make it available only for screen readers)?

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 42. Describe z-index and how a stacking context is formed

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 43. Is there any reason you'd want to use translate() instead of absolute positioning, or vice-versa? And why?

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 44. What the code fragment has the greater CSS specificity?

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 45. What will be the CSS output for the following Sass code?

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 46. What is the @content directive used for?

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 47. Write down a selector that will match any links end in .zip, .ZIP, .Zip etc...

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 48. How to style every element which has an adjacent item right before it?

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 49. Whatโ€™s wrong with Sass nesting? Provide some example.

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers


๐Ÿ”น 50. What clearfix methods do you know? Provide some examples.

- ๐Ÿ‘‰๐Ÿผ Check - all 50 answers



- Thanks ๐Ÿ™Œ for reading and good luck on your next tech interview! -
- Explore 3800+ dev interview question here ๐Ÿ‘‰ - Devinterview.io
+# 100 Fundamental CSS Interview Questions in 2025 + +
+

+ +web-and-mobile-development + +

+ +#### You can also find all 100 answers here ๐Ÿ‘‰ [Devinterview.io - CSS](https://devinterview.io/questions/web-and-mobile-development/css-interview-questions) + +
+ +## 1. What does _CSS_ stand for and what is its primary use? + +**Cascading Style Sheets** (**CSS**) is primarily designed to separate web page content from its visual presentation. This allows for a consistent and adaptable design across multiple web pages. + +### Key Concepts + +- **Selectors**: Elements to which the style rules apply. +- **Properties**: Visual features, such as font-size, color, and background. +- **Values**: Specific settings for properties, like 'red' for the color property. + +### Visual Example + +Here is the HTML code: + +```html + + + + + + CSS Example + + + +
+

Welcome to Our Site

+ +
+
+

Latest News

+
+

Breaking News: Big Event Tomorrow

+

Join us for our biggest event of the year!

+
+
+ + + +``` + +And, here is the accompanying CSS in `styles.css`: + +```css +/* Targeting all text on the page */ +body { + font-family: Arial, sans-serif; + color: #333; + background-color: #f4f4f4; +} + +/* Targeting the header elements */ +header { + background-color: #1e90ff; + padding: 1em 0; + text-align: center; +} + +/* Targeting the nav elements */ +nav ul { + list-style-type: none; + padding: 0; +} + +/* Targeting the nav links */ +nav a { + text-decoration: none; + color: #fff; + margin: 0 10px; +} + +/* Targeting the main section */ +section { + padding: 20px; +} + +/* Targeting the footer element */ +footer { + text-align: center; + margin-top: 50px; + padding: 10px; + background-color: #1e90ff; + color: #fff; +} +``` +
+ +## 2. How do you include _CSS_ in your _HTML document_? + +There are **four primary methods** to incorporate CSS in an HTML document, each presenting unique advantages and use cases. + +### Methods of CSS Integration + +1. **Inline Style**: Directly insert CSS rules within HTML tags. +2. **Embedded Style**: Encompass CSS within the HTML document's `` section. +3. **External Style Sheet**: Create a standalone `.css` file to be referenced in the HTML. +4. **Imported Style Sheet**: Employ `@import` within a ` + +

My Header

+

Hello, World!

+ + +``` +
+ +## 3. Can you explain the difference between _class_ and _ID selectors_? + +**Class** and **ID** selectors in CSS serve distinct roles and have limitations in their applicability. + +### Selectivity and Applicability + +- **Class Selector** (\`.classname{...}\`): Matches **multiple elements** that share the same class attribute. These elements can belong to various HTML tags (e.g., `
`, `

`). + +- **ID Selector** (`#idName{...}`): Identifies a **single unique element** based on its unique ID attribute. While it's still possible to style multiple elements with the same ID, best practices mandate unique IDs for effective CSS usage. + +### Efficiency and Performance + +- **Class Selector**: Generally faster to compute than ID selectors in modern browsers, particularly when applied to a large number of elements. + +- **ID Selector**: Formerly superior in terms of speed, contemporary browsers mitigate this difference. + +### Common Use Cases + +- **Class Selector**: Ideal for styling groups of elements based on shared attributes or type. + +- **ID Selector**: Typically reserved for unique elements that require highly specific styling or JavaScript manipulation. While it's valid to use an ID for styling, as stated in the HTML5 specification, it's generally more maintainable to reserve the use of IDs for uniquely identifiable elements and use classes for styling. + +### Code Example: Class and ID Selectors + +Here is the HTML code: + +```html + + + + + +

Content 1
+
Content 2
+
Special Content
+ + +``` + +Here is the CSS code: + +```css +/* Styles applied using class selectors */ +.content { color: blue; } + +/* Styles applied using ID selector */ +#uniqueContent { color: red; } +``` +
+ +## 4. What are _pseudo-classes_ in _CSS_? + +**Pseudo-classes** are special keywords in CSS that allow you to apply styles to elements based not only on their state or position in the document tree but also on user interaction. + +### Categories of Pseudo-Classes + +- **Dynamic Pseudo-classes**: These appear as the user interacts with an element. For instance, `:hover` is activated when the user hovers the cursor over an element. + +- **User-action Pseudo-classes**: These capture actions taken by the user, such as `:checked` for input elements that are selected. + +- **Relationship Pseudo-classes**: These pertain to the document tree's hierarchical structure, like `:first-child` for an element that's the first child within its parent. + + +- **Language Pseudo-Classes**: These cater to elements displayed in specific languages, for example `:dir()`. + +- **Input Control Pseudo-Classes**: Designed specifically for interactive elements, these pseudo-classes style form controls like buttons, inputs, and text areas. Some examples are `:default`, `:valid`, `:invalid`, and `:optional`. + +- **Enabled and Disabled Pseudo-classes**: These are self-explanatory; they alter the style of elements based on whether they're enabled or disabled. Examples include `:enabled` and `:disabled`. +
+ +## 5. Describe how to implement a _CSS reset_ and why it is useful. + +A **CSS reset** is a set of styles intended to reduce browser inconsistencies in elements such as margins, paddings, and various typical style defaults. + +### Benefits of CSS Reset + +- **Consistent Starting Point**: Eliminates default styling differences across browsers, making the design process more predictable. +- **Consistent Box Model**: Ensures uniform calculations of element sizing (e.g., widths and heights) to prevent unexpected layout shifts. +- **Want Only Custom Styles**: It's especially useful if you intend to start from a blank slate and apply your own bespoke styles. + +### The Code + +For HTML: + +```html + + + + + + + Document + + +

Hello, CSS Reset!

+ + +``` + +And for CSS, here is a simple **normalize.css**-based reset: + +```css +/* reset.css */ +/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */ +h1 { + font-size: 2em; + margin: 0.67em 0; +} +``` +
+ +## 6. How do you select elements by _attribute_ in _CSS_? + +While programming in CSS, you can leverage **attribute selectors** to define rules based on the presence or value of specific HTML attributes. + +### Benefits + +Using attribute selectors has multiple advantages, such as: + +- **Versatility**: They cater to a wide range of scenarios. +- **Simplicity**: They are easy to use. +- **Consistency**: They're a part of a standard set of CSS selectors. + +### Variations + +You can utilize attribute selectors in three distinct ways: + +- **Exact Match**: `[]` selects an exact attribute value. +- **Value Starts With**: `[^]` targets attributes with specified starting values. +- **Case Insensitive**: Selectors are usually case-sensitive, but by using `i`, you can make them case-insensitive. + +Here is the CSS code snippet: + +```css +/* Exact Match */ +[class="important"] { + color: red; +} + +/* Value Starts With */ +[href^="https"] { + color: green; +} + +/* Case Insensitive */ +[alt="home" i] { + background: url('home-icon.png'); +} +``` + +In the example above, + +- `[class="important"]` selects all elements with the exact `class` attribute set to "important". +- `[href^="https"]` will style all anchor links with an `href` attribute that starts with "https". +- `[alt="home" i]` targets the `alt` attribute with a value of "home" in a case-insensitive manner. +
+ +## 7. What is a _pseudo-element_, and what are they used for? + +**Pseudo-elements** are virtual elements that give developers the power to style parts of an HTML document that don't correspond to actual HTML elements. Essentially, they let you apply styles to specific parts of an element without the need for extra HTML markup. + +Commonly used `pseudo-elements` include `::before` and `::after` which let developers insert content before or after an element, respectively. + +### Key Features + +- **Automatic Insertion**: These pseudo-elements can add content continuously without requiring manual code changes. +- **Dynamic Content**: With generated content and styles, pseudo-elements can adapt based on the specific conditions. +- **Custom Styling**: Pseudo-elements enable developers to style parts of an element differently than the rest. + +### Practical Applications + +1. #### Indicating External Links + + - **Link**: Indicating content that opens an external website. + - **Implementation**: Visual or textual cues like arrows or "External Link" next to anchor elements. + +2. #### Specialized Numbers and Letters + + - **Link**: Styling a single letter or number within a text block. + - **Implementation**: Especially useful in design, for instance, highlighting the first letter of a paragraph with a larger font size. + +3. #### Responsive Backgrounds + + - **Link**: Apply background images or colors specific to certain parts of an element for various screen sizes. + - **Implementation**: Use media queries within the pseudo-element for specific screen sizes. + +4. #### Code Blocks and Blockquotes + + - **Link**: Add decorative elements preceding and following code blocks and blockquote elements. + - **Implementation**: Help highlight code samples or visually delineate long blockquote sections. + +5. #### Custom Radio Buttons and Checkboxes + + - **Link**: Rework default styling for radio buttons and checkboxes for a more customized look. + - **Implementation**: Use ::before or ::after with content property to replace default appearance. + +6. #### Clear Floats + + - **Link**: Overcome challenges in parent containers not respecting the height of floated child elements and collapsing. + - **Implementation**: Create an element with ::after pseudo-element where the content clears the floats. + +7. #### Hacks for Older Browsers + + - **Link**: Sometimes, especially with prior versions of Internet Explorer, using pseudo-elements proves crucial for achieving desired stylings. + - **Implementation**: Useful for applying specifically crafted styles that wouldn't work properly on older browsers without this technique. +
+ +## 8. Explain the difference between the _child combinator_ and the _descendant combinator_. + +The **child combinator** (>) and the **descendant combinator** (~) both serve to target HTML elements with CSS. However, they **operate in different ways**. + +### Distinct Characteristics + +- Child Combinator **>**: Selects an HTML element that is a **direct child** of another element. +- Descendant Combinator **~**: Matches an HTML element that is a **descendant** (direct or indirect child) of another specified element. + +### Code Example + +Here is the CSS: + +```css +/* target direct children of the parent element */ +nav > ul > li { + color: red; +} + +/* target any descendant list items under nav */ +nav li { + color: blue; +} +``` + +Here is the HTML: + +```html + +``` + +### Best Practices for Combinator Use + +1. **Specificity of Selection**: Implement the **child combinator** $>$ when you want to target a specific, direct child of an element. +2. **Minimize Global Targeting**: Utilize the **descendant combinator** cautiously as it has the potential for global targeting. It's often a good habit to opt for more specific selectors. +3. **Balance Styling and Performance**: As a rule of thumb, more specific selectors could improve rendering speed. Use combinators with a balanced approach keeping in mind both specificity and performance needs. +
+ +## 9. How would you select all direct _children elements_ of a particular type? + +To **select all direct children** of a specific type in CSS, you can use the `>` **child selector** combined with the desired element to build the selector. + +For example, to select all the direct children that are `
  • ` elements within an `
      ` element, you would use the following CSS: + +```css +ul > li { + /* Styles here */ +} +``` +
      + +## 10. What are the _universal selector_ and the _sibling combinator_, and when would you use them? + +The **Universal Selector** (the asterisk, `*`) is a powerful tool that enables you to target every element within a specified container. While it's a straightforward selector, its implications can be broad. + +- **When to Use**: You might want to normalize or reset specific CSS properties (resetting padding, margin, etc.) across all elements within a container or the entire document. The **Universal Selector** effectively achieves this. + +- **Best Practices**: Overuse of the **Universal Selector** can lead to performance issues and unexpected style side effects. Keep its use concise and well-defined. + +### When To Use Sibling Combinator + +The **Sibling Combinator** (`+`) in CSS targets elements that are immediately preceded by a specified element. Unlike child (`>`) or descendant (whitespace) selectors, the **sibling combinator** allows direct sibling targeting. + +- **When to Use**: For DOM structures where direct sibling relationships are key, such as tabbed content or multi-step forms. + +- **Best Practices**: While direct sibling targeting is useful, ensure it's the most efficient method for your objective. Overreliance can lead to inflexible CSS and HTML structures. + +#### Code Example: Universal Selector + +Here is the CSS: + +```css +/* Remove margins, paddings on all elements within the container */ +.containers > * { + margin: 0; + padding: 0; +} +``` + +The HTML: + +```html +
      +

      Paragraph 1

      +
        +
      • Item 1
      • +
      • Item 2
      • +
      +
      +``` + +#### Code Example: Sibling Combinator + +Here is the CSS: + +```css +/* Style the direct sibling anchor tag when a list item is hovered */ +ul li:hover + a { + color: red; +} +``` + +The HTML: + +```html +
        +
      • Item 1
      • +
      • Item 2
      • +
      • Link
      • +
      +``` + +### Case Study: Practical Applications + +Let us take a real-world example. + +#### Resetting Margins and Paddings + +In this scenario, you have a parent container and you want to remove the default margins and paddings from all its child elements. + +The **Universal Selector** can accomplish this: + +Here is the CSS: + +```css +.container > * { + margin: 0; + padding: 0; +} +``` + +The HTML: + +```html +
      +

      Paragraph 1

      +

      Paragraph 2

      +
      +``` +
      + +## 11. What is the _CSS Box Model_? + +The **Box Model** is the foundational concept in CSS that describes the structure of an HTML element. It encompasses four key components: **content**, **padding**, **border**, and **margin**. + +### Box Model Components + +- **Content**: The actual element content, such as text, images, or other visual or interactive elements. +- **Padding**: Clears an area around the element's content, inside the border. The padding is transparent and doesn't have a background color or border. +- **Border**: A solid line that defines the boundary of the padding area. +- **Margin**: Clears an area around the element's border, outside any defined background or border. + +### Visual Representation +![CSS Box Model](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/questions-images%2Fcss-box-model.jpg?alt=media&token=f36af6aa-69e3-4cc5-bdce-8a0558d22861) + +### Key Attributes + +- **Height** & **Width**: Element dimensions are determined by the sum of content width/height, and any padding, border, or margin added to it. +- **Border**: Specifies the size, style, and color of the border surrounding the content and padding. +- **Margin**: Defines the **clearance** between adjacent elements. + +### Code Example: Box Model + +Here is the HTML code: +```html +
      This is an example of text within the Box Model.
      +``` + +Here is the CSS code: +``` CSS +#boxModelExample { + border: 5px solid red; + padding: 20px; + margin: 20px; +} +``` + +### Margins + +#### Auto Margins +When the surrounding container has a defined width, horizontal margins set to "auto" equally distribute the remaining horizontal space on both sides of the element, centering it within the container. + +``` CSS +#autoMarginExample { + width: 50%; + margin-left: auto; + margin-right: auto; +} +``` + +### Parent and Child Element Interplay + +#### Box Sizing + +By default, the width of an element does not include padding or border. CSS can alter this behavior using the `box-sizing` property: + +- **Content-Box** (default): The element's specified width and height are calculated excluding padding and border. When you change the width or height of an element using CSS, this is the model being used. +- **Border-Box**: The width and height comprise the content, padding, and border, avoiding the expansion of the box when adding padding or border to an element. + +This distinction aids in layout control and ensures uniformity. + +``` CSS +#borderBoxExample { + box-sizing: border-box; +} +``` +
      + +## 12. Explain _margin collapsing_. + +**Margin collapsing** can occur when there are adjacent vertical margins between elements. In such cases, the larger of the two margins becomes the "collapsed margin." + +### Types of Margin Collapsing +1. **Adjacent Sibling Collapsing**: When two blocks or inline-block elements are hierarchically adjacent, such as being direct children of a common container, their top and bottom margins might collapse. For instance, in the code: + + ```html +
      +

      This is paragraph 1

      +

      This is paragraph 2

      +
      + ``` + +2. **Parent-Child Collapsing**: If there are no intervening content or padding or border between the parent and the first/last child inside it, the parent's margins might collapse with the child's corresponding margin. + +### Visual Representation of Margin Collapsing +- Vertical margin collapse: +![Vertical Margin Collapse](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/questions-images%2Fvartical-margin-collapse.jpg?alt=media&token=7a9f7961-302b-48c7-b74e-168f6780897f) +- Horizontal margin collapse does not occur: ![Horizontal Margin Collapse](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/questions-images%2Fhorizontal-margin-collapse.jpg?alt=media&token=da23e77b-72aa-4c17-a287-3f274753be9a) + +### Preventing Margin Collapsing +1. **Padding or Borders**: Introduce padding or borders to disrupt the margin collapsing behavior when required. +2. **Inline-Block or Floats**: Transform adjacent elements into `inline-block` or use `float` property. +3. **Clearfix**: Employ a clearing technique for floated elements, which separates subsequent elements in the flow, ultimately preventing margin collapse. + +### CSS Rules and Margin Collapsing +1. **Marginal vs. Calculated Total**: + - If margins are set, every other margin is respected. + - If margins are calculated to be a non-zero value, margins can be collapsed. + - Margins from both the top and the bottom end of the elements are considered. +2. **Non-Root Elements**: The root `` element's margins don't collapse. +3. **Non-Adjacent Items**: A margin doesn't collapse through wrapping or inline elements. + +While margin collapsing can simplify layout management under specific conditions, it's essential to understand its behavior to ensure predictable and consistent designs. +
      + +## 13. What are the different values for the _box-sizing_ property and what do they do? + +The `box-sizing` property has three possible values: + +1. **Content-Box**: Box dimensions are calculated by adding the `width` and `height` to the content only. This is the default behavior. Mathematically, this is represented as: $$ \text{Content Width/Height} = \text{Specified Width/Height} $$ + +2. **Border-Box**: The `width` and `height` of the box are calculated by including both the content and padding within the specified values. Essentially, the browser will adjust the **content width and height measurements to include the padding and border** thickness. Mathematically, this is represented as: $$ \text{Content Width/Height} = \text{Specified Width/Height} - \text{Padding} - \text{Border} $$ + +3. **Initial**: This value sets the `box-sizing` property to its default value, which is typically `content-box`. + +### Visual Representation + +![Box-Sizing Properties in CSS](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/questions-images%2Fcss-box-sizing.jpg?alt=media&token=6bba3876-148a-4b03-a5cc-c96bb8fddb5a) +
      + +## 14. How do you center a _block element_ with _CSS_? + +To center a **block-level** element using CSS, there are several methods, which handle either horizontal or vertical alignment. + +### Horizontal Centering + +There are three common options to horizontally center a block: + +1. **Auto margins**: by setting both left and right margins to `auto`. +2. **Flexbox**: placing the block in a flex container and setting `justify-content: center`. +3. **Grid**: applying the `place-items` property on the container set to grid layout. + +#### Code Example: Auto Margins +```css +.container { + width: 50%; + margin: 0 auto; /* Center horizontally */ +} +``` + +#### Code Example: Flexbox +```css +.container { + display: flex; + justify-content: center; /* Horizontally center child elements */ +} +``` + +### Vertical Centering + +To vertically center a block, modern techniques such as Flexbox and Grid layout can be used. + +#### Code Example: Flexbox +```css +.container { + display: flex; + align-items: center; /* Vertically center child elements */ +} +``` + +#### Code Example: CSS Grid +```css +.container { + display: grid; + align-items: center; /* Vertically center child elements */ +} +``` +
      + +## 15. What is the difference between _block_, _inline_, and _inline-block elements_? + +**Block elements**, by default, stack vertically, while **inline elements** sit next to each other on the same line. + +**Inline-block elements** combine characteristics of both, stacking vertically and allowing for adjustments in height, margin, and padding. + +### Code Example: Key Differences + +Here is the HTML: + +```html +
      Block
      +Inline +Inline-Block +``` + +Here is the CSS: + +```css +div, span { + display: block; + margin-bottom: 10px; +} + +.inline-block { + display: inline-block; + background: lightblue; + padding: 10px; +} +``` + +In `div` and `span` due to default display type (block): text is separated by +a gap. + +In `span.inline-block`: with `display: inline-block`, text shares a line but is visually separated by its background. +
      + + + +#### Explore all 100 answers here ๐Ÿ‘‰ [Devinterview.io - CSS](https://devinterview.io/questions/web-and-mobile-development/css-interview-questions) + +
      + + +web-and-mobile-development + +

      +