CSS, or Cascading Style Sheets, is a language used to control the presentation of web pages. It is an essential part of web development, and mastering it is crucial for any front-end developer. In this blog post, we’ll be discussing some of the most common CSS interview questions and how to answer them. We’ll cover topics such as CSS selectors, layout and positioning, and more. Whether you’re a seasoned veteran or just starting out, these questions will help you prepare for your next job interview and showcase your CSS skills. So, let’s dive in and see what CSS questions employers are asking!
Basic CSS Interview Questions
Q. What is the difference between a class and an ID?
Ans. In HTML and CSS, a class is a way to group elements together that share the same characteristics, so that you can apply styles to all of them at once. An ID, on the other hand, is a way to uniquely identify a single element on a webpage, so that you can apply styles to that specific element. Classes are denoted by a “.” (dot) and IDs are denoted by a “#” (hash) in CSS.
Q. What was the purpose of developing CSS?
Ans. The purpose of developing CSS (Cascading Style Sheets) was to separate the presentation of a document (i.e. how it looks) from its structure and content (i.e. the HTML or XML markup). This allows developers to make changes to the presentation of a website or application without having to make changes to the underlying HTML or XML markup, making it easier to maintain and update the website or application over time. Additionally, CSS allows developers to create a consistent look and feel across multiple web pages or even an entire website, which improves the user experience.
Q. What is meant by RGB stream?
Ans. RGB (Red, Green, Blue) stream refers to the process of displaying colors on a screen by combining red, green and blue light in different intensities.
Each color is represented by a numerical value between 0 and 255 (for an 8-bit color depth), where 0 represents the minimum intensity and 255 represents the maximum intensity. For example, an RGB value of (255,0,0) would represent the color red, (0,255,0) would represent the color green, and (0,0,255) would represent the color blue. By varying the intensity of each of these primary colors, it is possible to create a wide range of different colors.
Q. How can CSS be integrated into an HTML page?
Ans. CSS can be integrated into an HTML page in several ways:
Inline styles: Styles can be applied directly to an HTML element using the “style” attribute. This method is useful for applying styles to a single element, but it can quickly become unwieldy if you need to apply the same style to multiple elements.
<p style="color:blue;">This is a blue paragraph.</p>
Internal stylesheet: A stylesheet can be included within the head of an HTML document using the <style>
tag. This method is useful for applying styles to multiple elements within a single HTML document.
<head>
<style>
p {
color: blue;
}
</style>
</head>
<body>
<p>This is a blue paragraph.</p>
</body>
External stylesheet: A separate CSS file can be linked to an HTML document using the <link>
tag within the head of the HTML document. This method is useful for applying styles to multiple HTML documents or an entire website.
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<p>This is a blue paragraph.</p>
</body>
It’s worth noting that all the above methods can be used together.
CSS can also be integrated into an HTML page using CSS preprocessors like SASS, LESS etc.
Q. Differentiate between CSS3 and CSS2
Ans. CSS3 is the latest version of Cascading Style Sheets, while CSS2 is the previous version. Here are some key differences between the two versions:
- New selectors: CSS3 introduces new selectors such as attribute selectors, structural selectors, and pseudo-classes, which allow for more precise targeting of elements on a webpage.
- New layout modules: CSS3 introduces new layout modules, such as Flexbox and Grid, which make it easier to create flexible and responsive layouts.
- New visual effects: CSS3 introduces new visual effects such as shadows, gradients, and animations, which can be used to create more interactive and dynamic web pages.
- New units: CSS3 introduces new units such as rem and vh/vw which are related to font-size and viewport respectively.
- Media Queries: CSS3 introduced Media Queries which allow to apply different CSS styles depending on the screen size, device, and other factors.
- Improved support for web fonts: CSS3 improves support for web fonts, allowing designers to use a wider range of fonts on their websites.
- Improved performance: CSS3 is designed to be more efficient and performant than CSS2, with features such as hardware acceleration and reduced file size.
Overall, CSS3 offers a wider range of options for styling webpages, and allows for more dynamic and responsive designs. CSS2 had less selectors, layout options and visual effects compared to CSS3.
Q. Explain a few advantages of CSS?
Ans: There are several advantages of using Cascading Style Sheets (CSS) in web development:
- Separation of presentation and content: By using CSS to control the presentation of a webpage, developers can separate the design and layout of a webpage from the content (HTML/XML). This makes it easier to maintain and update the website, as changes to the design can be made without affecting the underlying HTML/XML markup.
- Improved accessibility: CSS allows developers to create webpages that are more accessible to users with disabilities by providing ways to separate the visual design from the content and structure of a webpage.
- Reusability: CSS styles can be reused across multiple webpages, which can save time and effort when building and maintaining a website.
- Better cross-browser compatibility: By using CSS, developers can control the way a webpage is displayed in different browsers, which helps ensure that the webpage looks consistent across different browsers.
- Increased performance: Using CSS can lead to faster loading times and improved performance as it reduces the amount of code in the HTML, and allows the browser to cache the CSS styles.
- Responsive design: CSS allows for creating responsive design which adapts to different screen size and device, providing a good user experience.
- Improved search engine optimization (SEO): By using CSS to control the presentation of a webpage, developers can create webpages that are more search engine friendly, which can help improve the webpage’s visibility in search engine results.
Q. What do you understand by the universal selector?
Ans: In CSS, the universal selector, represented by the asterisk (*) is a selector that matches any element on the page.
The universal selector can be used to target all elements on the page and apply a style to them. For example:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
This CSS will set the margin, padding and box-sizing property of all elements on the page to 0 and “border-box” respectively.
It’s important to note that the universal selector is considered as a powerful selector, It can be used to override any other CSS styles, so it should be used with caution. It’s generally recommended to use more specific selectors whenever possible, rather than relying on the universal selector.
It can be useful to reset the default browser styles for all elements on the page by using the universal selector.
Q. Tell me about the use of the ruleset?
Ans: A ruleset in CSS is a set of instructions that tells the browser how to style a specific group of elements on a webpage. It consists of two parts: a selector and a declaration block.
The selector is used to identify the group of elements that the ruleset should be applied to. For example, a selector of “p” would select all the
elements on the page.
The declaration block is a set of instructions that specify the styles that should be applied to the selected elements. The declaration block is enclosed in curly braces {} and contains one or more property-value pairs, separated by semicolons.
For example, the following ruleset would make all the text inside <p> elements red and italic:
p {
color: red;
font-style: italic;
}
Multiple rulesets can be used on the same page to style different elements in different ways, allowing for a great deal of flexibility in controlling the layout and appearance of a webpage.
Rulesets can also be used to override the styles of other rulesets, in cases where the selectors have conflicting styles. The rule that is written later in the stylesheet will override the rule that was written earlier.
It’s also worth noting that rulesets can be nested inside other rulesets, which allows for creating more complex and specific selectors, this is known as the CSS cascading mechanism.
Q. What are the elements of the CSS Box Model?
Ans: The CSS Box Model is a layout model used in CSS to calculate the size and position of elements on a webpage. It defines the rectangular boxes that are generated for elements in the document, and consists of the following elements:
- Content: The content of the box, where the text or image of an element is placed.
- Padding: The transparent area surrounding the content, used to create space between the content and the border.
- Border: A visible line that surrounds the padding and content, it can be set to different thickness, style, and color.
- Margin: The transparent area surrounding the border, used to create space between the element and other elements on the page.
The width and height of an element in the box model are calculated by adding the content width/height, left and right padding, left and right border, and left and right margin.
By default, the width and height of an element in the box model are determined by the content within the element, but they can also be set explicitly using the width and height properties in CSS. The padding, border, and margin properties can also be used to adjust the size of the box and the space around it.
It’s important to note that the box-sizing property in CSS allows to change the default box model to include the padding and border within the width and height, this property is called the “content-box” and the other one is “border-box”.
Intermediate CSS Interview Questions
Q. Define z-index?
Ans: The z-index is a CSS property that specifies the stack order of an element. An element with a higher z-index is always in front of an element with a lower z-index. Elements with the same z-index are stacked in the order in which they appear in the HTML. The default z-index value is 0. Elements with a positive z-index are positioned above elements with a default z-index of 0, and elements with a negative z-index are positioned below elements with a default z-index of 0.
Q. What are the benefits of CSS Sprites?
Ans: CSS sprites are a technique for combining multiple images into a single image file, and then using CSS to display specific portions of that image file on a web page. The benefits of using CSS sprites include:
- Reduced HTTP requests: By using a single image file, the number of HTTP requests made by the browser is reduced, which can improve page load times.
- Improved performance: Combining multiple images into a single file reduces the overhead of loading and displaying multiple images, which can improve the overall performance of a website.
- Simplified maintenance: With CSS sprites, you only have to update one image file instead of multiple image files, which can make it easier to maintain a website.
- Consistent look and feel: CSS sprites can be used to ensure a consistent look and feel for a website by using a single image file for all of the website’s icons, buttons, and other small graphics.
- Sprites also allows to reduce the number of image files required for a website, which means less data to be downloaded by users.
Q. How can you target h3 and h2 with the same styling?
Ans: You can target h2 and h3 elements with the same styling by using a CSS selector that targets both elements. There are a few different ways you can do this:
- Use a CSS class: You can create a class, for example
.same-styling
and apply it to both h2 and h3 elements in your HTML like<h2 class="same-styling">
and<h3 class="same-styling">
. Then in your CSS you can target that class.same-styling { /* CSS styles */ }
- Use a CSS descendant selector: You can use a descendant selector to target h2 and h3 elements that are descendants of a specific element. For example:
div h2, div h3 { /* CSS styles */ }
- Use a CSS combination selector: You can use a combination selector to target h2 and h3 elements that have a specific class. For example:
h2.someclass, h3.someclass { /* CSS styles */ }
- Use CSS universal selector: You can use a universal selector to target any element, including h2 and h3 elements like
* h2, * h3 { /* CSS styles */ }
- Use CSS attribute selectors: You can use attribute selectors to target h2 and h3 elements that have a specific attribute. For example:
h2[attribute], h3[attribute] { /* CSS styles */ }
Q. Name media types allowed by CSS?
Ans: CSS supports several different media types, which allow you to apply styles differently depending on the type of device or display being used to view a web page. The media types supported by CSS are:
- all: This media type applies to all devices and display types.
- print: This media type applies to print devices, such as printers and print preview in browsers.
- screen: This media type applies to screen devices, such as computer monitors, tablets, and smartphones.
- speech: This media type applies to speech synthesizers.
- braille: This media type applies to braille tactile feedback devices.
- embossed: This media type applies to paged braille printers.
- handheld: This media type applies to handheld devices such as PDA and mobile phones.
- projection: This media type applies to projected presentations, such as those shown on a large screen using a projector.
- tty: This media type applies to media using a fixed-pitch character grid, such as teletypes and terminals.
- tv: This media type applies to television-type devices.
- and many more like, (min-width, max-width, min-height, max-height, aspect-ratio, color, color-index, resolution, etc)
It’s worth noting that the actual media types that are supported will depend on the capabilities of the browser or device being used to view the web page.
Q. Tell us about the property used for image scroll controlling?
Ans: The CSS property used for controlling image scrolling is the background-attachment
property. This property sets whether a background image is fixed or scrolls with the rest of the content on a web page.
The background-attachment
property accepts two values:
scroll (default)
: The background image scrolls along with the rest of the content on the web page.fixed
: The background image is fixed in place and does not move when the rest of the content on the web page is scrolled.
When using the background-attachment: fixed
, it’s important to keep in mind that the image will remain fixed in relation to the browser window, and not the containing element. It means that the background image will be fixed in place even when the user scrolls the page.
The background-attachment
property is used in conjunction with the background-image
, background-position
, and background-repeat
properties to specify the properties of a background image.
Example:
/* Make the background image fixed */
body {
background-image: url(image.jpg);
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
}
Note that the behavior of background-attachment:fixed
on mobile devices can vary between browsers and devices.
Q. Name some font-related CSS attributes?
Ans: There are several CSS attributes related to fonts that can be used to control the appearance of text on a web page. Some of the most commonly used font-related CSS attributes include:
font-family
: Specifies the font to be used for text. This can be a specific font (e.g. “Arial” or “Helvetica”), or a generic font family (e.g. “serif”, “sans-serif”, “monospace”).font-size
: Specifies the size of the font in pixels, points, or other units.font-weight
: Specifies the boldness of the font. Common values include “normal” and “bold”.font-style
: Specifies the style of the font. Common values include “normal” and “italic”.line-height
: Specifies the height of a line of text. This can be a specific value (e.g. “24px”), or a multiple of the font size (e.g. “1.5”).letter-spacing
: Specifies the amount of space between characters in a block of text.word-spacing
: Specifies the amount of space between words in a block of text.text-align
: Specifies how text is aligned within an element. Common values include “left”, “center”, “right”, and “justify”.text-decoration
: Specifies the decoration to be applied to text. Common values include “none”, “underline”, “overline”, and “line-through”.text-transform
: Specifies how text should be capitalized. Common values include “none”, “uppercase”, “lowercase” and “capitalize”.text-shadow
: Specifies the shadow effect for the text, which includes the horizontal and vertical offset, the blur radius and the color of the shadow.text-overflow
: Specifies what should happen when text overflows the containing element.
These are just a few of the many font-related CSS attributes that are available. Each of these attributes can be used to fine-tune the appearance of text on a web page and create a unique look and feel.
Q. Define contextual selectors?
Ans: Contextual selectors are CSS selectors that target elements based on their context or relationship to other elements in the HTML document. They allow you to select and apply styles to specific elements based on their location or relationship to other elements on the page.
There are several types of contextual selectors:
- Descendant selectors: These selectors target elements that are descendants of a specific element. For example,
div p
will select allp
elements that are descendants of adiv
element. - Child selectors: These selectors target elements that are direct children of a specific element. For example,
div > p
will select allp
elements that are direct children of adiv
element. - Adjacent sibling selectors: These selectors target elements that are next to a specific element. For example,
h2 + p
will select the firstp
element that immediately follows anh2
element. - General sibling selectors: These selectors target elements that are siblings of a specific element. For example,
h2 ~ p
will select allp
elements that are siblings of anh2
element. - Attribute selectors: These selectors target elements based on their attributes and attribute values. For example,
a[href='https://example.com']
will select all a elements that have ahref
attribute with the value ofhttps://example.com
- Pseudo-class selectors: These selectors target elements based on a certain state or condition. For example,
a:hover
will select alla
elements that are currently being hovered over by the user’s cursor.
Contextual selectors can be very powerful and allow you to apply styles very specific parts of your HTML document. They also make it easy to maintain your CSS code by avoiding the use of class and id selectors in many cases.
Q. Explain responsive web design?
Ans: Responsive web design (RWD) is an approach to web design that aims to make websites look and function well on a variety of devices and screen sizes. This includes desktops, laptops, tablets, and smartphones, as well as different screen resolutions and orientations.
The core principles of responsive web design are:
- Flexible layout: The layout of a responsive website should be able to adapt to the size of the screen it is being viewed on. This is achieved by using flexible grid-based layouts and media queries, which allow the layout to change based on the width of the screen.
- Flexible images: Images should also be able to adapt to the size of the screen they are being viewed on. This is achieved by using CSS to scale images proportionally, or by using the
srcset
andsizes
attribute in theimg
tag. - Flexible media: Videos and other media should also be able to adapt to the size of the screen they are being viewed on. This can be achieved by using the
object-fit
CSS property. - Mobile-first design: The design process should start with the smallest screens and then progressively enhance the layout for larger screens.
- Navigation: Navigation should be designed to work well on small screens. This can be achieved by using a “hamburger” menu for navigation, which is hidden behind a button on small screens and is displayed as a full menu on larger screens.
- Touch-friendly: Responsive websites should be designed to work well on touch-enabled devices. This means using larger buttons and links, and making sure that links are far apart from each other to prevent accidental clicks.
Overall, responsive web design allows web developers to create a single version of a website that looks and works well on a wide range of devices, rather than creating separate versions of a website for different devices. This can save time and resources, and also provide a better user experience for visitors to the website.
Q. Tell us about the general CSS nomenclature?
Ans: In CSS (Cascading Style Sheets), the general nomenclature consists of selectors, properties, and values.
Selectors are used to select the HTML element(s) that you want to style. There are several types of selectors including element, class, and ID selectors.
Properties are used to define the styles that you want to apply to the selected elements. Common properties include color, font-size, and margin.
Values are used to specify the actual settings for the properties. For example, the value for the color property could be “red” or “#ff0000”.
Q. What are the limitations of CSS?
Ans: CSS, or Cascading Style Sheets, is a powerful styling language that allows developers to control the layout and appearance of web pages. However, there are some limitations of CSS that developers should be aware of:
- Browser compatibility: Different browsers may interpret and display CSS differently, leading to inconsistencies in the layout and appearance of web pages across different browsers.
- Limited layout control: While CSS provides a wide range of layout options, it is not as powerful as other technologies such as Flexbox and Grid for advanced layout control.
- Lack of JavaScript integration: CSS does not have the ability to directly interact with JavaScript, which can make it difficult to create dynamic user interfaces.
- Limited animations and transitions: While CSS3 introduced support for animations and transitions, it is still more limited compared to JavaScript libraries such as animate.css, and GreenSock.
- Lack of data manipulation: CSS does not provide any built-in means for data manipulation and is mainly used for styling and layout.
- No logical control flow: CSS does not support control flow statements such as if-else, loop, and switch-case and thus, it’s not possible to create complex conditions and rules.
Despite these limitations, CSS is still a widely used and powerful styling language that plays a crucial role in creating visually appealing and interactive web pages.
Q. What is a CSS Preprocessor?
Ans: A CSS preprocessor is a scripting language that extends the capabilities of CSS, by allowing developers to use variables, functions, and other programming constructs in their stylesheets. The preprocessed code is then translated into regular CSS, which can be interpreted and applied by web browsers.
The most popular CSS preprocessors are:
- SASS (Syntactically Awesome Style Sheets): SASS is a powerful preprocessor that allows developers to use variables, nested rules, mixins, and other programming constructs in their stylesheets.
- LESS (Leaner Style Sheets): LESS is a dynamic stylesheet language that extends the capabilities of CSS by adding features such as variables, mixins, and functions.
- STYLUS: Stylus is a CSS preprocessor that allows developers to write stylesheets using a more expressive and powerful syntax. It also supports features such as variables, functions, and mixins.
CSS preprocessors can help to make the CSS development process more efficient and organized by allowing developers to use variables and functions to maintain consistency and reduce duplication across stylesheets. They also provide a way to use nested selectors which makes it easy to maintain and understand the style rules.
CSS preprocessors are compiled to CSS, so the browser can interpret and apply the style rules. So, the CSS preprocessors are not supported directly by the browsers. They need to be compiled before sending to the browser.
Q. What are the different types of Selectors in CSS?
Ans: There are several different types of selectors in CSS, each with its own unique functionality:
Element selectors: Element selectors select elements based on the element’s name. For example, the p
selector selects all
<p>
elements on a page.
p {
color: blue;
}
Class selectors: Class selectors select elements based on the element’s class attribute. For example, the ‘.example’ selector selects all elements with a class of ‘example’.
<p class="example">This is an example paragraph.</p>
.example {
color: blue;
}
ID selectors: ID selectors select elements based on the element’s id attribute. For example, the ‘#example’ selector selects the element with an id of ‘example’.
<p id="example">This is an example paragraph.</p>
#example {
color: blue;
}
Attribute selectors: Attribute selectors select elements based on the element’s attributes and attribute values. For example, the [type="text"]
selector selects all elements with a type attribute with the value “text”.
<input type="text" placeholder="Enter your name">
input[type="text"] {
border: 1px solid #ccc;
}
Pseudo-class selectors: Pseudo-class selectors select elements based on a certain state or condition. For example, the :hover
selector selects an element when the user hovers over it.
a:hover {
color: blue;
}
Pseudo-element selectors: Pseudo-element selectors select a specific part of an element. For example, the ::before
selector selects the content before an element.
p::before {
content: "Note: ";
}
By using these selectors, you can select specific elements or groups of elements on a webpage and apply styles to them. This allows for precise control over the layout and appearance of a webpage.
Q. What is VH/VW (viewport height/ viewport width) in CSS?
Ans: VH (viewport height) and VW (viewport width) are units of measurement in CSS that refer to a percentage of the viewport’s size. They allow developers to specify the size of elements relative to the size of the viewport, rather than absolute units such as pixels.
VH is equal to 1% of the height of the viewport and VW is equal to 1% of the width of the viewport. For example, if the viewport is 800px wide, then 1vw = 8px. Similarly, if the viewport is 600px tall, then 1vh = 6px.
/* 100vh = 100% of the viewport height */
.header {
height: 100vh;
}
/* 50vw = 50% of the viewport width */
.sidebar {
width: 50vw;
}
Using VH and VW can be useful for creating responsive designs that adapt to the size of the viewport. For example, you can use VH to ensure that a background image always fills the entire viewport, regardless of the screen size.
It’s worth noting that while VH and VW units are supported by most modern browsers, they may not work correctly on older browsers or in some mobile devices.
Additionally, VH and VW units also have some issues with accessibility. When the browser zoom level is changed, the units will still be based on the viewport size, not the actual size of the element. So, the result may be different from what the developer expected.
Q. What is the difference between inline, inline-block, and block?
Ans: In CSS, the difference between inline, inline-block, and block elements refers to the way they are displayed on a webpage and how they interact with other elements around them.
Inline elements: Inline elements are elements that are placed inline with the text, and they only take up as much width as necessary. Examples of inline elements include the <a>
, <span>
, and <img>
tags. They do not take up the full width of the parent container, and they respect the left and right margins and padding, but not the top and bottom.
<p>This is a <span>inline</span> element.</p>
Inline-block elements: Inline-block elements are similar to inline elements, but they can have a specified width and height. They also respect the top and bottom margins and padding. Examples of inline-block elements include <button>
, <input>
, and <select>
.
<div>
<button>This is an inline-block element.</button>
</div>
Block elements: Block elements take up the full width of their parent container, and they add a line break before and after the element. Examples of block elements include <div>
, <p>
, and <h1>
.
<div>
<p>This is a block element.</p>
</div>
It’s also worth noting that these display types can be changed with the CSS property display
. For example, you can change an inline element to a block element by setting its display
property to block
.
span {
display: block;
}
In summary, inline elements only take up as much width as necessary and respect left and right margins and padding, inline-block elements respect all margins and padding, and block elements take up the full width of the parent container and add a line break before and after.
Q. Difference between reset vs normalize CSS?
Ans: Both reset and normalize CSS are used to set a consistent base for styling web pages, but they do it in different ways.
Reset CSS: Reset CSS is a set of CSS rules that are used to remove all the default styles applied by the browser. This is done by setting all the elements’ styles to a default value such as setting all margins and padding to zero. This allows developers to start styling their web pages with a clean slate and avoid any cross-browser inconsistencies.
/* example of reset.css */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
Normalize CSS: Normalize CSS is a set of CSS rules that are used to make the default styles of different web browsers more consistent. Instead of removing all the default styles, normalize CSS preserves the useful defaults and corrects the inconsistencies across different browsers. This allows developers to maintain a consistent look and feel across different browsers without having to start styling their web pages from scratch.
/* example of normalize.css */
html {
line-height: 1.15; /* corrects inconsistent font size */
-webkit-text-size-adjust: 100%; /* corrects font size in mobile browsers */
}
In summary, reset CSS removes all the default styles, while normalize CSS preserves the useful defaults and corrects the inconsistencies across different browsers. The choice between reset and normalize depends on the project requirement, and the developer’s preference. Some developers prefer to start with a clean slate, while others prefer to maintain the default styles for consistency across browsers.
Q. Is it important to test the webpage in different browsers?
Ans: Yes, it is important to test webpages in different browsers to ensure that they display and function correctly across different browser environments.
Different browsers have different rendering engines and interpret web standards differently. This can lead to inconsistencies in the layout, styling, and functionality of a webpage. For example, a webpage that looks perfect in Google Chrome may have alignment issues in Internet Explorer.
Testing webpages in different browsers allows developers to identify and fix any compatibility issues, ensuring that the webpage is accessible to the widest possible audience.
It is also important to test webpages in different versions of the same browser, as browser updates can introduce new features or change how web pages are rendered.
Additionally, it’s also important to test webpages in different devices and screen sizes (responsive testing) to ensure that the page is optimized for different devices and screen sizes.
There are different tools that can help with the cross-browser testing, such as BrowserStack, Sauce Labs, CrossBrowserTesting, and more. These tools allow developers to test webpages on a wide range of different browsers and devices, making it easier to identify and fix compatibility issues.
In summary, testing webpages in different browsers is important to ensure that the webpage is accessible to the widest possible audience and display correctly across different browser environments.
Q. What are Pseudo classes?
Ans: In CSS, pseudo-classes are used to select elements based on a certain state or condition. They are denoted by a colon (:) followed by the name of the pseudo-class.
Pseudo-classes allow developers to apply styles to elements based on the element’s dynamic state, such as when a user hovers over a link or when a form input is focused.
Here are some examples of common pseudo-classes:
:hover:
Selects an element when the user hovers over it with the cursor.
a:hover {
color: blue;
}
:active:
Selects an element when it is in the process of being activated by the user.
button:active {
background-color: green;
}
:focus:
Selects an element when it has focus, typically when a user clicks or tabs into it.
input:focus {
border: 2px solid blue;
}
:visited:
Selects links that have been visited by the user.
a:visited {
color: purple;
}
:first-child:
Selects the first child element of its parent.
li:first-child {
font-weight: bold;
}
:nth-child(n):
Selects the nth child element of its parent.
li:nth-child(3) {
color: orange;
}
By using these pseudo-classes, you can create dynamic and interactive web pages that respond to user actions and events.
It’s worth noting that some pseudo-classes can be used in combination with pseudo-elements to apply styles to specific parts of an element, such as the first letter or line of a text.
Q. How do you specify units in the CSS?
Ans: In CSS, units are used to specify the numeric values of various properties such as width, height, margin, padding, and font-size. There are several different units that can be used in CSS, including:
Pixels (px): Pixels are the most commonly used unit in CSS and are used to specify the size of an element in terms of pixels.
/* width of an element will be 100 pixels */
div {
width: 100px;
}
Ems (em): Ems are a relative unit that is based on the font-size of an element. One em is equal to the font-size of the element.
/* font-size of an element will be 16 pixels */
p {
font-size: 1em;
}
Rems (rem): Rems are also a relative unit, but unlike ems, rems are based on the font-size of the root element (usually the <html> element) rather than the font-size of the element itself.
/* font-size of an element will be 16 pixels */
p {
font-size: 1rem;
}
Percentages (%): Percentages are used to specify the size of an element in terms of a percentage of the parent container.
/* width of an element will be 50% of its parent container */
div {
width: 50%;
}
Viewport units (vw, vh): Viewport units are used to specify the size of an element in terms of the viewport’s size. 1vw is equal to 1% of the viewport’s width, and 1vh is equal to 1% of the viewport’s height.
/* height of an element will be 50% of the viewport's height */
div {
height: 50vh;
}
It’s important to note that while these units can be used to specify the size of an element, it’s important to consider the content of the element and its purpose. Some elements may need to be fixed size, while others should be flexible and responsive to the parent container.
Q. Does margin-top or margin-bottom have an effect on inline elements?
Ans: No, margin-top and margin-bottom have no effect on inline elements. Inline elements are elements that are placed inline with the text, such as the <span>
or <a>
elements, and they do not have a block-level layout. These properties only affect block-level elements, which are elements that take up the full width of the parent container and create a new block formatting context, such as the <div>
or <p>
elements.
Q. How is opacity specified in CSS3?
Ans: In CSS3, the opacity property is used to specify the transparency level of an element. The property can be applied to an element using the following syntax:
element {
opacity: value;
}
Where “value” is a number between 0 and 1, with 0 being fully transparent and 1 being fully opaque. For example, to make an element 50% transparent:
element {
opacity: 0.5;
}
Alternatively, value can be specified in decimal or percentage format, like “0.5” or “50%”.
It’s worth mentioning that when the opacity property is applied to an element, it also affects all of the element’s child elements, making them transparent as well.
Q. When does DOM reflow occur?
Ans: DOM reflow, also known as layout or reflow, is the process of the browser recalculating the layout and position of all elements in the Document Object Model (DOM) in response to changes in the layout or size of elements.
There are several situations that can trigger a reflow:
- When the size or position of an element changes, either through changes in CSS or JavaScript.
- When an element is added or removed from the DOM.
- When the text or font size changes.
- When the screen size or orientation changes.
- When the contents of an element change, like an image is loaded.
- When an element’s style is updated or computed by JavaScript.
It’s worth noting that reflows can be expensive and cause performance issues if they occur frequently, as it requires the browser to recalculate the layout for the entire page. Therefore, it’s a good practice to minimize the number of reflows by, for example, avoiding to change multiple elements at the same time, or by using techniques such as layout thrashing.
Q. What is cascading in CSS?
Ans: Cascading in CSS refers to the way that styles are applied to elements in a web page. When multiple styles are defined for a single element, the browser uses a set of rules, known as the “cascade,” to determine which styles take precedence. The cascade determines the final, computed values for all CSS properties on an element.
The basic rules of the cascade are:
- Specificity: A style with a higher specificity will take precedence over one with a lower specificity. Specificity is determined by the number of ID selectors, class selectors, and element selectors used in the rule.
- Origin: Styles that are defined by the user (in a stylesheet or inline) will take precedence over styles that are defined by the browser.
- Importance: Styles that are marked as “important” will take precedence over non-important styles.
- Order: If multiple styles are defined for a single element, the last one defined will take precedence.
It’s worth noting that the cascade is used to determine the final values of all CSS properties, but it doesn’t determine which selectors will match an element, that’s done by the matching process.
Q. What does Accessibility (ally) mean?
Ans: Accessibility, also known as web accessibility or a11y, refers to the practice of making web content and applications usable by people with disabilities. This includes people with visual, auditory, motor, and cognitive impairments, as well as older users who may have difficulty using a computer or the internet.
Accessibility features can include things like:
- Text alternatives for non-text content, such as alt text for images and captions for videos.
- Keyboard-only navigation for users who can’t use a mouse.
- Large text and high-contrast color schemes for users with visual impairments.
- Audio descriptions for users who are blind or have low vision.
- Structured headings and labels to help users navigate the content using screen readers.
- The goal of accessibility is to ensure that users with disabilities have the same access to and experience of web content as users without disabilities. This is important not only for legal compliance, but also for creating inclusive and user-friendly websites that are usable by everyone.
It’s worth noting that many countries have laws and regulations regarding accessibility of digital content, such as Web Content Accessibility Guidelines (WCAG) and Americans with Disabilities Act (ADA) in the US.
Q. How do I restore the default value of a property?
Ans: To restore the default value of a CSS property, you can use the CSS keyword initial
.
The initial
keyword sets the property to its default value, which is the value the property would have if no value had been set for the element. For example, if you have set the color
property to red
and you want to restore it to its default value, you can use the following CSS rule:
element {
color: initial;
}
Alternatively, you can also use the unset
keyword which also sets the property to its default value, but it also allows you to reset inherited properties to their inherited value. For example:
element {
color: unset;
}
It’s worth noting that the initial
and unset
values will only restore the default value for the specific property it’s applied to, it will not restore the default values for all properties.
You could also use revert
keyword, which allows you to restore the value of a property to the value it would have if no styles had been applied to the element. However, this keyword is not yet widely supported by all browsers.
Q. How does Calc work?
Ans: The CSS calc()
function allows you to perform mathematical calculations in your CSS styles. It can be used to set the value of any CSS property that accepts a length, percentage, or number value.
The basic syntax of the calc()
function is as follows:
element {
property: calc(expression);
}
Where “expression” is a mathematical expression made up of numbers, units of measurement, and mathematical operators (+, -, *, /).
For example, to set the width of an element to be equal to 50% of the parent element’s width minus 20 pixels, you can use the following rule:
element {
width: calc(50% - 20px);
}
You can also use calc()
function with CSS variables, also called custom properties:
:root {
--main-width: 100px;
}
element {
width: calc(var(--main-width) + 50%);
}
It’s worth noting that the calc()
function supports the standard mathematical operators, including addition (+), subtraction (-), multiplication (*), and division (/). Also, you need to ensure that the units of the values being used in the calculation are compatible, otherwise it will not work.
Q. Difference between CSS grid vs flexbox?
Ans: CSS Grid and Flexbox are both layout systems in CSS that allow you to create flexible and responsive designs for web pages. However, they have different strengths and are best suited for different types of layout tasks.
CSS Grid is a two-dimensional layout system, meaning it can handle both columns and rows. It is best suited for creating grid-based layouts, such as those used in web page layouts, image galleries, and other complex layouts. It allows you to define a grid with rows and columns, and then place elements onto that grid. You can also control the size of the rows and columns, and align and distribute elements within the grid.
Flexbox, on the other hand, is a one-dimensional layout system, meaning it can handle either rows or columns, but not both. It is best suited for creating flexible layouts that can adjust to the size of the screen or the size of their content. It allows you to align and distribute elements along a single axis (horizontally or vertically) and control the size and position of elements in relation to their parent container.
In summary, if you need a grid-based layout, you should use CSS Grid, if you need a flexible layout that adjusts to the size of the screen or the size of the content, you should use Flexbox. Both of them can work together and solve different layout problem.
Q. What do CSS Custom properties variables mean?
Ans: CSS Custom Properties (also known as CSS Variables) are a way to store and reuse values in CSS styles. They allow you to define a value once, and then use that value in multiple places throughout your stylesheet. This can make your code more maintainable and easier to update, as you only need to change the value in one place.
Custom properties use the --
prefix to define them, and the var()
function to reference them. For example, you can define a custom property for the primary color of your website like this:
:root {
--primary-color: blue;
}
Then you can use this variable to set the color of different elements:
h1 {
color: var(--primary-color);
}
nav a {
color: var(--primary-color);
}
Custom properties can also be scoped to a specific element or class, allowing you to define different values for different parts of your website. For example:
.card {
--card-bg-color: #f8f8f8;
background-color: var(--card-bg-color);
}
It’s worth noting that custom properties are not supported by all browsers and it is recommended to use a tool like Autoprefixer or a polyfill to ensure that your website works in older browsers.
Also, you can use custom properties in CSS calc()
function as well, for example:
:root {
--main-width: 100px;
}
element {
width: calc(var(--main-width) + 50%);
}
Custom properties are a powerful tool to make your CSS more maintainable, readable and reusable.
Q. What does { box-sizing: border-box; } do?
Ans: The box-sizing
property in CSS controls how the size of an element is calculated. By default, the value is set to content-box
, which means that the element’s width and height properties only include the content inside the element and do not include padding or borders.
When you set box-sizing: border-box;
, the element’s width and height properties include the element’s content, padding, and borders. This means that the size of the element will be calculated to include the total width and height of the element, including any padding and borders.
For example, consider the following HTML and CSS:
<div class="box"></div>
.box {
width: 300px;
height: 200px;
padding: 20px;
border: 10px solid black;
}
With the default box-sizing (content-box), the total width and height of the element will be 340px and 240px, respectively. However, if you set box-sizing: border-box;
, the total width and height of the element will be 300px and 200px, respectively, which is the width and height you set originally.
Using box-sizing: border-box;
can make it easier to control the size of elements and can also prevent unexpected layout changes when adding padding or borders to elements. It’s worth noting that box-sizing
property can also be set to padding-box
, this value calculates the size of an element by including the content, padding but not the border. It’s a widely supported property, but it may not work in some older browsers.
Q. What does !important mean in CSS?
Ans: In CSS, the !important
keyword is used to indicate that a particular value for a property should take precedence over any other values that might be specified for that property. When a property is set with !important
, it will override any other styles that might be applied to the element, even if those styles have a higher specificity.
The !important
keyword is added at the end of a property value, like this:
element {
property: value !important;
}
For example, consider the following CSS:
.error {
color: red;
}
.important-error {
color: red !important;
}
If you apply both classes to the same element, the text color will be red because the second class has the !important keyword and it will override the first class.
It’s worth noting that using !important
is generally considered a bad practice, as it can make your code harder to maintain and understand. It can also make debugging difficult, as it can be unclear where a particular style is coming from. It’s recommended to use it only as a last resort and try to achieve the same result using other CSS techniques such as increasing specificity, class naming, and cascading.
Q. How does absolute positioning work?
Ans: In CSS, the position
property is used to control the positioning of an element. When the value of position
is set to absolute
, the element is positioned relative to its nearest positioned ancestor, instead of being positioned based on the normal flow of the document.
An element with position: absolute
is taken out of the normal flow of the document and positioned with respect to its closest positioned ancestor, or with respect to the initial containing block (usually the viewport) if none of its ancestor is positioned. The top, right, bottom, and left properties are used to specify the position of the element.
For example, consider the following HTML and CSS:
<div class="container">
<div class="box"></div>
</div>
.container {
position: relative;
}
.box {
position: absolute;
top: 10px;
left: 20px;
}
In this example, the .box
element is positioned 10px
from the top and 20px
from the left of the .container element because .container
has a position: relative
and it’s the closest positioned ancestor of .box
.
It’s worth noting that when an element is positioned absolutely, it doesn’t take up any space in the normal flow of the document and it doesn’t affect the layout of the other elements. Also, you can use negative values for top, right, bottom, and left properties to position the element outside of its parent element.
You can also use right, bottom
properties in addition to top, left
to give more control over the positioning of the element. Also, by default, an element with position: absolute
will be positioned relative to the browser viewport if it doesn’t have a positioned ancestor, you can use transform: translate
property to position it relative to the its parent without changing the layout.
Q. Does this property work overflow: hidden?
Ans: The overflow
property in CSS is used to control the behavior of content that exceeds the boundaries of an element. When the value of overflow
is set to hidden
, any content that exceeds the boundaries of the element will be hidden and not be visible to the user.
For example, consider the following HTML and CSS:
<div class="container">
<div class="box"></div>
</div>
.container {
overflow: hidden;
}
If the content of the .box
element exceeds the boundaries of the .container
element, it will be hidden and not be visible to the user.
It’s worth noting that the overflow
property can also take other values such as scroll
, auto
, visible
, and can be applied to both the x and y axis with overflow-x
and overflow-y
respectively.
overflow: hidden
is widely supported by all modern browser and it’s a widely used property to control the visibility of overflowing content. It’s also used to hide the scrollbar on elements that overflow the container.
Q. What are Pseudo classes?
Ans: In CSS, a pseudo-class is a keyword added to selectors that specifies a special state or characteristic of the selected elements. Pseudo-classes allow you to select elements based on their current state, such as whether they are hovered over, whether they are active, or whether they are the first child of a parent element.
Pseudo-classes are added to a selector using a colon (:
) followed by the keyword for the pseudo-class. For example, to select all a
elements that are being hovered over, you can use the :hover
pseudo-class like this:
a:hover {
color: blue;
}
Some of the most common pseudo-classes include:
:hover
: Selects elements when the user hovers over them with a cursor.:active
: Selects elements that are in the process of being activated, such as when a button is being clicked.:visited
: Selects links that have been visited by the user.:first-child
: Selects the first child element of a parent element.:last-child
: Selects the last child element of a parent element.:nth-child(n)
: Selects the nth child element of a parent element.:not(selector)
: Selects elements that do not match the specified selector.
It’s worth noting that some pseudo-classes are dynamic and change based on the state of the element while others are static and they select elements based on their location or relation in the document.
Pseudo-classes can be combined with other selectors and pseudo-elements to make powerful and specific selections.
Pseudo-classes are widely supported by modern browsers and it’s a widely used feature in CSS to select elements based on their state, location, or relation in the document.
Advanced CSS Interview Questions
Q. How is a CSS selector used?
Ans: A CSS selector is used to select elements on an HTML page and apply styles to them. It specifies the elements to which a set of CSS rules will apply. A CSS selector can be a simple element name, or it can include class and ID selectors, attribute selectors, and pseudo-classes and pseudo-elements.
For example, the following CSS rule uses the h1
element selector to select all h1
elements in the HTML document and apply the specified styles to them:
h1 {
color: blue;
}
You can also use class and ID selectors, the class selector uses a dot (.) prefix and the ID selector uses a pound (#) prefix, for example:
.warning {
color: red;
}
#main-header {
background-color: black;
}
You can use multiple selectors to apply styles to different elements at the same time, for example:
h1, h2, h3 {
font-weight: bold;
}
This will apply the font-weight: bold;
styles to all h1, h2, and h3 elements.
You can also use attribute selectors to select elements based on their attributes, for example:
a[href^="http"] {
color: blue;
}
This will select all a
elements whose href
attribute starts with “http” and apply the specified styles to them.
CSS selectors can be very powerful and specific, they can select elements based on their type, class, ID, attribute, or state, this is why they are the backbone of CSS and they are widely used in web development.
Q. What are CSS image scripts?
Ans: CSS image sprites are a technique used in web development to combine multiple images into a single image file. This technique allows you to use a single image file to represent multiple images on a website, which can improve the performance of the website by reducing the number of HTTP requests needed to load the images.
An image sprite is created by combining multiple images into a single image file, and then using CSS to position the images correctly. The CSS uses the background-position
property to position the images correctly and the background-image
property to define the image file that contains the images.
For example, consider the following HTML and CSS:
<div class="icon icon-home"></div>
<div class="icon icon-search"></div>
.icon {
background-image: url('sprites.png');
width: 16px;
height: 16px;
display: inline-block;
}
.icon-home {
background-position: 0 0;
}
.icon-search {
background-position: -16px 0;
}
In this example, the sprites.png
image file contains both the home and search icons. The .icon
class defines the background image and the size of the icon. The .icon-home
and .icon-search
classes use the background-position
property to position the correct icon in the image file.
CSS image sprites can improve the performance of a website by reducing the number of HTTP requests needed to load images. It can also save the space on the server and improve the loading time of the website.
It’s worth noting that while CSS sprites can be beneficial for performance, they can make it harder to update or maintain the images. Also, it’s important to consider the layout of the images inside the sprites and try to group the images that are used together.
Q. Explain CSS specificity?
Ans: CSS specificity is a concept that determines which CSS styles will be applied to an HTML element. It is determined by the number and type of CSS selectors used to select the element. Specificity is a weight that is applied to a given CSS declaration, and the declaration with the highest specificity will be applied. In other words, styles with higher specificity will override styles with lower specificity. Specificity is usually represented as a three-part value, such as 0,0,0,1 (four numbers separated by commas), with each value representing the number of ID selectors, class selectors, and element selectors used in the selector. For example, a selector using one ID, two classes, and three elements would have a specificity value of 1,2,3.
Q. Define gradients in CSS?
Ans: A gradient in CSS is a transition between two or more colors, which can be used to create a smooth transition between colors in an element. There are two types of gradients: linear and radial.
Linear gradients are created by specifying a direction and angle for the gradient, and the colors will transition along that angle. For example, a linear gradient with the direction “to right” will transition the colors from left to right.
Radial gradients are created by specifying the center of the gradient and the shape and size of the transition area. For example, a radial gradient with the center at the top left corner and a shape of “ellipse” will transition the colors from the top left corner to the bottom right corner in an elliptical shape.
Gradients can be applied to background, background-image, border-image, and other properties. The syntax for creating a linear gradient is typically:
background: linear-gradient(direction, color-stop1, color-stop2, ...);
and for radial gradient is:
background: radial-gradient(shape size at position, color-stop1, color-stop2, ...);
You can also use repeating-linear-gradient
and repeating-radial-gradient
to create repeating gradients, which are gradients that repeat themselves as many times as space allows.
Q. What are the properties of flexbox?
Ans: Flexbox is a layout mode in CSS that allows elements to be aligned and distributed within a container. It provides a more efficient way to lay out, align, and distribute space among items in a container, even when their size is unknown or dynamic. Flexbox has several properties that can be used to control the layout of elements within a container:
display
: This property is set on the container and specifies that its children should be laid out using flexbox. The value for this property is typically set toflex
orinline-flex
.flex-direction
: This property specifies the direction in which items are laid out within the container. The possible values arerow
,row-reverse
,column
, andcolumn-reverse
.justify-content
: This property aligns items along the main axis of the container. The possible values areflex-start
,flex-end
,center
,space-between
, andspace-around
.align-items
: This property aligns items along the cross axis of the container. The possible values areflex-start
,flex-end
,center
,baseline
, andstretch
.align-content
: This property aligns the lines of a multi-line container along the cross axis. The possible values areflex-start
,flex-end
,center
,space-between
,space-around
, andstretch
.flex-wrap
: This property specifies whether items should be wrapped onto multiple lines if they don’t fit within the container. The possible values arenowrap
,wrap
, andwrap-reverse
.flex-flow
: This is a shorthand property that combinesflex-direction
andflex-wrap
into a single property.align-self
: This property aligns a single item along the cross axis of the container. The possible values areauto
,flex-start
,flex-end
,center
,baseline
, andstretch
.order
: This property controls the order in which items are displayed within a container. The default value is 0 and elements are displayed in the order in which they appear in the HTML.flex-grow
: This property specifies how much an item should grow relative to the rest of the items in the container. The default value is 0.flex-shrink
: This property specifies how much an item should shrink relative to the rest of the items in the container. The default value is 1.flex-basis
: This property specifies the initial size of an item before flex-grow and flex-shrink properties are applied. The default value isauto
.flex
: This is a shorthand property that combinesflex-grow
,flex-shrink
, andflex-basis
into a single property.
Q. Tell us about the use of the CSS Box Model?
Ans: The CSS Box Model is a concept that describes the layout of elements on a web page. It defines how the dimensions of an element are calculated and how the element is positioned in relation to other elements on the page.
Each HTML element is considered as a rectangular box, which consists of four parts:
- Content: The area where the element’s content (such as text or images) is displayed.
- Padding: The transparent area around the content. It is used to create space between the content and the border.
- Border: A line that surrounds the element and separates it from other elements on the page.
- Margin: The transparent area outside the border that separates the element from other elements on the page.
The total width and height of an element is the sum of the content width and height, the padding, the border and the margin.
The box model can be used to control the layout and positioning of elements on a page, for example, by setting the dimensions, padding, margins, and borders of elements. Additionally, it can be used to create visual effects such as spacing and borders.
It is important to note that the box-sizing property can be used to change the way the box model is calculated. The default value is content-box
where the width and height properties only apply to the content and do not include padding or borders. The other value is border-box
where the width and height properties include padding and borders as well as the content.
Q. Differentiate between absolute and relative in CSS?
Ans: In CSS, the position property can be set to either absolute or relative.
An element with a position set to absolute is positioned relative to the nearest positioned ancestor, but still maintains the layout in the normal flow. However, if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
An element with a position set to relative is positioned relative to its normal position, and does not affect the layout of the other elements on the page.
In summary, the main difference between absolute and relative positioning in CSS is that an element with absolute positioning is positioned relative to its nearest positioned ancestor, while an element with relative positioning is positioned relative to its normal position.
Q. What is common between class and ID?
Ans: Both classes and IDs in CSS are used to select and style specific elements on a web page.
The main difference between them is that an ID should be used for a unique element on a page, while a class can be used for multiple elements.
Both class and ID can be used to select elements and apply styles to them. Both can be used in combination with HTML elements to select and style them.
In summary, the commonalities between classes and IDs in CSS are that they are both used to select and style specific elements on a web page, and they can both be used in combination with HTML elements to select and style them.
Conclusion:
By familiarizing yourself with the common CSS interview questions discussed in this blog post, you can be well-prepared for your next job interview and showcase your CSS skills. Remember that it’s also important to have a good understanding of HTML and web development concepts to be able to fully utilize CSS in your development process. Keep practicing and learning, and you’ll be ready to ace your next CSS interview.
Also Read: