CSS is an acronym standing for Cascading Style Sheets. CSS is used together with HTML to describe how HTML elements look in a web browser. The file extension for CSS is .css
. The MIME type for CSS is text/css
.
The CSS code below represents a 200px red square.
.square {
background: #f00;
height: 200px;
width: 200px;
}
The following example demonstrates how to implement CSS in HTML code.
<!DOCTYPE html>
<html>
<head>
<title>CSS Example</title>
<style>
/** Declare a CSS class named square. **/
.square {
background: #f00;
height: 200px;
width: 200px;
}
</style>
</head>
<body>
<!-- Add the square CSS class to a DIV. -->
<div class="square"></div>
</body>
</html>
A CSS ID selector is used in combination with the id
attribute of an HTML element to select a unique element in a web page. According to the ID of an HTML element being unique, a CSS ID selector is used to select one specific HTML element with the the same ID.
A CSS ID selector begins with a hash #
character, followed by the name of an ID. For example, #header
is for selecting the HTML element with the header
ID attribute.
The following CSS code is a CSS ID selector for selecting the HTML element with the header
ID in a web page. Please note that a CSS ID selector can't begin with a number.
#header {
background: #333;
color: #fff;
height: 40px;
width: 100%;
}
CSS ID selectors seem to be very handy to select the unique HTML element. However, it's not advisable to use them because their specificity is higher than CSS class selectors, and they can't be reused. You have to overwrite the ID specificity by using !important
which could lead to further confusions in your CSS code. Therefore, CSS class selectors are preferred instead.
Anyway, according to CSS ID selectors being unique, they can be used as anchor links for navigating to certain sections within a web page.
A CSS class selector is used in combination with the class
attribute of an HTML element to select one or multiple elements in a web page. The difference between a CSS class selector and an ID one is that a CSS class selector can be used to select all the HTML elements with the same class attribute whereas an ID one can select only one unique HTML element.
A CSS class selector begins with a dot .
, followed by the name of a class. For example, .post
is for selecting any HTML elements with the post
class attribute.
The CSS code below shows how to declare a CSS class selector to use in multiple HTML elements. Please note that a CSS class selector can't begin with a number.
.post {
background: #fff;
box-shadow: 0 0 2px;
color: #333;
height: 600px;
padding: 10px;
width: 400px;
}
CSS minification is the process of removing all the unnecessary whitespace characters as well as comments from CSS code so that it will be more compact for production. CSS minification significantly helps reduce the file size and bandwidth usage.