Complete CSS Tutorial: Core Concepts in a Nutshell
Sep 29, 2026 10 Min Read 10164 Views
(Last Updated)
Every website you admire, from a clean portfolio to a busy online store, gets its look from CSS. It decides the colors, the spacing, the fonts, and how a page rearranges itself on your phone.
This guide skips the long theory and covers the parts of CSS you will use most often. Go through the sections in order and try each example yourself, and you will have a solid base to build on.
Table of contents
- TL;DR Summary
- What is CSS?
- Ways to Add CSS (Inline, Internal, External)
- Inline CSS
- Internal CSS
- External CSS
- Which One Should You Use?
- CSS Syntax and Selectors
- Element Selector
- Class Selector
- ID Selector
- Grouping and Descendant Selectors
- Pseudo-class Selectors
- Which Rule Wins?
- Colors and Backgrounds
- Color Formats
- Background Color and Image
- Gradients
- Text and Font Styling
- px, em, and rem
- Using a Web Font
- The Box Model (Margin, Padding, Border)
- Setting Individual Sides
- The Width Problem and box-sizing
- A Note on Margins
- Display and Positioning
- The Display Property
- The Position Property
- Controlling Overlap with z-index
- Flexbox Basics
- Main Axis and Cross Axis
- Changing Direction and Wrapping
- Common justify-content Values
- Making Items Share Space
- Centering Something Perfectly
- CSS Grid Basics
- Mixing Column Sizes
- Spanning Multiple Columns
- A Responsive Grid Without Media Queries
- Flexbox or Grid?
- Responsive Design with Media Queries
- The Viewport Meta Tag
- Writing a Media Query
- Mobile-First vs Desktop-First
- Common Breakpoints
- Flexible Images and Units
- CSS Tutorial Quick Reference: Concepts and Learning Time
- FAQs
- What is CSS used for?
- What are the three ways to add CSS to HTML?
- How long does it take to learn CSS basics?
- What is the difference between Flexbox and CSS Grid?
- What is the box model in CSS?
TL;DR Summary
- This CSS Tutorial covers the core building blocks: what CSS is, how to add it to a page, and how selectors and syntax work.
- You will see how to style colors, backgrounds, text, and fonts with short, practical examples.
- The box model, display, and positioning sections explain how elements take up space and where they sit on a page.
- Flexbox and CSS Grid are introduced at a basic level so you can understand how modern layouts are built.
- The final section shows how media queries help a page adjust to different screen sizes.
CSS was first proposed by Håkon Wium Lie in 1994 to make it easier to style and control the appearance of web pages.
What is CSS?

