📖 CSS Style Sheets
Cascading Style Sheets (CSS) provide a way for web developer's to have more control over the appearance of their web pages. CSS uses style tags and attributes to format text and specify layout for your Web pages. Remember the principles of layout and composition when designing your web pages.
There are three ways to add style to your web pages through CSS.
- in-line style
- embedded (internal) style sheet
- external style sheets
In-line style works by adding a style attribute to an existing tag. In-line style is not standards compliant, so we will not be using it in this class. However, if you were to come across some HTML code that has a style attribute in a tag (i.e. <p style="color:#ff0000">
, then you will understand that it is CSS applied at the element level. You may also find inline style useful in cases where you do not have access to the HTML code or style sheet on a page - for example if you are posting information from a form based application. For example, I use it in the college LMS to add styles since I don't have access to the style section or external style sheet within eCampus.
An embedded style is a (internal) style sheet that is included in an HTML document. The styles in the embedded style sheet will apply to everything on that Web page. The style rules are coded between the <style>
and </style>
tags and are located in the <head>
section of your document:
<style>
style rules will be listed here
...
</style>
An external style sheet is a text document that contains a list of style rules which can be applied to any number of web pages. The text document does not contain any HTML content—only style definitions. The document should be named with an extension of .css
and included in the same folder with your web pages. To use the style sheet on your Web pages, you must link it to each page that you want it to format by placing the <link>
tag in the <head>
section of each page:
<link rel="stylesheet" href="style.css" />
where "style.css" is the name of your external style sheet document.
Another option is to use @import
to attach an external style sheet to a page. The @import
rule must be the first statement in the <style>
element. You can import more than one external style sheet, but they must all be before any style selectors and will be applied in the order listed.
<style>
@import url("filename");
body {
font-face: arial;
}
. . . more styles here . . .
</style>
Internal vs. External Stylesheets
Internal and external style sheets each have advantages and disadvantages when used with mobile devices.
Internal Stylesheets
- Not reusable
- Styles must be coded on each and every page where they are used
- Stored in same document with html code
- Only one server response needed for the page
- Render quickly
- Increase page size
External Stylesheets
- Reusable across multiple pages
- Create styles once and apply to multiple pages.
- Ensures design consistency
- Easier to maintain and update
- Stylesheet only has to be loaded one time if the user browses several pages in your site
- Stored separately
- Increases download time for the initial page
So which one is best? If you have a lot of styles that are applied across the majority of your mobile web pages, then it is probably best to put these in an external stylesheet and attach it to each page. Although the initial download may take a little longer, performance on subsequent pages will be quicker. Plus your design will be consistent and any changes you make to the design will be quicker and easier. However, if you have styles that only apply to one page, you should probably include those in an internal stylesheet. This will reduce the size of the external stylesheet for all other pages and render quickly for the page where they are used.
CSS Rules
A CSS rule looks like this...
p {
color: #660000;
font-family: Arial, Helvetica, sans-serif;
/* additional properties... */
}
where p
is the selected element that the style will be applied to and color: #660000
is the style property (color
) and value (#660000
) that will be applied. A CSS rule can contain any number of properties and values, separated by a semicolon (;
). In this case, any text on a Web page that was inside a <p> element would be maroon with 3 font-families specified. These fonts are used in order as available.
h1, h2, h3 {
color: #660000;
font: 700 Georgia, 'Times New Roman', Times, serif;
}
You can apply styles to multiple elements by separating them with a comma. The rules for the headings above show the font shorthand rule with a bold (700) weight and cascading font-families. The shorthand rules can include style, variant, weight, family and more. More information about fonts at W3 Schools. Notice that fonts with multiple names must be enclosed in quotes.
Comments in stylesheets
If you want to document your styles in your style sheets, you can add comments by placing the comment between /* and */ delimiters.
/* this is a css comment */
main {
width: 80%;
margin: 0 auto;
}
Class attribute
Classes allow you to set up groups of rules to apply to multiple elements by adding the desired elements to the class. You can also apply multiple classes to elements. To create a class in your style sheet, you simply type a period(.) followed by the name of the class:
.special {
color: #660000;
}
This creates a class called special which will turn the text maroon. To use the class, add a class attribute to the HTML tag:
<p class="special">
Now, instead of all the paragraphs on the Web page being maroon, only those with a class of "special" will be maroon. The class attribute can be added to any HTML tag. Occasionally, you may find that you want to add style where no html tag is currently found. There are 2 special html tags that can be used for this purpose. The <span>
tag is an inline tag that can be used to add a style class to your code where no existing HTML tag is available and the <div>
tag is a block tag that can be used to add a style class to an entire section of your HTML page (i.e. multiple paragraphs, headings, etc.)
You can create a class just for one html tag by placing the name of the tag in front of the class name:
p.special {
color: #660000;
. . .
}
This would create the special class just for the paragraph tag and not any other tags.
You can also apply multiple classes to the same tag by listing them inside the quotes:
<p class="special creative">
This would apply both the special and the creative classes to the paragraph.
id attribute
The id attribute is similar to the class attribute in that it allows you to apply styles to specific elements. However, instead of assigning a class to an element, you give the element an id attribute. Generally, you should use id when the styles are unique to a single element. Classes are more generic and can be used for multiple elements. In the style definition, you can specify styles just for an id by using the #id designation:
#id1 {
border-color: red;
border-width: medium;
background-color: aqua;
padding: 20px;
}
Link pseudoclasses
CSS has some built in pseudoclasses that can be used to override the default styles for links:
a:link { color:#FF0000; } /* unvisited link */
a:visited { color:#00FF00; } /* visited link */
a:hover { color:#FF00FF; } /* mouse over link */
a:active { color:#0000FF; } /* selected link */
If you use all 4 anchor pseudoclasses, they must appear in the order listed here or they will not work properly.
Action pseudo-classes
- :focus - applies when a form element is selected and ready for input
- :hover - applies when the mouse hovers over an element
- :active - applies when the element is in the process of being clicked or tapped
Pseudo-element selectors
- :first-line - applies to the first line of the element. Limited style properties available
- :first-letter - applies to the first letter of the element. Limited style properties available
- :before - inserts content before the element
- :after - inserts content after the element
Other selector options
The following code is used in the examples for these selector types.
<div id="gallery">
<img src="image1.png" id="img1">
<p>
<img src="image2.png" id="img2">
<img src="image3.png" id="img3">
<img src="image4.png" id="img4">
</p>
</div>
Name | Target | Selector | Selection |
---|---|---|---|
Descendant selector | Selects descendant elements of the first selector |
|
|
Child selector | Only selects a direct child of the selector |
|
|
Adjacent sibling selector | Only selects an element that comes immediately after another element with the same parent. |
|
|
General sibling selector | Selects an element that shares a parent with the selector and comes after the selector |
|
and
|
There are many more specific ways to apply CSS to your code. A good reference for CSS selectors can be found on the W3Schools site at http://www.w3schools.com/cssref/css_selectors.asp, if you need more help with this process.
The Cascade
In some cases you may have more than one style rule that applies to the same element on your page. There are several principles that can help you understand how they are applied to the page.
Style Inheritance
Styles defined for a parent tag or element will apply to the descendant elements or tags unless they conflict with styles defined for that element. For example, if you have a style on the body tag that changes the text color to maroon, then all text on the entire page will be maroon -- unless you have a style on a lower level tag that conflicts. So, if on that same page, you have style defined for the h1 tag that has the color property set to navy blue, then the text inside of the h1 tag would be navy instead of maroon.
Specificity
If you set the class on a paragraph tag to a different color, then it would override the body attribute. This is known as specificity - the more specific the rule, the stronger. So, an element nested inside another element (such as the h1 inside the body, or an em inside a paragraph) is more specific so those rules will apply. A class is more specific than an element and an id is more specific than a class.
Style Precedence
You may include embedded style and external style sheets in the same Web page. When conflicting styles are found for a web element, the browser will apply the styles in the order that they occur.
You can use both an internal and external stylesheet in the same page. The styles will be applied in the order that they appear. So if the link to the external stylesheet is above the <style>
section, the external will apply first and the internal will be applied second. If the link to the external stylesheet is below the <style>
section, then the internal styles are applied first and the external second. This is only significant when there are conflicting styles as demonstrated in the examples below. For example, if I have h1 {color: blue; font-style: italic;}
in my external stylesheet and h1 {color: red; font-weight: bold;}
in my internal stylesheet, then the following would apply.
External Stylesheet
h1 {
color: blue;
font-style: italic;
}
Example Code |
---|
|
Appearance on Page |
Example 1 |
Example Code |
---|
|
Appearance on Page |
Example 2 |
Because the font-style and border-top attributes do not conflict, they apply to the h1 text in both examples. However, since the color attribute is different, in the first example, the internal style applies because it occurs second. In the second example the external style applies because it comes after the internal.
!important
To prevent a subsequent CSS rule from overriding a rule (such as in a cascade), you can add !important after the style value.
blockquote {
font-style: italic !important;
}
You can also link multiple style sheets to a single web page and designate them for use on a particular output such as screen, print, handheld, etc. by adding media="output" to the link.
@media output {
style rules...
}
To designate rules for a particular media, for example, if your site has a 2 column layout, you might want to have a different layout for mobile devices (media="handheld") to make it more readable on a smaller screen.
HTML5 Web Page with CSS
The example below uses some minimal CSS to create a wrie frame layout. A wire frame layout is a quick and easy layout used to visualize a page concept. Designers and developers use this to provide choices to clients and solicit their feedback. It's much easier to make site changes early than to make a lot of changes later.
Backgrounds
You can add a background color or background image to your elements as well using the following style attributes.
Attribute | Definition |
---|---|
|
specifies the color of the background using a keyword, rgb value or hex code. |
|
specifies the image that will be displayed in the background of the box. |
|
specifies how the image will be repeated: repeat is the default and will tile the image to cover the entire box. no-repeat will display the image only once. repeat-x will repeat the image horizontally only. repeat-y will repeat the image vertically only.. |
|
specifies the horizontal and vertical position of the image. Top and left are the default values. |
Shorthand Methods for Styles
CSS properties that have multiple values can all be specified in a single line using the parent element. For example, the following style declarations are all equivalent.
Full Definition | Shorthand |
---|---|
|
|
|
|
|
|
|
|
Miscellaneous Other Styles
Attribute | Definition |
---|---|
|
specifies the stacking order of elements that overlap. Larger numbers are stacked on top of smaller numbers. If no z-index is specified, elements that occur later in a document are stacked on top of elements that appear earlier. |
|
specifies what to do with content that exceed the size of the box. Options are:
|
|
specifies how items are aligned vertically. Options are baseline, middle, sub, super, text-top, text-bottom, top, bottom or a percentage. |
|
allows you to change the cursor shape. Options are pointer, default (arrow), crosshair, move, wait, help, text, progress or auto. |
|
changes the display type of an element. Options include inline, block, inline-block, or none (does not display and is removed from the normal flow of the page). Other options available but seldom used. |
|
determines whether an element is visible on a page (does not remove from the normal flow). Options are hidden or visible. |
Additional Resources
Testing Your Page
Once you have finished your page, you will need to validate your code to make sure you have not made any obvious errors including accessibility errors. The HTML validator can help spot HTML code errors but will not catch everything. You should also run your pages through the CSS validator and check the page for accessibility errors including page structure and contrast. You can find more information about testing in the article on Testing and Debugging HTML and CSS. I recommend you upload your pages and dependencies (scripts, images, etc.) to the class server and test the page from there using the site URL.