What Is CSS?: CSS Interview Questions For Freshers
What Is CSS?: CSS Interview Questions For Freshers
1. What is CSS?
Cascading Style Sheets fondly referred to as CSS, is a simply designed language intended to simplify
the process of making web pages presentable. CSS allows you to apply styles to web pages.
More importantly, CSS enables you to do this independent of the HTML that makes up each web
page. CSS is easy to learn and understood, but it provides powerful control over the presentation of
an HTML document.
CSS saves time: You can write CSS once and reuse the same sheet on multiple HTML pages.
Easy Maintenance: To make a global change simply change the style, and all elements in all
the webpages will be updated automatically.
Search Engines: CSS is considered a clean coding technique, which means search engines
won’t have to struggle to “read” its content.
Superior styles to HTML: CSS has a much wider array of attributes than HTML, so you can
give a far better look to your HTML page in comparison to HTML attributes.
Offline Browsing: CSS can store web applications locally with the help of an offline cache.
Using of this we can view offline websites.
CSS plays an important role, by using CSS you simply got to specify a repeated style for an
element once & use it multiple times because CSS will automatically apply the required
styles.
The main advantage of CSS is that style is applied consistently across a variety of sites. One
instruction can control several areas which are advantageous.
Web designers need to use a few lines of programming for every page improving site speed.
Cascading sheet not only simplifies website development but also simplifies maintenance as
a change of one line of code affects the whole website and maintenance time.
CSS changes are device friendly. With people employing a batch of various range of smart
devices to access websites over the web, there’s a requirement for responsive web design.
It has the power for re-positioning. It helps us to determine the changes within the position
of web elements that are there on the page.
These bandwidth savings are substantial figures of insignificant tags that are indistinct from a
mess of pages.
With CSS, what works with one browser might not always work with another. The web
developers need to test for compatibility, running the program across multiple browsers.
After making the changes we need to confirm the compatibility if they appear. A similar
change affects all the browsers.
The programing language world is complicated for non-developers and beginners. Different
levels of CSS i.e. CSS, CSS 2, CSS 3 are often quite confusing.
Browser compatibility (some style sheets are supported and some are not).
CSS works differently on different browsers. IE and Opera support CSS as different logic.
There are multiple levels that create confusion for non-developers and beginners.
S.No
CSS CSS3
.
Bootstrap
Foundation
Bulma
UIKit
Semantic UI
Materialize
Pure
Tailwind CSS
A CSS style rule consists of a selector, property, and its value. The selector points to the HTML
element where CSS style is to be applied. The CSS property is separated by semicolons.
Syntax:
selector {
Property: value;
}
Cascading Style Sheet(CSS) is used to set the style in web pages that contain HTML elements. It sets
the background color, font size, font family, color, … etc properties of elements on a web page.
There are three types of CSS which are given below:
Inline CSS: Inline CSS contains the CSS property in the body section attached with the
element known as inline CSS. This kind of style is specified within an HTML tag using the style
attribute.
Internal or Embedded CSS: This can be used when a single HTML document must be styled
uniquely. The CSS ruleset should be within the HTML file in the head section i.e the CSS is
embedded within the HTML file.
External CSS: External CSS contains a separate CSS file which contains only style property
with the help of tag attributes (For example class, id, heading, … etc). CSS property is written
in a separate file with .css extension and should be linked to the HTML document using
the link tag. This means that for each element, style can be set only once and that will be
applied across web pages.
Inline CSS has the highest priority, then comes Internal/Embedded followed by External CSS which
has the least priority. Multiple style sheets can be defined on one page. If for an HTML tag, styles are
defined in multiple style sheets then the below order will be followed.
As Inline has the highest priority, any styles that are defined in the internal and external style
sheets are overridden by Inline styles.
Internal or Embedded stands second in the priority list and overrides the styles in the
external style sheet.
External style sheets have the least priority. If there are no styles defined either in the inline
or internal style sheet then external style sheet rules are applied for the HTML tags.
CSS Selectors: CSS Selectors are used to selecting HTML elements based on their element name, id,
attributes, etc. It can select one or more elements simultaneously.
element selector: The element selector in CSS is used to select HTML elements which are required to
be styled. In a selector declaration, there is the name of the HTML element, and the CSS properties
which are to be applied to that element is written inside the brackets {}.
Syntax:
element_name {
// CSS Property
}
id selector: The #id selector is used to set the style of the given id. The id attribute is the unique
identifier in an HTML document. The id selector is used with a # character.
Syntax:
#id_name {
// CSS Property
}
class selector: The .class selector is used to select all elements which belong to a particular class
attribute. To select the elements with a particular class, use the (.) character with specifying the class
name. The class name is mostly used to set the CSS property to the given class.
Syntax:
.class_name {
// CSS Property
}
Comments are the statements in your code that are ignored by the compiler and are not executed.
Comments are used to explain the code. They make the program more readable and understandable.
Syntax:
/* content */
RGBA contains A (Alpha) which specifies the transparency of elements. The value of alpha lies
between 0.0 to 1.0 where 0.0. represents fully transparent and 1.0 represents not transparent.
Syntax:
h1 {
color:rgba(R, G, B, A);
}
HSL: HSL stands for Hue, Saturation, and Lightness respectively. This format uses the cylindrical
coordinate system.
Hue: Hue is the degree of the color wheel. Its value lies between 0 to 360 where 0
represents red, 120 represents green and 240 represents a blue color.
Saturation: It takes a percentage value, where 100% represents completely saturated, while
0% represents completely unsaturated (gray).
Lightness: It takes a percentage value, where 100% represents white, while 0% represents
black.
Syntax:
h1 {
color:hsl(H, S, L);
}
Example:
HTML
<html>
<head>
<style>
h1{
text-align:center;
</style>
</head>
<body>
<h1>
GeeksforGeeks
</h1>
</body>
</html>
Output:
The CSS background properties are used to define the background effects for elements.
3. background-repeat: By default, the background image property repeats the image both
horizontally and vertically.
4. background-attachment: This property is used to fix the background ground image. The
image will not scroll with the page.
CSS border properties allow us to set the style, color, and width of the border.
Border Style: The border-style property specifies the type of border. None of the other
border properties will work without setting the border style.
Border Width: Border width sets the width of the border. The width of the border can be in
px, pt, cm or thin, medium and thick.
Border Color: This property is used to set the color of the border. Color can be set using the
color name, hex value, or RGB value. If the color is not specified border inherits the color of
the element itself.
CSS margins are used to create space around the element. We can set the different sizes of margins
for individual sides (top, right, bottom, left).
Margin properties can have the following values:
1. top = 40px
2. right = 100px
3. bottom = 120px
4. left = 80px
Margin is used to create space around elements and padding is used to create space around
elements inside the border.
We can set the margin property to auto but we cannot set the padding property to auto.
In Margin property we can allow negative or float number but in padding we cannot allow
negative values.
Margin and padding target all the 4 sides of the element. Margin and padding will work
without the border property also. The difference will be more clear with the following
example.
Example:
HTML
<!DOCTYPE html>
<html>
<head>
<style>
h2 {
margin:50px;
padding:80px;
</style>
</head>
<body>
<h1>GEEKSFORGEEKS</h1>
<h2>
Padding properties
</h2>
</body>
</html>
Output:
The CSS box model is a container that contains multiple properties including borders, margin,
padding, and the content itself. It is used to create the design and layout of web pages. It can be used
as a toolkit for customizing the layout of different elements. The web browser renders every element
as a rectangular box according to the CSS box model.
Box-Model has multiple properties in CSS. Some of them are given below:
borders
margins
padding
Content
Border Area: It is the area between the box’s padding and margin. Its dimensions are given
by the width and height of the border.
Margin Area: This area consists of space between border and margin. The dimensions of the
Margin area are the margin-box width and the margin-box height. It is useful to separate the
element from its neighbors.
Padding Area: It includes the element’s padding. This area is actually the space around the
content area and within the border box. Its dimensions are given by the width of the
padding-box and the height of the padding-box.
Content Area: This area consists of content like text, images, or other media content. It is
bounded by the content edge and its dimensions are given by content box width and height.
CSS border properties allow us to set the style, color, and width of the border.
CSS outline property allows us to draw a line around the element, outside the border.
Example:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<style>
p{
</style>
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>
Output:
Differences:
Unlike borders, outlines don’t allow us to set each edge to a different width, or set different
colors and styles for each edge. An outline is the same on all sides.
Outlines do not take up space, because they are always placed on top of the box of the
element.
CSS text formatting properties are used to format text and style text.
CSS text formatting includes the following properties:
1. Text-color
2. Text-alignment
3. Text-decoration
4. Text-transformation
5. Text-indentation
6. Letter spacing
7. Line height
8. Text-direction
9. Text-shadow
A link is a connection from one web page to another web page. CSS property can be used to style the
links in various different ways.
States of Link: Before discussing CSS properties, it is important to know the states of a link. Links can
exist in different states and they can be styled using pseudo-classes.
There are four states of links given below:
To add an image as the list-item marker in a list, we use the list-style-image property in CSS.
Syntax:
The style display property is used to hide and show the content of HTML DOM by accessing the
DOM element using JavaScript/jQuery.
display: "none";
display:"block";
Example:
HTML
<!DOCTYPE html>
<html>
<head>
<style>
.visible {
display: block;
.hidden {
display: none;
</style>
</head>
<body>
<p>
</p>
</body>
</html>
Output:
The visibility property is used to hide or show the content of HTML elements. The visibility property
specifies that the element is currently visible on the page. The ‘hidden’ value can be used to hide the
element. This hides the element but does not remove the space taken by the element, unlike the
display property.
Syntax:
visibility : 'hidden';
visibility :'visible';
Example:
HTML
<!DOCTYPE html>
<html>
<head>
<style>
.visible {
visibility: visible;
.hidden {
visibility: hidden;
</style>
</head>
<body>
</body>
</html>
Output:
25. What is the difference between display: none and visibility: hidden?
Both of the property is quite useful in CSS. The visibility: “hidden”; property is used to specify
whether an element is visible or not in a web document but the hidden elements take up space in
the web document. The visibility is a property in CSS that specifies the visibility behavior of an
element and display: “none” property is used to specify whether an element is exist or not on the
website.
Syntax:
Visibility property:
Display property:
So, the difference between display: “none”; and visibility: “hidden”;, right from the name itself we
can tell the difference as display: “none”, completely gets rids of the tag, as it had never existed in
the HTML page whereas visibility: “hidden”;, just makes the tag invisible it will still be on the HTML
page occupying space it’s just invisible.
Creating an overlay effect simply means putting two div together at the same place but both the div
appear when needed i.e while hovering or while clicking on one of the div to make the second one
appear. Overlays are very clean and give the webpage a tidy look. It looks sophisticated and is simple
to design. Overlays can create using two simple CSS properties:
The z-index property is used to displace elements on the z-axis i.e in or out of the screen. It is used
to define the order of elements if they overlap with each other.
Syntax:
z-index: auto|number|initial|inherit;
The position property in CSS tells about the method of positioning for an element or an HTML entity.
The position property in CSS tells about the method of positioning for an element or an HTML entity.
There are five different types of position properties available in CSS:
1. Fixed
2. Static
3. Relative
4. Absolute
5. Sticky
The positioning of an element can be done using the top, right, bottom, and left properties. These
specify the distance of an HTML element from the edge of the viewport. To set the position by these
four properties, we have to declare the positioning method.
1. Fixed: Any HTML element with position: fixed property will be positioned relative to the viewport.
An element with fixed positioning allows it to remain at the same position even as we scroll the page.
We can set the position of the element using the top, right, bottom, and left.
2. Static: This method of positioning is set by default. If we don’t mention the method of positioning
for any element, the element has the position: static method by default. By defining Static, the top,
right, bottom and left will not have any control over the element. The element will be positioned
with the normal flow of the page.
3. Relative: An element with position: relative is positioned relatively with the other elements which
are sitting at top of it. If we set its top, right, bottom, or left, other elements will not fill up the gap
left by this element.
4. Absolute: An element with position: absolute will be positioned with respect to its parent. The
positioning of this element does not depend upon its siblings or the elements which are at the same
level.
5. Sticky: Element with position: sticky and top: 0 played a role between fixed & relative based on
the position where it is placed. If the element is placed in the middle of the document then when the
user scrolls the document, the sticky element starts scrolling until it touches the top. When it
touches the top, it will be fixed at that place in spite of further scrolling. We can stick the element at
the bottom, with the bottom property.
The CSS overflow controls the big content. It tells whether to clip content or to add scroll bars. The
overflow contains the following property:
visible
hidden
scroll
auto
1. Visible: The content is not clipped and is visible outside the element box.
2. Hidden: The overflow is clipped and the rest of the content is invisible.
3. Scroll: The overflow is clipped but a scrollbar is added to see the rest of the content. The scrollbar
can be horizontal or vertical.
Float is a CSS property written in a CSS file or directly in the style of an element. The float property
defines the flow of content. Below are the types of floating properties:
float: inherit The element inherits the floating property of its parent (div, table, etc…)
Inline-block: This feature uses both properties: block and inline. So, this property aligns the div inline
but the difference is it can edit the height and the width of the block. Basically, this will align the div
both in the block and inline fashion.
Example:
HTML
<!DOCTYPE html>
<html>
<head>
<style>
#main{
height: 100px;
width: 200px;
background: teal;
display: inline-block;
}
#main1{
height: 100px;
width: 200px;
background: cyan;
display: inline-block;
#main2{
height: 100px;
width: 200px;
background: green;
display: inline-block;
.gfg {
margin-left:200px;
font-size:42px;
font-weight:bold;
color:#009900;
.geeks {
font-size:25px;
margin-left:210px;
.main {
margin:50px;
</style>
</head>
<body>
</div>
</body>
</html>
Output:
This solution will work for a single line and multiple lines of text, but it still requires a fixed height
container:
div {
height: 200px;
line-height: 200px;
text-align: center;
border: 2px dashed #f69c55;
}
span {
display: inline-block;
vertical-align: middle;
line-height: normal;
}
div{
GeeksforGeeks
}
Example: This example uses the position property to make the image align to the center.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<style>
#Outer {
height: 300px;
position: relative;
img {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
</style>
</head>
<body>
<div id = "Outer">
<img src=
"https://media.geeksforgeeks.org/wp-content/uploads/gfgbg.png"/>
</div>
</body>
</html>
Output:
CSS combinators are explaining the relationship between two selectors. CSS selectors are the
patterns used to select the elements for style purposes. A CSS selector can be a simple selector or a
complex selector consisting of more than one selector connected using combinators.
There are four types of combinators available in CSS which are discussed below:
General Sibling selector: The general sibling selector is used to select the element that follows the
first selector element and also shares the same parent as the first selector element. This can be used
to select a group of elements that share the same parent element.
Adjacent Sibling selector: The Adjacent sibling selector is used to select the element that is adjacent
or the element that is next to the specified selector tag. This combinator selects only one tag that is
just next to the specified tag.
Child Selector: This selector is used to select the element that is the immediate child of the specified
tag. This combinator is stricter than the descendant selector because it selects only the second
selector if it has the first selector element as its parent.
Descendant selector: This selector is used to select all the child elements of the specified tag. The
tags can be the direct child of the specified tag or can be very deep in the specified tag. This
combinator combines the two selectors such that selected elements have an ancestor same as the
first selector element.
A Pseudo class in CSS is used to define the special state of an element. It can be combined with a CSS
selector to add an effect to existing elements based on their states. For Example, changing the style
of an element when the user hovers over it, or when a link is visited. All of these can be done using
Pseudo Classes in CSS.
Syntax:
selector: pseudo-class{
property: value;
}
There are many Pseudo-classes in CSS but the ones which are most commonly used are as follows:
:hover Pseudo-class: This pseudo-class is used to add a special effect to an element when
our mouse pointer is over it. The below example demonstrates that when your mouse enters
the box area, its background color changes from yellow to orange.
:active Pseudo-class: This pseudo-class is used to select an element that is activated when
the user clicks on it. The following example demonstrates that when you click on the box, its
background color changes for a moment.
:focus Pseudo-class: This pseudo-class is used to select an element that is currently focussed
by the user. It works on user input elements used in forms and is triggered as soon as the
user clicks on it. In the following example, the background color of the input field which is
currently focused changes.
:visited Pseudo-class: This pseudo-class is used to select the links which have been already
visited by the user. In the following example, the color of the link changes once it is visited.
Pseudo Elements: Pseudo-element in CSS is used to add style to specified parts of an element.
Example: Using style before or after an element.
Syntax:
selector::pseudo-element {
property:value;
}
::before Pseudo-element: It is used to add some CSS property before an element when that
element is called.
::after Pseudo-element: It is used to add some CSS property after an element when that
element is called.
1. Linear Gradients: It includes the smooth color transitions to going up, down, left, right, and
diagonally. A minimum of two colors are required to create a linear gradient. More than two color
elements can be possible in linear gradients. The starting point and the direction are needed for the
gradient effect.
Syntax:
2. CSS Radial Gradients: A radial gradient differs from a linear gradient. It starts at a single point and
emanates outward. By default, the first color starts at the center position of the element and then
fades to the end color towards the edge of the element. Fade happens at an equal rate until
specified.
Syntax:
Yes, we can, a transformation modifies an element by its shape, size, and position. It transforms the
elements along the X-axis and Y-axis.
There are six main types of 2D transformations which are listed below:
translate()
rotate()
scale()
skewX()
skewY()
matrix()
There are three main types of transformation which are listed below:
rotateX()
rotateY()
rotateZ()
Transitions in CSS allow us to control the way in which transition takes place between the two states
of the element.
The transition allows us to determine how the change in color takes place. We can use the transitions
to animate the changes and make the changes visually appealing to the user and hence, giving a
better user experience and interactivity. In this article, we will show you how to animate the
transition between the CSS properties.
There are four CSS properties that you should use, all or in part (at least two, transition-property and
transition-duration, is a must), to animate the transition. All these properties must be placed along
with other CSS properties of the initial state of the element:
transition-property: This property allows you to select the CSS properties which you want to
animate during the transition(change).
Syntax:
transition-duration: This property allows you to determine how long it will take to complete
the transition from one CSS property to the other.
Syntax:
transition-duration: time;
Here, time can be in seconds(s) or milliseconds(ms), you should use ‘s’ or ‘ms’ after the number
(without quotes).
transition-timing-function: This property allows you to determine the speed of change and
the manner of change, during the transition. Like, the change should be fast at the beginning
and slow at the end, etc.
Syntax:
transition-timing-function: ease|ease-in|ease-out|ease-in-out|linear|
step-start|step-end;
transition-delay: This property allows you to determine the amount of time to wait before
the transition actually starts to take place.
Syntax:
transition-delay: time;
Here, again, time can be in seconds(s) or milliseconds(ms), and you should use ‘s’ or ‘ms’ after the
number (without quotes).
The Shorthand Property You can combine all the four transition properties mentioned
above, into one single shorthand property, according to the syntax given below. This saves us
from writing long codes and prevents us from getting messy. Note the ordering of property, it
has significance.
Syntax:
CSS Animations is a technique to change the appearance and behavior of various elements in web
pages. It is used to control the elements by changing their motions or display. It has two parts, one
which contains the CSS properties which describe the animation of the elements and the other
contains certain keyframes which indicate the animation properties of the element and the specific
time intervals at which those have to occur.
The @keyframes rule: Keyframes are the foundations with the help of which CSS Animations works.
They define the display of the animation at the respective stages of its whole duration. For example:
In the following code, the paragraph changes its color with time. At 0% completion, it is red, at 50%
completion it is of orange color and at full completion i.e. at 100%, it is brown.
Example:
HTML
<!DOCTYPE html>
<html>
<head>
<style>
#gfg {
animation-name: color;
animation-duration: 25s;
padding-top:30px;
padding-bottom:30px;
#geeks {
font-size: 40px;
text-align:center;
font-weight:bold;
color:#090;
padding-bottom:5px;
#geeks1 {
font-size:17px;
font-weight:bold;
text-align:center;
@keyframes color {
0% {
background-color: red;
50% {
background-color: orange;
100% {
background-color: brown;
</style>
</head>
<body>
<div id = "gfg">
<div id = "geeks">GeeksforGeeks</div>
<div id = "geeks1">
</div>
</div>
</body>
</html>
Output:
The box-sizing CSS property defines how the user should calculate the total width and height of an
element i.e. padding and borders, are to be included or not.
Syntax:
box-sizing: content-box|border-box;
Property Values:
content-box: This is the default value of the box-sizing property. In this mode, the width and
height properties include only the content. Border and padding are not included in it i.e if we
set an element’s width to 200 pixels, then the element’s content box will be 200 pixels wide,
and the width of any border or padding will be added to the final rendered width.
border-box: In this mode, the width and height properties include content, padding, and
borders i.e if we set an element’s width to 200 pixels, that 200 pixels will include any border
or padding we added, and the content box will shrink to absorb that extra width. This
typically makes it much easier to size elements.
Media query is used to create a responsive web design. It means that the view of a web page differs
from system to system based on screen or media types.
Orientation
Resolution
A media query consist of a media type that can contain one or more expression which can be either
true or false. The result of the query is true if the specified media matches the type of device the
document is displayed on. If the media query is true then a style sheet is applied.
Syntax:
Syntax:
.main-container {
display: flex;
}
Flex Properties:
flex-direction
flex-wrap
flex-flow
justify-content
align-items
align-content
It is a CSS property that offers a grid-based layout system, with rows and columns, making it easier to
design web pages without floats and positioning.
Syntax:
Flexbox offers greater control over alignment and space distribution between items. Being
one-dimensional, Flexbox only deals with either columns or rows.
The grid has two-dimension layout capabilities which allow flexible widths as a unit of length.
This compensates for the limitations in Flex.
2. Alignment:
Flex Direction allows developers to align elements vertically or horizontally, which is used
when developers create and reverse rows or columns.
CSS Grid deploys fractional measure units for grid fluidity and auto-keyword functionality to
automatically adjust columns or rows.
3. Item Management
Flex Container is the parent element while Flex Item represents the children. The Flex
Container can ensure balanced representation by adjusting item dimensions. This allows
developers to design for fluctuating screen sizes.
Grid supports both implicit and explicit content placement. Its inbuilt automation allows it to
automatically extend line items and copy values into the new creation from the preceding
item.
Support
Layout First Content First
Type
46. What is the best way to include a CSS file? Why use @import?
The External Style Sheet (using HTML <link> Tag) is the best method that is used to link the element.
Maintaining and re-using the CSS file across different pages is easy and efficient. The <link> tag is
placed in the HTML <head> element. To specify a media type=”text/css” for a Cascading Style Sheet
<type> attribute which is used to ignore style sheet types that are not supported in a browser.
@import rule: The @import rule is used to import one style sheet into another style sheet. This rule
also supports media queries so that the user can import the media-dependent style sheet. The
@import rule must be declared at the top of the document after any @charset declaration.
Characteristics of @import:
The @import at-rule is used to import a style sheet into an HTML page or another style
sheet.
The @import at-rule is also used to add media queries, therefore import is media-
dependent.
It is always to be declared at the top of the document.
Syntax:
All CSS style sheets are case-insensitive, except for portions that are not under the control of CSS. For
example, the case sensitivity due to values of the HTML attributes “id” and “class”, font names, and
URIs lies outside the scope of this specification.
CSS allows the animation of HTML elements without using JavaScript. An animation lets an element
systematically and with proper timing, change from one style to another. You can change whatever
CSS properties you want, and end a number of times, as you want it. To use CSS animation, you must
first specify some @keyframes for the animation. @keyframes will describe which styles that
element will have at specific times. We will be using a basic example such as the animation of a
battery charging.
The @keyframes property has the option to divide the animation time into parts/percentage and
perform an activity that is specified for that part of the whole duration of the animation. The
@keyframes property is given to each animation according to the name of that animation. It allows
you to run the animation infinitely as well.
Keyframes are the foundations with the help of which CSS Animations works. They define the display
of the animation at the respective stages of its whole duration. For example: In the following code,
the paragraph changes its color with time. At 0% completion, it is red, at 50% completion it is of
orange color and at full completion i.e. at 100%, it is brown.
Example:
HTML
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 200px;
height: 200px;
margin: 200px;
border-radius: 100px;
background-color: red;
animation: circle 8s infinite;
@keyframes circle {
0% {
background-color: red;
25% {
background-color: yellow;
50% {
background-color: blue;
100% {
background-color: green;
</style>
</head>
<body>
<div></div>
</body>
</html>
Output:
50. What are CSS counters?
Counters in CSS are basically variables that can be used for numbering and values of CSS counters
may be incremented by CSS rules. For example, CSS counters can be used to increment the
numbering of the headings automatically. In HTML, the <ol> tag is used to give the ordered numbers
to list items but CSS contains a counter to give order elements in some other fashion.
counter() or counters() function: The value of a counter can be displayed using either the
counter() or counters() function in a content property. These two functions basically used to
add the value of a counter to the element.
Initialization of the CSS Counter: To use the CSS counter property firstly it must be created with the
counter-reset property and the first step is resetting the counter. The counter by default initialized to
a value 0(zero) with the counter-reset property.
Syntax:
counter-reset: myCounter;
Incrementation and Use of CSS Counter: To increment the counter use the CSS counter-increment
property.
Syntax:
counter-increment: myCounter;
The counter() or counters() function in content is used to display the content in a particular order.
Syntax:
content: counter(myCounter);
51. What is meant by universal selector?
The * selector in CSS is used to select all the elements in an HTML document. It also selects all
elements which are inside under another element. It is also called the universal selector.
Syntax:
*{
// CSS property
}
Responsive Web Design comprises two words i.e., responsive and web design. Responsive means to
respond and web design means to design a website. Therefore, responsive web design generally
means the website that responds to or resizes or adjusts itself depending upon the screen size it is
being seen through. It automatically adjusts to fit the user’s screen whether it’s desktop, laptop,
mobile, tablet, etc. It only uses one layout for a web page and it can be done either using CSS and
HTML or CSS3 and HTML5.
Id selector(“#”): The id selector selects the id attribute of an HTML element to select a specific
element. An id is always unique within the page so it is chosen to select a single, unique element. It is
written with the hash character (#), followed by the id of the element.
Syntax:
#element_id_name{
// CSS properties
}
Class Selector(“.”): The class selector selects HTML elements with a specific class attribute. It is used
with a period character “.” (full stop symbol) followed by the class name.
Syntax:
.element_class_name{
// CSS properties
}
Each elements can contain more that one “.” selector means Each element can contain only
Class “.” Id “#”
The “.” selectors are not unique, same selectors can applicable
on multiple elements, if the HTML elements holds the same
class property like a list of elements can contains the same
class.
Pagination is the process of dividing the document into pages and providing them with numbers.
Types of Pagination: There are many types of pagination in CSS. Some of them are given below:
1. Simple Pagination
5. Bordered Pagination
7. Centered Pagination
9. Pagination Size
Syntax:
.pagination {
display:type
}
.pagination body {
color:colorname
decoration:type
}
Attributes:
below: to create a reflection below the original image
Example:
HTML
<!DOCTYPE html>
<html>
<head>
<style>
img {
-webkit-box-reflect: right;
</style>
</head>
<body>
<img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20210322123023/gfg2.png">
</body>
</html>
Output:
56. How can we create multiple columns of text-like newspapers using CSS?
The multiple columns are used to create column layouts on the web pages. There are many column
properties in CSS which are listed below:
column-count
column-gap
column-rule-style
column-rule-width
column-rule-color
column-rule
column-span
column-width
Example:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Column-count property</title>
<style>
.geeks_content {
-webkit-column-count: 3;
-moz-column-count: 3;
column-count: 3;
padding-top:35px;
text-align:justify;
.gfg {
text-align:center;
font-size:40px;
font-weight:bold;
color:green;
.geeks {
text-align:center;
</style>
</head>
<body>
<div class="gfg">GeeksforGeeks</div>
<div class="geeks_content">
</div>
</body>
</html>
Output:
The approach of this article is to add a shadow using the text-shadow property in CSS. This property
accepts a list of a comma-separated list of shadows to be applied to the text. The default value of
the text-shadow property is “none”.
Syntax:
The !important property in CSS is used to provide more weight (importance) than normal property.
In CSS, the !important means that “this is important”, ignore all the subsequent rules, and apply !
important rule and the !important keyword must be placed at the end of the line, immediately
before the semicolon.
In other words, it adds importance to all the sub-properties that the shorthand property
represents.
In normal use, a rule defined in an external style sheet which is overruled by a style defined
in the head of the document, which in turn, is overruled by an inline style within the element
itself (assuming equal specificity of the selectors).
Defining a rule with the !important attribute that discards the normal concerns as regards
the later rule overriding the earlier ones.
So, it is used for overriding the styles that are previously declared in other style sources, in
order to achieve a certain design.
Syntax:
element {
color: blue !important;
font-size: 14px !important;
...
}
When more than one set of CSS rules applies to the same element, the browser will have to decide
which specific set will be applied to the element. The rules the browser follows are collectively
called Specificity
CSS style applied by referencing external stylesheet has the lowest precedence and is
overridden by Internal and inline CSS.
Inline CSS has the highest priority and overrides all other selectors.
3. Classes, pseudo-classes, and attributes: Classes, pseudo-classes, and attributes have come
next.
4. Elements and pseudo-elements: Elements and pseudo-elements have the lowest priority.
The CSS Attribute Selector is used to select an element with some specific attribute or attribute
value. It is an excellent way to style the HTML elements by grouping them based on some specific
attributes and the attribute selector will select those elements with similar attributes.
There are several types of attribute selectors which are discussed below:
[attribute] Selector: This type of attribute selector is used to select all the elements that
have the specified attribute and applies the CSS property to that attribute. For example, the
selector [class] will select all the elements with the style attribute.
[attribute = “value”] Selector: This selector is used to select all the elements whose attribute
has the value exactly the same as the specified value.
[attribute~=”value”] Selector: This selector is used to select all the elements whose attribute
value is a list of space-separated values, one of which is exactly equal to the specified value.
[attribute|=”value”] Selector: This selector is used to select all the elements whose attribute
has a hyphen-separated list of values beginning with the specified value. The value has to be
a whole word either alone or followed by a hyphen.
[attribute^=”value”] Selector: This selector is used to select all the elements whose attribute
value begins with the specified value. The value doesn’t need to be a whole word.
[attribute$=”value”] Selector: This selector is used to select all the elements whose attribute
value ends with the specified value. The value doesn’t need to be a whole word.
[attribute*=”value”] Selector: This selector selects all the elements whose attribute value
contains the specified value present anywhere. The value doesn’t need to be a whole word.
Basic CSS Questions
o Answer: CSS (Cascading Style Sheets) is a stylesheet language used for describing the
presentation of a document written in HTML or XML. Its primary purpose is to
control the layout, colors, fonts, and overall aesthetics of web pages. CSS enables
developers to separate content from design, making it easier to maintain and update
websites. By using CSS, you can apply styles to multiple pages or elements
consistently.
o Answer: There are three main ways to apply CSS to a web page:
Inline CSS: CSS rules are applied directly within an HTML element using the
style attribute. This method is not recommended for larger projects due to
maintenance issues.
html
Copy code
Internal CSS: CSS rules are defined within a <style> tag in the <head> section
of an HTML document. This method is useful for single-page websites.
html
Copy code
<style>
h1 { color: blue; }
</style>
External CSS: CSS rules are written in a separate .css file and linked to the
HTML document using a <link> tag. This is the most efficient method for
larger websites as it promotes reusability and maintainability.
html
Copy code
o Answer:
Class Selectors: Denoted with a period (.), class selectors can be applied to
multiple elements throughout a document. This allows for the same styling
to be reused across different elements.
css
Copy code
.classname {
color: red;
ID Selectors: Denoted with a hash (#), ID selectors are unique and should
only be applied to one element per page. This ensures that the styles applied
to an ID are specific and do not conflict with other elements.
css
Copy code
#idname {
color: blue;
4. What are CSS units? Explain the difference between absolute and relative units.
o Answer: CSS units are used to define lengths and sizes in CSS. They can be
categorized into:
Absolute Units: These units have a fixed size and do not change regardless of
the context. Examples include:
px (pixels)
cm (centimeters)
in (inches)
Relative Units: These units are relative to other elements, making them
more flexible and responsive. Examples include:
em: Relative to the font-size of the element (1em = font size of the
element).
Example: Using em or rem can help create responsive designs that adapt to
user settings.
o Answer: The CSS box model describes how elements are structured and how their
sizes are calculated. It consists of the following components:
Content: The innermost area where text and images are displayed. The size
of this area is controlled by the width and height properties.
Padding: The space between the content and the border. Padding is
transparent and can be set for each side (top, right, bottom, left) individually
or as a shorthand property.
Border: The area surrounding the padding (if any). Borders can be styled
with various widths, colors, and styles (solid, dashed, etc.).
lua
Copy code
Answer:
Example:
css
Copy code
.box {
o Padding: Padding is the space between the content of the element and its border. It
increases the size of the element without affecting its outer layout. Padding can also
be set individually for each side.
Example:
css
Copy code
.box {
Answer:
o Pseudo-Classes: These are keywords added to selectors that specify a special state of
the selected elements. They allow you to style elements based on their state, such as
when a user hovers over them or when they are focused.
Example:
css
Copy code
a:hover {
input:focus {
o Pseudo-Elements: These are used to style specific parts of an element. They allow
you to apply styles to certain parts of an element, such as the first line or
before/after the content.
Example:
css
Copy code
p::first-line {
}
div::after {
Answer:
o Flexbox (Flexible Box Layout) is a CSS layout model that provides a more efficient
way to layout, align, and distribute space among items within a container. It allows
for responsive design by giving items the ability to grow and shrink according to the
available space.
o Key Properties:
flex-direction — Defines the direction of the flex items (row, column, row-
reverse, column-reverse).
justify-content — Aligns flex items along the main axis (e.g., space-between,
center, flex-start).
align-items — Aligns flex items along the cross axis (e.g., stretch, center, flex-
start).
Example:
css
Copy code
.container {
display: flex;
What are CSS Grid Layouts? How do they differ from Flexbox?
Answer:
o CSS Grid Layout is a two-dimensional layout system that allows you to create
complex layouts by defining rows and columns within a grid. This makes it suitable
for building web applications with intricate designs.
Dimensions: Grid allows for both rows and columns (2D), while Flexbox is
primarily one-dimensional (1D) and can only arrange items in a row or a
column.
Use Cases: Grid is ideal for layouts with both horizontal and vertical
alignment, whereas Flexbox is better suited for aligning items in a single
direction.
Example of Grid:
css
Copy code
.grid-container {
display: grid;
Answer:
o Specificity is a set of rules that determine which CSS rule applies when multiple rules
could affect the same element. Specificity is calculated based on the types of
selectors used in a rule. The hierarchy of specificity is:
1. Inline styles (e.g., styles set directly in the HTML element) have the highest
specificity.
2. ID selectors (#id) have higher specificity than class selectors (.class) and
pseudo-classes.
3. Class selectors, attributes selectors, and pseudo-classes have the same level
of specificity.
A style defined by an inline style will take precedence over a style defined by
a class selector:
html
Copy code
<style>
</style>
o Answer:
display: none: This property removes the element from the document flow
entirely. The element will not take up any space in the layout, and other
elements will move in to fill the space. It is as if the element does not exist in
the HTML structure.
Example:
css
Copy code
.hidden {
visibility: hidden: This property makes the element invisible but still
occupies space in the layout. Other elements will not adjust their positions
as the element is still considered part of the document flow.
Example:
css
Copy code
.invisible {
o Answer:
Example:
css
Copy code
.container {
Example:
css
Copy code
.box {
o Answer:
CSS Transitions: These allow you to change property values smoothly (over a
specified duration) when a state change occurs, such as hovering over an
element. You define the initial and final state, and the transition handles the
intermediate steps.
Example:
css
Copy code
.box {
background-color: blue;
.box:hover {
CSS Animations: These are more complex than transitions and allow you to
create keyframes that define styles at various points in the animation
timeline. You can create animations that repeat, have delays, and more.
Example:
css
Copy code
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
.fade {
o Answer:
css
Copy code
*{
margin: 0;
padding: 0;
box-sizing: border-box; /* Include padding and border in element's total width and height */
o Answer:
The z-index property determines the stacking order of elements that
overlap. Elements with a higher z-index value are placed above those with a
lower value.
Usage:
Example:
css
Copy code
.layer1 {
position: absolute;
.layer2 {
position: absolute;
Here's a simple example of a responsive navigation bar using HTML and CSS:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
body {
margin: 0;
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
background-color: #333;
.navbar a {
color: white;
text-decoration: none;
.navbar a:hover {
background-color: #575757;
.toggle-button {
display: none;
flex-direction: column;
cursor: pointer;
.toggle-button div {
width: 25px;
height: 3px;
background-color: white;
margin: 3px 0;
transition: 0.3s;
.navbar a {
display: none;
.navbar a.active {
display: block;
.toggle-button {
display: flex;
.navbar {
flex-direction: column;
</style>
</head>
<body>
<div class="navbar">
<div></div>
<div></div>
<div></div>
</div>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Contact</a>
</div>
<script>
function toggleMenu() {
</script>
</body>
</html>
You can center a block element both horizontally and vertically using Flexbox or Grid. Here’s how to
do it with both methods:
Using Flexbox:
css
Copy code
.container {
display: flex;
.block {
width: 200px;
height: 100px;
background-color: lightblue;
Using Grid:
css
Copy code
.container {
display: grid;
.block {
width: 200px;
height: 100px;
background-color: lightgreen;
html
Copy code
<style>
.button {
color: white;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
.button:hover {
}
</style>
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image Gallery</title>
<style>
.gallery {
display: grid;
gap: 10px;
.gallery img {
width: 100%;
border-radius: 5px;
</style>
</head>
<body>
<div class="gallery">
</div>
</body>
</html>
To handle browser compatibility issues, you can use the following techniques:
1. Vendor Prefixes: Use vendor prefixes for properties that may not be fully supported across
all browsers. For example:
css
Copy code
.example {
2. Feature Queries: Use @supports to apply styles only if a certain feature is supported by the
browser:
css
Copy code
.grid-container {
display: grid;
3. Fallback Styles: Provide fallback styles for browsers that do not support newer features. For
example:
css
Copy code
.example {
BEM (Block Element Modifier): Use a naming convention like BEM to create a clear
structure. For example, .block__element--modifier helps in understanding the relationship
between the components.
css
Copy code
.button {
.button--primary {
Meaningful Names: Use descriptive class names that reflect the purpose of the style, making
it easier for others (and yourself) to understand later.
b. Modular CSS
Component-Based Approach: Write CSS that targets specific components, allowing for better
reusability and isolation of styles.
css
Copy code
/* Button Component */
.button {
border: none;
border-radius: 4px;
}
Separation of Concerns: Keep your styles organized by component or feature rather than by
type (e.g., layout, typography). This improves maintainability.
Separation of HTML and CSS: Inline styles make it difficult to maintain and override styles
later. Use classes and stylesheets instead.
html
Copy code
Reduce File Size: Minification removes whitespace, comments, and unnecessary characters
from CSS files, reducing their size and improving load times.
bash
Copy code
Fewer HTTP Requests: Combine multiple CSS files into a single file to reduce the number of
HTTP requests, which can enhance loading performance.
Single Entry Point: Using @import can lead to additional HTTP requests and delayed
rendering. Instead, use a single CSS file for styles or use build tools to bundle stylesheets.
css
Copy code
/* Avoid this */
@import url('styles1.css');
@import url('styles2.css');
/* Prefer direct linking in HTML */
3. Critical CSS
Critical CSS refers to the CSS rules required for rendering above-the-fold content (the visible part of a
webpage before scrolling). By inlining critical CSS in the <head> of your HTML document, you can
reduce render-blocking requests and improve page load speed.
html
Copy code
<head>
<style>
/* Critical CSS */
body {
margin: 0;
.hero {
background-color: #f00;
color: #fff;
height: 100vh;
</style>
</head>
To implement critical CSS effectively, tools like Critical or Penthouse can be used to extract the
necessary styles from your stylesheets.
CSS Variables (custom properties) allow you to define reusable values in your stylesheets. They can
be changed dynamically and help in maintaining themes or style changes across your application.
css
Copy code
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
}
.button {
background-color: var(--primary-color);
color: white;
.button--secondary {
background-color: var(--secondary-color);
Using CSS variables makes it easy to update styles across a site without needing to change multiple
rules.
Readable Text: Ensure text color contrasts sufficiently with background color. Use tools like
the WebAIM Color Contrast Checker to evaluate your color schemes.
Focus Styles: Provide visible focus indicators for interactive elements (links, buttons) to help
keyboard users navigate easily.
css
Copy code
a:focus, button:focus {
Use HTML Elements Semantically: Ensure that elements are used according to their
semantic meaning (e.g., <nav> for navigation, <header> for header content). This helps
assistive technologies interpret your page correctly.
Ensuring cross-browser compatibility, validating CSS, and handling deprecated properties are crucial
aspects of modern web development. Here’s a detailed overview of each topic:
a. CSS Resets
Use CSS Resets: Resets normalize default browser styling to ensure consistency across
browsers. Popular reset stylesheets include Eric Meyer's Reset CSS and Normalize.css. These
styles help reduce browser inconsistencies in things like default line heights, margins, and
font sizes.
css
Copy code
*{
margin: 0;
padding: 0;
box-sizing: border-box;
Manual Testing: Regularly test your website in various browsers (Chrome, Firefox, Safari,
Edge, etc.) and on different devices to identify issues. Use tools like BrowserStack or Sauce
Labs for cross-browser testing.
Stay Updated: Familiarize yourself with CSS specifications and avoid using deprecated
properties. Check resources like MDN Web Docs for current property status.
css
Copy code
/* Deprecated */
/* Recommended */
font-weight: bold;
Several tools can help validate your CSS and ensure that it follows standards:
o Usage: You can input your CSS directly or provide a URL to your stylesheet. Visit the
W3C CSS Validator to access it.
Developer Tools: All modern browsers come with built-in developer tools that allow you to
inspect CSS rules, view warnings, and check for deprecated properties.
Handling deprecated properties is important for maintaining compatibility and ensuring future-proof
code:
Follow Standards: Regularly check the latest CSS specifications and best practices to stay
informed about which properties are deprecated or modified. Websites like MDN Web Docs
and CSS-Tricks are excellent resources.
css
Copy code
.example {
By implementing these strategies, you can effectively manage cross-browser compatibility, validate
your CSS, and handle deprecated properties, leading to a more robust and user-friendly web
experience.
The architecture of CSS (Cascading Style Sheets) refers to its design principles, structure, and the
methodologies used to organize and implement styles on web pages. Understanding CSS architecture
is crucial for maintaining scalable, efficient, and maintainable stylesheets, especially in large projects.
Here’s a detailed breakdown of the architecture of CSS:
Selectors: These are patterns used to select the elements you want to style. Selectors can be:
o Type Selectors: Target all elements of a specific type (e.g., div, p).
o Class Selectors: Target elements with a specific class attribute (e.g., .classname).
Properties and Values: These define how selected elements should be styled. Properties are
the characteristics (e.g., color, font-size), and values are the settings for those characteristics
(e.g., red, 16px).
CSS Declaration Block: A declaration block contains a list of declarations enclosed in curly
braces. Each declaration consists of a property and a value, separated by a colon, and
multiple declarations are separated by semicolons.
css
Copy code
.example {
color: blue;
font-size: 14px;
CSS stands for Cascading Style Sheets, which means styles can cascade from one source to
another.
Cascading Order: When multiple CSS rules apply to the same element, the browser
determines which rule takes precedence based on:
o Importance: Inline styles (using the style attribute) take the highest precedence,
followed by internal styles (in a <style> tag), and finally external styles (from a linked
stylesheet).
o Specificity: Specificity is calculated based on the type of selectors used. The more
specific a selector is, the higher its precedence.
ID selectors: 100
3. CSS Modules
CSS Modules allow for better organization and encapsulation of styles. Each CSS module is
scoped locally by default, which avoids conflicts between styles in different components.
4. CSS Preprocessors
Tools like Sass, LESS, and Stylus are preprocessors that extend CSS with additional features:
o Nesting: Write CSS rules nested within other rules for better readability.
o Mixins: Create reusable sets of CSS properties that can be included in other
selectors.
Preprocessors help maintain a clean structure and improve the maintainability of large
stylesheets.
5. CSS Frameworks
CSS frameworks like Bootstrap, Tailwind CSS, and Foundation provide pre-defined styles and
components to streamline development. They promote consistency and can accelerate the
design process.
Frameworks often come with responsive design principles, grid systems, and utility classes to
facilitate development.
Responsive design is essential in modern web development, and CSS architecture supports
this through:
o Media Queries: Allow styles to adapt based on device characteristics (e.g., screen
size, resolution).
o Flexbox and Grid Layouts: Enable flexible layouts that adjust to various screen sizes.
o Fluid Typography and Spacing: Use relative units (like em, rem, %) for responsive
typography and spacing.
Organize Stylesheets: Structure your CSS files logically, grouping related styles together and
using comments to clarify sections.
Use Naming Conventions: Adopt conventions like BEM (Block, Element, Modifier) to create
meaningful class names that indicate their function and relationship.
css
Copy code
Avoid Inline Styles: Use external or internal stylesheets for maintainability and to leverage
the cascading nature of CSS.
8. Performance Optimization
Minification: Remove unnecessary characters (like spaces and comments) from CSS files to
reduce file size and improve loading speed.
Critical CSS: Load essential styles inline in the <head> to improve rendering speed for above-
the-fold content.
Combine CSS Files: Minimize HTTP requests by combining multiple CSS files into one where
possible.
Conclusion
The architecture of CSS is built around its core principles of cascading, specificity, and modularity. By
following best practices and utilizing modern tools and frameworks, developers can create scalable,
maintainable, and performant stylesheets that enhance the user experience on web applications.
Understanding this architecture is key to being an effective front-end developer.
4o mini