HTML Styles - CSS
CSS stands for Cascading Style Sheets. CSS saves a lot of work. It can control the layout of multiple web pages all at once.
What is CSS?
Cascading Style Sheets (CSS) is used to format the layout of a webpage. With CSS, you can control the color, font, the size of text, the spacing between elements, how elements are positioned and laid out, what background images or background colors are to be used, different displays for different devices and screen sizes, and much more!
Three Ways to Insert CSS
There are three ways of inserting a style sheet:
- External CSS: Styles are defined in an external
.cssfile. This is the recommended method for styling large websites. - Internal CSS: Styles are defined within a
<style>element, inside the<head>section of an HTML page. - Inline CSS: Styles are defined directly inside an HTML element, using the
styleattribute.
Inline CSS
An inline style may be used to apply a unique style for a single element. To use inline styles, add the style attribute to the relevant element.
Example
<h1 style="color:blue;text-align:center;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>Internal CSS
An internal style sheet may be used if one single HTML page has a unique style. The internal style is defined in the <head> section of an HTML page, within a <style> element.
Example
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>External CSS
With an external style sheet, you can change the look of an entire website by changing just one file! Each HTML page must include a reference to the external style sheet file inside the <link> element, inside the head section.
Example (HTML File)
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>The external stylesheet (e.g., "styles.css") would look like this:
Example (styles.css)
body {
background-color: powderblue;
}
h1 {
color: blue;
}CSS Fonts, Colors, and Borders
CSS provides a wide range of properties to control the appearance of your content. Here are a few common ones:
color: Sets the text color.font-family: Sets the font for the text.font-size: Sets the size of the text.border: A shorthand property for setting the width, style, and color of an element's border.padding: Sets the space between the content and the border.margin: Sets the space outside the border.
Test Yourself with an Exercise
Which method is generally considered the best practice for applying CSS to a large website?