CSS (Cascading Style Sheets) is the language that controls how a web page appears. HTML builds the structure of a page, such as headings, paragraphs, images, and buttons, and CSS decides how those elements appear on screen, including their colors, fonts, spacing, and layout.
The word “cascading” refers to how the browser settles conflicts. When several rules target the same element, the browser picks a winner based on order, specificity, and importance. Generally, a later rule overrides an earlier one, and a more specific selector beats a general one.
In web development, CSS works alongside HTML and JavaScript. HTML holds the content, CSS handles the design, and JavaScript adds behavior. Keeping design in CSS also means you can change an entire site’s look by editing one file instead of touching every page.
Key features of CSS:
- Separates design from content
- Reuses one stylesheet across many pages
- Controls colors, fonts, and spacing
- Builds layouts for different screen sizes
- Lets rules cascade so styles stay predictable
Also Read: A Complete Guide to HTML and CSS for Beginners
Ready to build a career in software? HCL GUVI’s Software and AI Engineer Programme offers Full Stack and Backend tracks, 130+ hours of live classes, real-world projects, one-on-one mock interviews, and an IITM Pravartak certification. Modules are available in English, Tamil, Hindi, and Telugu. Explore the programme and apply today!
Ways to Add CSS (Inline, Internal, External)
There are three ways to connect CSS to an HTML page. All three produce the same visual result, but they differ in how easy they are to manage as a project grows.
1. Inline CSS
Inline CSS is written directly inside an HTML tag using the style attribute.
<h1 style="color: blue; font-size: 32px;">Hello, CSS</h1>
styleis an HTML attribute that accepts CSS declarations.color: blue;changes the text color of this one heading.font-size: 32px;sets the text size to 32 pixels.- Only this single
<h1>is affected. No other heading on the page changes.
Inline styles are handy for a quick test, but they mix design into your HTML and cannot be reused. Repeating them across many elements gets messy fast.
2. Internal CSS
Internal CSS goes inside a <style> tag, placed in the <head> of the HTML document.
<head>
<style>
p {
color: darkgreen;
line-height: 1.6;
}
</style>
</head>
- The
<style>tag tells the browser that everything inside it is CSS. pis a selector, so the rules apply to every paragraph on this page.color: darkgreen;changes the text color of all paragraphs.line-height: 1.6;adds comfortable spacing between lines.
This works well for a single page, but the styles stay locked inside that one file. A second page would need the same code copied into it.
3. External CSS
External CSS lives in a separate .css file, which you connect to the HTML with a <link> tag.
<head>
<link rel="stylesheet" href="styles.css">
</head>
/* styles.css */
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
}
rel="stylesheet"tells the browser the linked file is a stylesheet.href="styles.css"is the path to the file. If the file sits in a folder, the path changes, for examplecss/styles.css.- Inside
styles.css, thebodyrules apply to the whole visible page. - Any page that includes the same
<link>tag gets the same styling.
External CSS is the standard choice for real websites. One file can control the design of an entire site, and browsers can store it after the first visit, which helps pages load faster.
Which One Should You Use?
Use external CSS for almost everything. Internal CSS is fine for small demos or single-page experiments, and inline CSS is best kept for quick tests or special cases.
If the same property is set in more than one place, the browser follows the cascade. Inline styles generally win over internal and external ones, and between internal and external, the rule that appears later in the page wins when the selectors are equally specific.
Optional Read: Types of CSS
CSS Syntax and Selectors
Every CSS rule follows the same pattern. Once you can read one rule, you can read them all.
h2 {
color: crimson;
margin-bottom: 12px;
}
h2is the selector. It chooses which elements the rule applies to.- The curly braces
{ }wrap the declaration block. colorandmargin-bottomare properties, the things you want to change.crimsonand12pxare values, what you want those properties to become.- Each declaration ends with a semicolon.
A property and its value together are called a declaration. A selector with its declaration block is called a rule.
1. Element Selector
An element selector targets every instance of an HTML tag.
p {
font-size: 18px;
}
- Every
<p>on the page now has 18px text.
2. Class Selector
A class selector targets any element that has a matching class attribute. It starts with a dot.
<p class="highlight">Important note</p>
<p>Regular note</p>
.highlight {
background-color: yellow;
}
.highlightmatches elements withclass="highlight".- Only the first paragraph gets the yellow background.
- You can reuse the same class on as many elements as you like.
3. ID Selector
An ID selector targets one specific element. It starts with a hash symbol.
<div id="main-header">Welcome</div>
#main-header {
text-align: center;
}
#main-headermatches the element withid="main-header".- An ID should be used only once per page.
- In practice, classes are preferred for styling because they are easier to reuse.
4. Grouping and Descendant Selectors
You can style several selectors at once by separating them with commas. You can also target elements inside other elements by separating selectors with a space.
h1, h2, h3 {
font-family: Georgia, serif;
}
nav a {
text-decoration: none;
}
- The first rule applies the same font to all three heading levels.
nav amatches only links that sit inside a<nav>element.- Links outside the navigation keep their default underline.
5. Pseudo-class Selectors
A pseudo-class applies styles when an element is in a particular state.
button:hover {
background-color: black;
color: white;
}
:hoveractivates when the mouse pointer is over the element.- The button turns black with white text only while it is hovered.
Which Rule Wins?
When two rules conflict, the browser looks at specificity. An ID selector is stronger than a class selector, and a class selector is stronger than an element selector. If two rules have the same specificity, the later one wins.
Colors and Backgrounds
Color is one of the first things you will change in any project. CSS gives you several ways to write colors, and you can use them for text, borders, and backgrounds.
1. Color Formats
.box-one {
color: tomato;
}
.box-two {
color: #2a9d8f;
}
.box-three {
color: rgb(38, 70, 83);
}
.box-four {
color: rgba(38, 70, 83, 0.5);
}
.box-five {
color: hsl(200, 60%, 40%);
}
tomatois a named color. CSS has around 140 of these, which are easy to read but limited.#2a9d8fis a HEX value. The pairs of characters represent red, green, and blue.rgb(38, 70, 83)sets the same three channels using numbers from 0 to 255.rgba(38, 70, 83, 0.5)adds an alpha value for transparency.0is fully transparent and1is fully solid.hsl(200, 60%, 40%)describes color by hue (0 to 360 on the color wheel), saturation, and lightness. It is often the easiest format for making a lighter or darker version of a color.
2. Background Color and Image
.hero {
background-color: #1d3557;
background-image: url("hero.jpg");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
color: white;
}
background-colorsets a solid color, which also acts as a fallback if the image fails to load.background-image: url("hero.jpg");places an image behind the content.background-size: cover;scales the image to fill the whole element, cropping the edges if needed.background-position: center;keeps the middle of the image in view.background-repeat: no-repeat;stops the image from tiling.color: white;keeps the text readable on top of a dark background.
3. Gradients
A gradient is treated as a background image, so it goes in background or background-image.
.banner {
background: linear-gradient(to right, #ff9a9e, #fad0c4);
}
linear-gradientblends from one color to another in a straight line.to rightsets the direction, starting on the left and ending on the right.- The two colors after it are the start and end points of the blend.
Always check that your text color has enough contrast against the background. Light gray text on a white background looks stylish in a mockup but is hard for many people to read.
Text and Font Styling
Most web pages are mainly text, so a few well-chosen text properties can change how a page feels.
body {
font-family: "Segoe UI", Arial, sans-serif;
font-size: 16px;
line-height: 1.7;
color: #333;
}
h1 {
font-size: 2.5rem;
font-weight: 700;
text-align: center;
text-transform: uppercase;
letter-spacing: 2px;
}
a {
text-decoration: none;
}
font-familylists fonts in order of preference. If the first is not available on the visitor’s device, the browser tries the next, and the last entry is a generic fallback likesans-serif.font-size: 16px;sets the base text size for the page.line-height: 1.7;sets the space between lines to 1.7 times the font size. A value between 1.5 and 1.8 usually reads well for body text.color: #333;uses a dark gray, which is softer on the eyes than pure black.font-size: 2.5rem;sizes the heading relative to the root font size, so it becomes 40px when the base is 16px.font-weight: 700;makes the heading bold. Values run from 100 (thin) to 900 (heavy).text-align: center;centers the heading horizontally.text-transform: uppercase;displays the text in capital letters without changing the HTML.letter-spacing: 2px;adds a little space between each character.text-decoration: none;removes the default underline from links.
1. px, em, and rem
Pixels (px) are fixed. em is relative to the font size of the element’s parent, and rem is relative to the font size set on the root of the page.
For font sizes, rem is a solid choice because it respects the size a user has chosen in their browser settings and keeps spacing consistent across the site.
2. Using a Web Font
If you want a font that visitors may not have installed, you can load one from a service such as Google Fonts.
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet">
body {
font-family: "Poppins", sans-serif;
}
- The
<link>tag downloads the Poppins font in weights 400 (regular) and 600 (semi-bold). display=swapshows fallback text right away and swaps in the web font once it loads.- The CSS rule then applies it, with
sans-serifas the backup.
The Box Model (Margin, Padding, Border)
Every element on a web page is a rectangular box. The box model describes how the box is built, and it is behind most of the spacing problems beginners run into.
A box is made of four layers, from the inside out:
- Content: the text, image, or other material inside the element.
- Padding: the space between the content and the border, inside the element.
- Border: a line that wraps around the padding and content.
- Margin: space outside the border that pushes other elements away.
.card {
width: 300px;
padding: 20px;
border: 2px solid #333;
margin: 30px;
}
width: 300px;sets the width of the content area.padding: 20px;adds 20px of space on all four sides inside the box.border: 2px solid #333;draws a 2px solid dark gray line. A border needs a width, a style, and a color.margin: 30px;leaves 30px of empty space around the outside of the box.
1. Setting Individual Sides
You can set each side separately or use shorthand.
.card {
padding: 10px 20px;
margin: 10px 20px 30px 40px;
margin-bottom: 50px;
}
padding: 10px 20px;uses two values. The first is top and bottom, and the second is left and right.margin: 10px 20px 30px 40px;uses four values, in the order top, right, bottom, left.margin-bottom: 50px;overrides only the bottom margin from the line above it.
2. The Width Problem and box-sizing
By default, width only measures the content area. Padding and border are added on top. So the .card above ends up 344px wide in total: 300 for content, 40 for padding, and 4 for border.
That can break layouts, so most developers change this behavior with box-sizing.
* {
box-sizing: border-box;
}
*targets every element on the page.border-boxmakeswidthinclude the content, padding, and border together.- With this rule, a 300px wide
.cardis exactly 300px wide on screen, no matter how much padding it has.
Adding this rule at the top of almost every stylesheet is standard practice.
3. A Note on Margins
Vertical margins between two stacked elements can merge into one. If one paragraph has margin-bottom: 30px and the next has margin-top: 20px, the gap between them is 30px, not 50px. The larger value wins. This is called margin collapsing, and it applies only to vertical margins.
Display and Positioning
Two properties control how elements are placed on a page: display decides how an element behaves in the flow of the page, and position decides whether it can be moved out of that flow.
1. The Display Property
.block-item {
display: block;
}
.inline-item {
display: inline;
}
.inline-block-item {
display: inline-block;
width: 120px;
height: 60px;
}
.hidden-item {
display: none;
}
blockelements start on a new line and stretch across the full width available.<div>,<p>, and headings are block by default.inlineelements sit within a line of text and take only as much width as their content needs.<span>and<a>are inline by default. Width and height settings have no effect on them.inline-blocksits in a line like an inline element, but accepts width, height, and vertical margins like a block element.noneremoves the element from the page entirely, and it takes up no space.
2. The Position Property
The position property has five values. Offset properties like top, right, bottom, and left only work when the position is anything other than static.
.parent {
position: relative;
height: 200px;
background-color: #e0e0e0;
}
.badge {
position: absolute;
top: 10px;
right: 10px;
}
.help-button {
position: fixed;
bottom: 20px;
right: 20px;
}
.section-title {
position: sticky;
top: 0;
}
staticis the default. The element follows the normal flow, and offsets do nothing.relativekeeps the element in its normal place but lets you nudge it with offsets. It also makes the element a reference point for any absolutely positioned children..badgeusesabsolute, so it is removed from the normal flow and placed 10px from the top and right edges of.parent, its nearest positioned ancestor..help-buttonusesfixed, so it stays 20px from the bottom right corner of the browser window, even while the page scrolls..section-titleusessticky, so it scrolls normally until it reaches the top of the screen, then stays there until its container ends.
3. Controlling Overlap with z-index
When positioned elements overlap, z-index decides which one appears on top.
.modal {
position: fixed;
z-index: 100;
}
- A higher
z-indexsits above a lower one. - It only works on elements that have a position value other than
static.
Flexbox Basics
Flexbox is a layout system for arranging items in a single row or a single column. It removes most of the older tricks people used for centering and spacing elements.
To use it, you set display: flex on a parent element, called the flex container. Its direct children become flex items.
<div class="menu">
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Contact</a>
</div>
.menu {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
}
display: flex;turns.menuinto a flex container, and the three links line up in a row.justify-content: space-between;spreads the items along the main axis, with the first at the start and the last at the end.align-items: center;centers the items on the cross axis, which is vertical when the direction is a row.gap: 16px;adds 16px of space between each item without needing margins.
1. Main Axis and Cross Axis
Flexbox works with two directions. The main axis is the direction items flow in, and the cross axis runs perpendicular to it. By default the main axis is horizontal.
justify-content controls alignment on the main axis, while align-items controls the cross axis.
2. Changing Direction and Wrapping
.sidebar {
display: flex;
flex-direction: column;
}
.gallery {
display: flex;
flex-wrap: wrap;
}
flex-direction: column;stacks items vertically, so the main axis becomes vertical.flex-wrap: wrap;lets items move to a new line when there isn’t enough room, instead of shrinking to fit.
3. Common justify-content Values
flex-startplaces items at the beginning.centerplaces items in the middle.flex-endplaces items at the end.space-betweenputs equal space between items, with none at the edges.space-aroundputs equal space around each item.
4. Making Items Share Space
.column {
flex: 1;
}
flex: 1;tells an item to grow and take an equal share of the available space.- If three columns all have
flex: 1, they end up the same width.
5. Centering Something Perfectly
One of the most common uses of flexbox is centering content both horizontally and vertically.
.center-box {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
justify-content: center;centers items horizontally.align-items: center;centers them vertically.height: 100vh;makes the container as tall as the browser window, which gives the vertical centering room to work.
CSS Grid Basics
CSS Grid is a layout system for arranging items in rows and columns at the same time. Flexbox handles one direction at a time, while Grid handles both, making it better suited to full-page layouts and card sections.
<div class="products">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
<div>Item 5</div>
<div>Item 6</div>
</div>
.products {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
display: grid;turns.productsinto a grid container.grid-template-columns: repeat(3, 1fr);creates three columns of equal width.1frstands for one fraction of the available space, so three1frcolumns each take a third.gap: 20px;puts 20px of space between rows and columns.- The six items fill the grid automatically, producing two rows of three.
1. Mixing Column Sizes
Columns do not have to be equal.
.layout {
display: grid;
grid-template-columns: 250px 1fr;
gap: 24px;
}
- The first column is fixed at 250px, which works well for a sidebar.
- The second column,
1fr, takes all the remaining space.
2. Spanning Multiple Columns
An item can stretch across more than one column or row.
.featured {
grid-column: span 2;
}
grid-column: span 2;makes the item take up two columns instead of one.- The other items move around it to fill the grid.
3. A Responsive Grid Without Media Queries
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 20px;
}
minmax(220px, 1fr)sets each column to be at least 220px wide and lets it grow to share leftover space.auto-fitfits as many columns as the container allows.- On a wide screen you may get four columns, on a tablet two, and on a phone one, all from this single line.
Flexbox or Grid?
Use Flexbox when you are arranging items along one line, such as a navigation bar or a row of buttons.
Use Grid when you need control over rows and columns together, such as a photo gallery or a page layout. The two also work well together, with Grid shaping the page and Flexbox aligning items inside each cell.
Responsive Design with Media Queries
Responsive design means a page adjusts to the screen it is viewed on, whether that is a phone, a tablet, or a wide desktop monitor. It relies on three things: a viewport setting, flexible sizing, and media queries.
1. The Viewport Meta Tag
Before any CSS works properly on mobile, this tag needs to be in the <head> of your HTML.
<meta name="viewport" content="width=device-width, initial-scale=1.0">
width=device-widthtells the browser to match the page width to the screen width.initial-scale=1.0sets the starting zoom level to normal.- Without this tag, phones often show a shrunken desktop version of the page.
2. Writing a Media Query
A media query applies a block of CSS only when a condition is true, most often based on screen width.
.container {
display: flex;
flex-direction: column;
padding: 16px;
}
@media (min-width: 768px) {
.container {
flex-direction: row;
padding: 32px;
}
}
- The first rule is the default, so it applies to every screen size. Here the items stack in a column.
@media (min-width: 768px)means the rules inside apply only when the screen is 768px wide or larger.- Inside the query, the direction switches to
rowand the padding increases. - On a phone you see a stacked layout, and on a tablet or desktop the items sit side by side.
3. Mobile-First vs Desktop-First
The example above is mobile-first. You write styles for small screens first, then use min-width queries to add changes for larger ones. This approach usually leads to simpler CSS, because small screens tend to need fewer layout rules.
A desktop-first approach does the opposite, using max-width to override styles for smaller screens.
@media (max-width: 600px) {
.sidebar {
display: none;
}
}
- This hides the sidebar on screens 600px wide or smaller.
4. Common Breakpoints
There are no official breakpoints; the best ones are wherever your layout starts to look broken. These values are a common starting point:
480pxfor small phones768pxfor tablets1024pxfor small laptops1200pxfor larger desktop screens
5. Flexible Images and Units
Media queries work best alongside sizing that already adapts on its own.
img {
max-width: 100%;
height: auto;
}
.wrapper {
width: 90%;
max-width: 1100px;
margin: 0 auto;
}
max-width: 100%;stops an image from growing wider than its container.height: auto;keeps the image proportions correct as it scales..wrappertakes 90% of the screen width but never grows past 1100px.margin: 0 auto;centers the wrapper horizontally by splitting the leftover space equally on each side.
Testing matters as much as writing the code. Open your browser’s developer tools, switch on the device toolbar, and resize the window to see where your layout needs adjusting.
Also Read: Debugging CSS
CSS Tutorial Quick Reference: Concepts and Learning Time
This CSS Tutorial quick reference lists each core concept with the time it usually takes to learn, so you can plan your practice before you start:
| Concept | What It Covers | Difficulty Level | Time to Learn |
|---|---|---|---|
| Selectors | Targeting elements by tag, class, and ID | Easy | 20 minutes |
| Properties and Values | Setting how an element looks, such as color or font-size | Easy | 15 minutes |
| Specificity | Deciding which rule wins when styles conflict | Medium | 30 minutes |
| Color Formats | Names, HEX, RGB, and HSL values | Easy | 20 minutes |
| Margin and Padding | Space outside and inside an element | Easy | 25 minutes |
| Display Property | Block, inline, inline-block, and none | Easy | 20 minutes |
| Position Property | Static, relative, absolute, fixed, and sticky | Medium | 45 minutes |
| Flexbox | Aligning and spacing items in a row or column | Medium | 1 hour |
| CSS Grid | Placing items into rows and columns | Medium | 1 hour |
| Media Queries | Applying styles at different screen widths | Medium | 40 minutes |
FAQs
1. What is CSS used for?
CSS controls how a web page looks. It sets colors, fonts, spacing, and layout, while HTML provides the structure and content.
2. What are the three ways to add CSS to HTML?
Inline CSS goes inside a tag with the style attribute, internal CSS goes inside a <style> tag in the <head>, and external CSS lives in a separate .css file linked with a <link> tag. External CSS is the best choice for most websites.
3. How long does it take to learn CSS basics?
The core concepts in this CSS Tutorial add up to roughly 7 hours of focused practice. Getting comfortable with layouts and building pages on your own usually takes a few weeks of regular practice.
4. What is the difference between Flexbox and CSS Grid?
Flexbox arranges items in one direction, either a row or a column. Grid works with rows and columns together, so it suits full-page layouts and card sections better.
5. What is the box model in CSS?
The box model describes every element as a box made of four layers: content, padding, border, and margin. It determines an element’s total size and the space around it.



Did you enjoy this article?