Categories
CSS (Cascading Style Sheets) syntax is used to apply styles and formatting to HTML and XML documents. It consists of rules that define how elements should be presented on a webpage. Here's the basic syntax of CSS along with an example:
selector {
property: value;
/* more properties and values */
}
Explanation:
-
selector
: It is used to target HTML elements that you want to style. It can be an element selector (e.g.,h1
,p
,a
), a class selector (e.g.,.my-class
), an ID selector (e.g.,#my-id
), or other complex selectors. -
property
: It refers to the specific style property you want to apply to the selected element (e.g.,color
,font-size
,background
,margin
). -
value
: It represents the value assigned to the property (e.g.,red
,16px
,url('image.jpg')
,2em
).
Example:
Let's say we have the following HTML markup:
<!DOCTYPE html>
<html>
<head>
<title>CSS Syntax Example</title>
<style>
/* CSS rule for h1 element */
h1 {
color: blue;
font-size: 24px;
text-align: center;
}
/* CSS rule for p elements with class "highlight" */
p.highlight {
background-color: yellow;
padding: 10px;
}
/* CSS rule for elements with ID "my-button" */
#my-button {
background-color: green;
color: white;
padding: 8px 16px;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Hello, CSS Syntax Example</h1>
<p class="highlight">This paragraph has a yellow background.</p>
<button id="my-button">Click Me</button>
</body>
</html>
In this example:
-
The CSS rule for
h1
selects all<h1>
elements on the page and sets their color to blue, font size to 24 pixels, and text alignment to center. -
The CSS rule for
p.highlight
selects all<p>
elements with the class "highlight" and applies a yellow background color with 10 pixels of padding. -
The CSS rule for
#my-button
selects the element with the ID "my-button" (in this case, a button element) and styles it with a green background, white text color, no borders, padding, and a cursor change on hover.
CSS is a powerful language that allows for extensive styling and layout control. By combining different selectors, properties, and values, you can create visually appealing and responsive webpages.