css
css
CSS is a styling language used to control the layout and appearance of web pages. It allows
us to separate the styles/design from the structure of the web page.
CSS was introduced in 1994.
CSS Syntax
CSS syntax consists of a set of rules known as styles, which are applied to elements of the
web page. It consists of:
1. Selector → Defines which element(s) the style will be applied to.
2. Property → Specifies what aspect of the element's style will be changed.
3. Value → Defines the value for the given property.
Example:
p{
background-color: red;
}
p → Selector (targets all <p> elements)
background-color → Property (defines the background color)
red → Value (sets the background color to red)
Types of CSS
CSS can be applied to HTML elements in three ways:
1. Inline CSS
Defined directly within the HTML element using the style attribute.
Example:
<p style="color: blue;">This is an inline-styled paragraph.</p>
Advantage: Quick and easy for small changes.
Disadvantage: Hard to maintain if used frequently.
2. Internal CSS
Defined within the <style> element inside the <head> section of an HTML document.
Example:
<head>
<style>
p{
color: blue;
}
</style>
</head>
Advantage: Better organization compared to inline CSS.
Disadvantage: Still makes the HTML file longer.
3. External CSS
Defined in a separate .css file and linked to the HTML document using the <link> tag.
Example:
<link rel="stylesheet" href="styles.css">
Content of styles.css file:
p{
color: blue;
}
Advantage: Keeps styles separate, making HTML cleaner and more maintainable.
Disadvantage: Requires an additional HTTP request to load the CSS file.
CSS Priority Order
From highest to lowest priority:
!important > Inline > Internal = External
!important overrides all other styles.
Inline styles override both internal and external styles.
Internal and external styles have the same priority (whichever appears last is applied).
CSS Selectors
CSS provides multiple ways to select elements:
1. Tag Selector
Selects all elements with a specific tag name.
Example:
p{
color: red;
}
(This applies to all <p> elements.)
2. Class Selector
Selects multiple elements that share the same class.
Uses a dot (.) notation.
Example:
.highlight {
background-color: yellow;
}
<p class="highlight">This is highlighted text.</p>
<div class="highlight">This div is also highlighted.</div>
3. ID Selector
Selects a single, unique element using an ID.
Uses a hash (#) notation.
Example:
#main-title {
font-size: 24px;
color: blue;
}
<h1 id="main-title">This is a unique heading</h1>
Selector Priority Order
#id > .class > tag
ID Selector (#id) has the highest priority.
Class Selector (.class) has medium priority.
Tag Selector (tagname) has the lowest priority.