Skip to content
YuDe edited this page Jun 29, 2015 · 32 revisions

Introduction to CSS

Cascading Style Sheets (CSS) is a style sheet language used for describing the look and formatting of a document written in a markup language. The language can be applied to HTML and XHTML and XML document, including plain XML, SVG and XUL. But now, it is most widely used in styling web pages.

CSS is designed primarily to enable the separation of document content from document presentation, including the layout, colors, and fonts. This separation can enable multiple HTML pages to share formatting by specifying the relevant CSS in a separate .css file, and reduce complexity and repetition in the structural content and unified the style for the whole related web pages.

This separation of formatting and content makes it possible to present the same markup page in different styles for different rendering methods, such as on-screen, in print, by voice (when read out by a speech-based browser or screen reader) and on Braille-based, tactile devices. It can also be used to display the web page differently depending on the screen size or device on which it is being viewed.

For more detail information, please read wiki CSS.

Like the Cookfrontend HTML, we classify tutorials into three levels. Besides, we add another creative css lesson called CSS border shaping to create beautiful icons.

Basic CSS

The method applying CSS to HTML

We all know that CSS is about style. If we see keyword style, it is definitely CSS!

We have three ways to apply CSS in our html.

First we can use the inline. For example, we can set tag's style attribute like: <p style="color red"> This is red.</p>

That will make the text of the paragraph becomes red. It's good when you just want to adjust few parts of the page.

The second one is Internal apply. We create the style inside the head tags and define the elements' style between style and its enclosed.

<!DOCTYPE html>
<html>
   <head>
        <title></title>
        <style type="text/css">
            div {
              border: 1px solid #000;
            }
            span {
              color: red;
            }
        </style>
   </head>
   <body>
        <div>This is <span>span</span> in <span>div1</span></div>
        <div>This is <span>span</span> in <span>div2</span></div>	
   </body>
</html> 

The div inside the body will have borders with color black and span's all text will become red.

The last and the most important one is External apply. What is it? It's a method importing CSS files like other programming languages import the libraries they need.

To import our wanted css styles externally, we should create a css file first. Creating a css file is simple, just add a new file which name ends with .css. Done!

Let's start to edit our css file:

div {
    border: 1px solid #000;
}
span {
    color: red;
}

Then we import the css file we created in our html. How to import? There is a tag called link can get the job done.

<!DOCTYPE html>
<html>
   <head>
        <title></title>
        <link rel="stylesheet" type="text/css" href="external_apply.css">
   </head>
   <body>
        <div>This is <span>span</span> in <span>div1</span></div>
        <div>This is <span>span</span> in <span>div2</span></div>	
   </body>
</html> 

You can see the same result as we have done in internal_apply.html.

Which one is the best way to apply CSS? In reality, the third way is the most popular way. Applying the CSS Externally makes the css styles reusable, maintainable and flexible. Sometimes if we want to do a little trim for the specific elements, method one is not a bad idea if the amount of the elements are not many. The method two... Well... I have no comment :)

Idea about Selectors

Selectors select the elements which following the rule it defines. We can define Selectors by html tags, class names and id names. We will discuss the selectors with pure html tags.

For each selector there are “properties” inside curly brackets like below:

htmlelement {
    property1: value1;
    property2: value2;
}

Every htmlelement inside the body tags will own the 2 properties we setup.

If you want to make every div's text with blue color and size 16px. You set up a div selector like:

div {
    color: blue;
    font-size: 16px;
}

Every div in body will be the style you want.

Text

Text is the soul to deliver the messages the web owner wants to express. Hence, there are lots of properties about font's size, font's color, font's style etc. Make good use of them can make your text elegant and comfortable for users to read.

font-family: Define font itself

font-family decides the appearance of the fonts such as Times New Roman, Arial, or Verdana.

The user’s browser has to be able to find the font you specify, which, in most cases, means it needs to be on their computer so there is little point in using obscure fonts that are only sitting on your computer. To prevent they don't have the specific type the web using, we always set up some “safe” fonts (the most commonly used are Arial, Verdana and Times New Roman) separated by commas. The purpose is that if the user does not have the first font you specify, the browser will go through the list until it finds one it does have. This is useful because different computers sometimes have different fonts installed. (Like Mac and Windows have their own fonts.)

p {
    font-family: arial, helvetica, serif;
}

The above css statement will look for the Arial font in the very beginning and, if the browser can’t find it, it will search for Helvetica, then a common serif font.

Noted: if the name of a font is more than one word, it should be put in quotation marks, such as font-family: "Times New Roman".

The web world is much competitive than years ago. More and more web developers designed their own text to express their own styles and integrate with their visual design to enhance UI/UX experiences. Sadly, we don't have any money to hire a designer to make a font for us and there is no font I would like to apply on my web page either. Don't worry, there are lots of free font sources we can use, the biggest one is google fonts. Using google fonts can make sure that users surf your webs with correct font styles because the font source is imported from the Google server. The only disadvantage is it slows the web traffic.

font-size: Define the fonts' size

font-size decide the size of the fonts and there are several units we can apply to our fonts' size.

  • px (ex: font-size: 12px) is the unit for pixels.
  • em (ex: font-size: 2em) is the unit for the calculated size of a font. So “2em”, for example, is two times the current font size.
  • pt (ex: font-size: 12pt) is the unit for points, for measurements typically in printed media.
  • pc (ex: font-size: 10 pc) is the pica unit
  • % (ex: width: 80%) is the unit for… wait for it… percentages.
  • cm (ex: font-size: 1cm) is the unit for centimeters
  • mm (ex: font-size: 10mm) is the millimeters unit.

Those units are not specified for fonts only. Height, weight, margin, padding, border etc. apply for these units too.

Test the snippet to see the result:

<!DOCTYPE html>
<html>
   <head>
        <title></title>
        <link rel="stylesheet" type="text/css" href="external_apply.css">
   </head>
   <body>
      <p style="font-size: 10px;;">font size is 10px</p>
      <p style="font-size: 2em;">font size is 2em</p>
      <p style="font-size: 10pt;">font size is 10pt</p>
      <p style="font-size: 10pc;">font size is 10pc</p>
      <p style="font-size: 50%;">font size is 50%</p>
      <p style="font-size: 4cm;">font size is 4cm</p>
      <p style="font-size: 50mm;">font size is 50mm</p>
   </body>
</html> 

font-weight

font-weight states whether the text is bold or not. Most commonly this is used as font-weight: bold or font-weight: normal but other values are bolder, lighter, 100, 200, 300, 400 (same as normal), 500, 600, 700 (same as bold), 800 or 900. We highly recommend you to use the number instead of bold and normal because older browsers would mess these two words. Some fonts do not support font-weight property either.

font-style

This states whether the text is italic or not. It can be font-style: italic or font-style: normal.

text-decoration

text-decoration states whether the text has got a line running under**(underline), over(overline), or through it(line-though)**.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <p style="text-decoration: underline;">underline</p>        
    <p style="text-decoration: overline;">overline</p>
    <p style="text-decoration: line-through;">line-through</p>        
</body>
</html>

text-transform

text-transform changes the case of the text. Copy the snippet to see the result.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <p style="text-transform: uppercase;">uppercase</p>        
    <p style="text-transform: lowercase;">lowercase</p>
    <p style="text-transform: capitalize;">capitalize</p>        
</body>
</html>

Text spacing

  • letter-spacing: spacing between letters
  • word-spacing: spacing between words
  • line-height: height of the lines in an element
  • test-align: Align the text inside an element to left, right, center, or justify
  • text-indent: Indent the first line of a paragraph.

Try the snippet below to see how they work:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        div {
            border: 1px solid #444;
        }
    </style>
</head>
<body>
    <div>
        <p style="letter-spacing: 3em;">letter-spacing: 3em;</p>
    </div>
    <div>
        <p style="word-spacing: 2em;">word-spacing: 2em;</p>
    </div>
    <div>
        <p style="line-height: 7em;">line-height: 7em;</p>
    </div>
    <div>
        <p style="text-align: center;">text-align: center;</p>
    </div>
    <div>
        <p style="text-align: justify;">text-align: justify;</p>
    </div>
    <div>
        <p style="text-indent: 2em;">text-indent: 2em;</p>  
    </div>
</body>
</html>

Colors

About Colors in CSS

CSS brings 16,777,216 colors generously to your disposal. They can take the form of a name, an RGB (red/green/blue), RGBA (red/green/blue/alpha) or a hex code.

  • name: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, orange, purple, red, silver, teal, white, yellow even transparent.
  • rgb: rgb(0 ~ 255, 0 ~ 255, 0 ~ 255) or rgb(0% ~ 100%, 0% ~ 100%, 0% ~ 100%)
  • rgba: rgba(0 ~ 255, 0 ~ 255, 0 ~ 255, 0 ~ 1) or or rgba(0% ~ 100%, 0% ~ 100%, 0% ~ 100%, 0 ~ 1)
  • hex code: #000000 ~ #ffffff

The most confused one is hex code. It is a base-16 number system starting from 0 and f. The first two digits represents red, the second two means green and the last two are blue. Sometimes we just use three digits which is compressed version for 6 digits to represent the colors. Using three digits can help us know easily the percentage of three colors (like rgb, first is read, the send is green, the last is blue) but six digits give us more more control over the color.

Border, Margin and Padding (Box Model)

Box Model

From the W3C definition: "CSS (Cascading Style Sheets) describes the rendering of documents on various media. When textual documents (e.g., HTML) are laid out on visual media (e.g., screen or print), CSS models the document as a hierarchy of boxes containing words, lines, paragraphs, tables, etc. each with properties such as size, color and font. "

Form the definition, we know every element is rendered as box. They owns their own border, margin and padding properties.

Border depicts the shape of the element; Margin describes the distance from the element to others; Padding defines the spaces inside the elements.

Try the below snippet.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        #box_model {
            margin: 20px;
            border: 10px solid red;
            padding: 30px;
            background-color: orange;
        }
    </style>
</head>
<body>
    <div id="box_model">
        <p>Box Model</p>
    </div>
</body>
</html>

Border

A element has the default border value none. To let a border be displayed, we need the border-style. The values can be solid, dotted, dashed, double, groove, ridge, inset and outset.

border-width sets the width of the border, most commonly using pixels as a value.

border-color sets the color. Here is an example snippet:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        #box {
            border-style: dashed;
            border-color: blue;
            border-width: 20px;
        }
    </style>
</head>
<body>
    <div id="box">
        <p>Box Model</p>
    </div>
</body>
</html>

There is a shorthand syntax border which combined border-width, border-style andborder-color.

border: width value, style value, color value

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        #box {
            border-style: dashed;
            border-color: blue;
            border-width: 20px;
        }
        #box2 {
            border: 20px solid red;
        }
    </style>
</head>
<body>
    <div id="box">
        <p>Box Model</p>
    </div>
    <div id="box2">
        <p>Box Model</p>
    </div>
</body>
</html>

We can also control 4 sides of the border separately.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        #box {
            border-left-style: dashed;
            border-left-color: blue;
            border-left-width: 20px;
            border-right-style: groove;
            border-right-color: orange;
            border-right-width: 10px;
            border-top-style: dotted;
            border-top-color: purple;
            border-top-width: 30px;
            border-bottom-style: solid;
            border-bottom-color: green;
            border-bottom-width: 40px;
        }
    </style>
</head>
<body>
    <div id="box">
        <p>Box Model</p>
    </div>
</body>
</html>

Round corners are really common nowadays. Using border-radius can reach our goal. Besides, we can control 4 corners separately.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        #box {
            border: 2px solid blue;
            border-radius: 20px;
        }
        #box2 {
            border: 2px solid red;
            border-top-left-radius: 5px;
            border-bottom-left-radius: 10px;
            border-top-right-radius: 15px;
            border-bottom-right-radius: 20px;
        }
    </style>
</head>
<body>
    <div id="box">
        <p>Box Model</p>
    </div>
    <div id="box2">
        <p>Box Model</p>
    </div>
</body>
</html>

Margin and Padding

Unlike border's various properties, margin and padding only provide separate control over the 4 sides.

margin-top, margin-bottom, margin-right, margin-left padding-top, padding-bottom, padding-right, padding-left

Background

Background, like the border, provides various properties: background-color, background-image, background-repeat (Decides how the image repeats itself), background-position etc.

background-color Literally, set the color for the background. background-image Attach the image to the background by pointing the location of the source. Internet resources or local sources are acceptable. background-repeat Determine how the image repeat itself.

  • repeat: Repeat the whole image crossing over the whole background.
  • repeat-x: Make the image repeat along the x-axis.
  • repeat-y: Make the image repeat along the y-axis.
  • no-repeat: The default value. only one instance of image shows. background-position: Decide where the image should be located. Name, percentage, length are allowed. Some special terms can be applied too. Such as top right, top left, bottom right and bottom left.

We can replace those 4 with a handy line background: (background-color) (background-image) (background-repeat) (background-position); Play the below snippet for more fun.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        body {
            background: green url(http://english.president.gov.tw/Portals/4/images/PresidentOffice/president.png) no-repeat top left;
        }
    </style>
</head>
<body>
    
</body>
</html>

Intermediate CSS

Page Layout: Display, Position and Float

Display

Display manipulates the fundamental layout of pages. CSS provides many choices for display properties. However, we only introduce the most common and widely support ones (Support 99% of the browsers).

None

Display: none makes the element invisible. It sounds useless but it's quite powerful when bounding with dynamic effect. For example, when you see an introduction of an item with a more info button below. You can click it to read further details then the hidden detail information shows up on the page.

Block

A lot of container-liked elements have display: block as their default like div, section and ul. Some text elements, p and heading, owns the same default. The block element takes up width as much as it can and does not allow other elements beside it.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        #id1 {
            background-color: red;
        }
        #id2 {
            background-color: blue;
        }
        #id3 {
            background-color: green;
        }
    </style>
</head>
<body>
    <div id="id1">
        <p>This is Div 1</p>  
    </div>
    <div id="id2">
        <p>This is Div 2</p>  
    </div>
    <div id="id3">
        <p>This is Div 3</p>  
    </div>
</body>
</html>

Inline

Unlike the block occupies the entire row from its parent. Inline tends to share with others. Elements like anchor and span set it as default display.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        div {
            display: inline;
        }
        #id1 {
            background-color: red;
        }
        #id2 {
            background-color: blue;
        }
        #id3 {
            background-color: green;
        }
    </style>
</head>
<body>
    <div id="id1">
        <p>This is Div 1</p>  
    </div>
    <div id="id2">
        <p>This is Div 2</p>  
    </div>
    <div id="id3">
        <p>This is Div 3</p>  
    </div>
</body>
</html>

Inline-Block

inline-block is similar to inline. The only slight difference is inline-block allows the element be set with height and width value. On the contrast, inline is not.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        div {
            display: inline-block;
        }
        #id1 {
            height: 100px;
            width: 150px;
            background-color: red;
        }
        #id2 {
            height: 200px;
            width: 200px;
            background-color: blue;
        }
        #id3 {
            height: 300px;
            width: 250px;
            background-color: green;
        }
    </style>
</head>
<body>
    <div id="id1">
        <p>This is Div 1</p>  
    </div>
    <div id="id2">
        <p>This is Div 2</p>  
    </div>
    <div id="id3">
        <p>This is Div 3</p>  
    </div>
</body>
</html>

Position

The position value in CSS deals with layout and manipulating elements to be in your desired visual place. There are the five values: static, relative, absolute, fixed and inherit. However, only three are commonly used since static and inherit are rarely needed.

static

Every element is static positioned by default. The element resides in the normal page flow. left/right/top/bottom/z-index have no effect on a static element. There is no need to set this unless it is overwritten and you want to set it back.

Noted: What is normal page flow? Normal flow is the way that elements which are not relative or absolute positioned are displayed in a web page. In normal flow, boxes are positioned on a page one after the other.

relative

Element's original position remains in the flow. But left/right/top/bottom/z-index properties do work. Those direction properties are able to move the elements from its origin. Here is a pic from CSS Tricks.

Pic

absolute

Absolute positioned element is no longer the flow of the document. Only the direction properties work on it. Moreover, those directions properties are relative to its parent if it's a relative positioned parent.

Pic

fixed

Like absolute positioned elements, Element is removed from the flow of the document. They behave almost the same. The only difference is fixed positioned elements are always relative to the document. It's usually used to provide a visual element that is always visible.

inherit

Nothing to talk about, it just take its parent's value as its.

Float

Class and ID

In CSS file, we define classes': .classname { property1: value1; ... }

ids': #idname { property1: value1; ... }

Then we can add the defined class name to the html element with class attribute, for example: <div class="classname"></div> Likewise, we add the id to the element with id attribute. <div id="idname"></div>

What's the difference between id and class? id is used for identifying which means the id name should be unique in the page. Besides, every element only own on id. Comparing to id's uniqueness, classname can be multiple applied to lots of elements and each element can have multiple classes.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        div {
            display: inline-block;
        }
        #id1 {
            background-color: red;
        }
        #id2 {
            background-color: blue;
        }
        #id3 {
            background-color: green;
        }
        .class1 {
            height: 200px;
            width: 200px;
        }
    </style>
</head>
<body>
    <div id="id1">
        <p>This is Div 1</p>  
    </div>
    <div id="id2" class="class1">
        <p>This is Div 2</p>  
    </div>
    <div id="id3" class="class1">
        <p>This is Div 3</p>  
    </div>
    <div id="id4" class="class1">
        <p>This is Div 4</p>
    </div>
</body>
</html>

Grouping and Nesting with Multiple Selectors

Grouping

If there are replicated properties in different selectors, like:

.class1 {
    color: red;
}
.class2 {
    color: red;
}
.class3 {
    color: red;
}

we can combined them in one CSS selector and use comma to separate them.

.class1, .class2, .class3 {
    color: red;
}

Nesting

Nesting helps to organize the CSS structures and makes the CSS properties more flexible to apply and reuse.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        #id1, #id2, #id3 {
            display: inline-block;
            height: 200px;
            width: 200px;
        }
        .classname .anotherclassname {
            font-size: 2em;
        }
        .classname {
            font-weight: 700;
        }
        .anotherclassname {
            background-color: red;
        }
    </style>
</head>
<body>
    <div id="id1" class="classname anotherclassname">
        <p>This is Div 1</p>  
    </div>
    <div id="id2" class="classname">
        <p>This is Div 2</p>  
    </div>
    <div id="id3" class="anotherclassname">
        <p>This is Div 3</p>  
    </div>
    <div id="id4" class="classname">
        <p>This is Div 4</p>
    </div>
</body>
</html>

According to the above the code, the element with have both classname and anotherclassname owns the font-size: 2em;.

Pseudo Classes

Pseudo classes are bounding on to selectors to specify a state or relation to the selector. They take the form of selector:pseudo_class { property: value; }. Here is an example code:

Dynamic Effects

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        div {
            display: inline-block;
            height: 200px;
            width: 200px;
        }
        .classname {
            font-weight: 700;
        }
        .classname:hover {
            background-color: #333;
        }
        a:visited {
            color: green;
        }
        a:active {
            color: red;
        }
    </style>
</head>
<body>
    <div id="id1" class="classname ">
        <a href="http://www.google.com">Google</a>
    </div>
    <div id="id2" class="classname">
        <a href="http://www.microsoft.com">M$</a>
    </div>
    <div id="id3" class="classname">
        <a href="http://www.oracle.com">Oracle</a>
    </div>
    <div id="id4" class="classname">
        <a href="http://www.ibm.com">IBM</a>
    </div>
</body>
</html>  

For example, when the cursor is over the element, the element changes its state of appearance to tell user: "You are pointing to me!". We use pseudo class :hover to implement this interactive effect.

There are lots of links in the web and we want to remind users that some of the links they have visited before. :visited can mark those linked with customized properties once the user clicks the links.

:active changes the states when user click it. If the internet speed is too fast, you might not see the affect easily. To see the affect, you can click and hold for seconds.

Position/Number-based pseudo class selectors

Most elements have siblings. Number-based pseudo class selectors are used to represent the ranking between the siblings. first-child represents the one ranking first. last-child represents the last one. We can use nth-child(position number) to point to the others.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        div {
            height: 100px;
        }
        div:first-child {
            background-color: red;
        }
        div:nth-child(2) {
            background-color: orange;
        }
        div:nth-child(3) {
            background-color: yellow;
        }
        div:nth-child(4) {
            background-color: green;
        }
        div:nth-child(5) {
            background-color: blue;
        }
        div:last-child {
            background-color: purple;
        }      
    </style>
</head>
<body>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</body>
</html>

Pseudo Elements

Pseudo Elements and Pseudo Classes have the same CSS synax: selector:pseudo_element. However, they have two different functions.

Pseudo elements don't select any "real" element existing on the page; pseudo classes do select the real.

It sounds absurd that developers can use the alike syntax to do totally different operations. In practical, we prefer each of the syntax has its own definition which makes the document much more logical, readable and maintainable. Thankfully, in CSS3 , there is a new rule for pseudo elements: adding another : before the original syntax making us to identify easier.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        p {
            font-size: 36px;
        }
        p::first-letter {
            font-size: 24px;
            float: left;
        }
        p::first-line {
            font-weight: bold;
        }  
        blockquote::after {
            content: close-quote;
        }
        blockquote::before {
            content: open-quote;
        }
    </style>
</head>
<body>
    <div>
        <p>
            First Line in First Paragraph<br>
            Second Line in First Paragraph
        </p>
        <p>
            First Line in Second Paragraph<br>
            Second Line in Second Paragraph
        </p>
        <blockquote>
            <p>This is a content of the blockquote.</p>
        </blockquote>
    </div>
</body>
</html>

::first-letter selects the first word from the first paragraph's content.

::first-line selects the first line from the first paragraph's content.

::before creates a open quote symbol at the beginning of content.

::after creates a close quote symbol at the end of content.

Specificity

When we start doing on a web project with lots of design, conflicts of CSS rules are really often. If two (or more) conflicting CSS rules pointing to the same element, there are some basic rules that a browser follows to determine which one is most specific and therefore wins out.

Specificity Calculation

There is a simple concept about specificity. The more Nested the selector is, the higher its specificity is.

.class1 .class2 .class3 {} <--- It owns higher specificity is.
.class1 .class2 {]

Assume that we have the css rules as follow:

p {
    color: red;
}
p {
    color: blue;
}

Obviously, they have the same specificity so the last one will overwrite the previous. Simply to say, those who have the same specificity, the latter wins over.

We often want to design a stylish website. Hence, we have to write tons of CSS rules with complex nested structure. Those complex CSS rules can not easily to be evaluated with an instinct once we have to fix the conflicts. Thankfully, there is a formula which can use to calculate the specificity of.

Here is a figure from CSS tricks.

figure

We can see that the style attributes set to the html elements directly have the highest specificity. Ids get the second highest, classes and pseudo get the third and html element itself has the lowest.

A 4-tuple (a, b, c, d)can be used for counting the specificity of the selectors. "a" counts the style attributes direct to the html element. "b" counts the number of the id. "c" does the statistic for the class and pseudo and "b" counts for the html elements. For example:

p --> (0, 0, 0, 1) <p style="testing">...</p> --> (1, 0, 0, 0) div#test1 --> (0, 0, 1, 1) div#test1.classname1.classname2 --> (0, 1, 2, 1)

So now we all know how to calculate the specificity. But how to compare the tuple's value? We compare the value from the left to the right.

(2, 1, 0, 1) vs (3, 1, 0, 1) --> The right one wins

(1, 0, 0, 0) vs (0, 4, 0, 0) --> The left one wins

We can easily observe that the number has higher priority than its right. When comparing two tuples, we start from the left to right digits. Once there is a tuple wining over, it deserves the highest specificity and stop the comparison.

Play below example code:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        div {
            height: 100px;
        }
        section {
            height: 50px;
        }
        body > div {
            background-color: green;
        }
        div#test1 {
            background-color: blue;
        }
        div#test1.oldclassname {
            text-align: center;
            font-size: 24px;
        }
        div#test1.oldclassname p {
            font-size: 36px;
        }
        .classname.anotherclassname {
            background-color: orange;
        }
        .classname {
            background-color: red;
        }
        .anotherclassname {
            background-color: purple;
        }
    </style>
</head>
<body>
    <div id="test1" class="oldclassname">
        <section class="classname anotherclassname">
            <p>Testing</p>
        </section>
    </div>
    <div id="test2">
        <section class="classname"></section>
    </div>
</body>
</html>

Advance CSS

Shadow

syntax: box-shadow: [horizontal offset] [vertical offset] [blur radius] [optional spread radius] [color];

  1. horizontal offset (required): positive means the shadow will be on the right of the box, a negative offset will put the shadow on the left of the box.

  2. vertical offset (required): a negative value means the box-shadow will be above the box, a positive means the shadow will be below the box.

  3. blur radius (required): if set to 0 the shadow will be sharp, the higher the number, the more blurred it will be, and the further out the shadow will extend. For instance a shadow with 5px of horizontal offset that also has a 5px blur radius will be 10px of total shadow.

  4. spread radius (optional): positive values increase the size of the shadow, negative values decrease the size. Default is 0 (the shadow is same size as blur).

  5. color (required): takes any color value, like hex, named, rgba or hsla. If the color value is omitted, box shadows are drawn in the foreground color (text color). But be aware, older WebKit browsers (pre Chrome 20 and Safari 6) ignore the rule when color is omitted. (From CSS Tricks)

    <title></title> <style type="text/css"> div { display: inline-block; height: 200px; width: 200px; margin: 20px; } #id1 { box-shadow: 10px 20px 0px red; } #id2 { box-shadow: -20px -10px 0px blue; } #id3 { box-shadow: -20px -5px 5px green; } #id4 { box-shadow: -20px -5px 5px 5px orange; } </style>

We can also make inner shadows with simple inset value.

Universal, Child, and Adjacent Selectors

They are three symbolic selectors we can apply in our CSS rules. They are Universal selectors, Child selectors and Adjacent Selectors.

Universal Selector

Universal Selector represented by *(asterisk), can target everything. You can use it to target all the elements inside the html or the elements under the parent with specific css rules.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        * {
            font-size: 40px;
        }
        #id1 * {
            color: green;
        }
    </style>
</head>
<body>
    <div id="id1" class="classname ">
        <a href="http://www.google.com">Google</a>
        <p>I Love Google.</p>
        <p>I am a Googler.</p>
    </div>
    <div id="id2" class="classname">
        <a href="http://www.microsoft.com">M$</a>
    </div>
    <div id="id3" class="classname">
        <a href="http://www.oracle.com">Oracle</a>
    </div>
    <div id="id4" class="classname">
        <a href="http://www.ibm.com">IBM</a>
    </div>
</body>
</html>

Child Selector and Descendant Selector

Child Selector ">" can choose the elements 1 level beneath such as div > p. The p under the div element within 1 level will all be selected.

There is no special syntax for choosing all the descendants. The only thing we need to do is to leave a space between each selector like div p. We can collect all the paragraph elements inside the div in this simple way without considering the levels.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        * {
            font-size: 40px;
        }
        div > a {
            color: green;
        }
        div span {
            color: orange;
        }
        .classname > a > span {
            text-decoration: line-through;
        }
    </style>
</head>
<body>
    <div id="id1">
        <a href="http://www.google.com">Google</a>
        <p>I Love <span>Google.</span></p>
        <p>I am a <span>Googler.</span></p>
    </div>
    <div id="id2" class="classname">
        <a href="http://www.microsoft.com">M<span>$</span></a>
    </div>
    <div id="id3" class="classname">
        <a href="http://www.oracle.com">Oracle</a>
    </div>
    <div id="id4" class="classname">
        <a href="http://www.ibm.com">IBM</a>
    </div>
</body>
</html> 

Adjacent Selector

Adjacent Selector (+) can select the element's sibling next to it for example div + div will choose the div next to the former div

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        * {
            font-size: 40px;
        }
        a + p {
            color: green;
        }
        div span {
            color: orange;
        }
        .classname > a > span {
            text-decoration: line-through;
        }
        #id1 + div {
            background-color: red;
        }
        div + div {
            background-color: purple;
        }
    </style>
</head>
<body>
    <div id="id1">
        <a href="http://www.google.com">Google</a>
        <p>I Love <span>Google.</span></p>
        <p>I am a <span>Googler.</span></p>
    </div>
    <div id="id2" class="classname">
        <a href="http://www.microsoft.com">M<span>$</span></a>
    </div>
    <div id="id3" class="classname">
        <a href="http://www.oracle.com">Oracle</a>
    </div>
    <div id="id4" class="classname">
        <a href="http://www.ibm.com">IBM</a>
    </div>
</body>
</html>

Attribute Selectors: Targeting boxes by their elements’ HTML attributes.

The discussion about the selectors has occupied lots of content in the tutorial. You might get little annoyed that there are too many selectors have to be memorized. I promise you this is the last selector you need to know. Cheer up!

The Attribute Selectors binding to html elements' attributes and become a new type of CSS rules. The pattern of the Attribute Selectors are:

selector[attribute_name] or selector[attribute_name=value]

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        q[title] {
            font-family: sans-serif, serif;
        }
        q[title=bible] {
            color: #999;
        }
        cite[title=bible] {
            font-weight: 700;
            color: #000;
        }
        .test[title=programming] {
            color: #08c;
        }
    </style>
</head>
<body>
    <div>
        <q title="bible"><cite title="bible">Bible</cite> is the words of God.</q><br>
        <q title="programming" class="test">Programming is the life of the developers.</q>
    </div>
</body>
</html>

More Colors

We have learned to use RGB, RGBa, Hexcode and simple name to define the colors. Now We introduce a new type called HSL ( and HSLa)*. HSL is the abbreviation of Hue, Saturation and Lightness. The syntax is:

For HSL: hsl([Hue], [Saturation], [Lightness])

For HSLa: hsla([Hue], [Saturation], [Lightness], [Transparency])

The usages are the same as the other color types and it is not so commonly used from my experience.

At-Rules

Transitions

Although most of use might know that we do static web page with CSS but add dynamic effects with javaScript. The statement is not definitely correct because there are basic dynamic effects that CSS provided.

Transitions can alter the appearance of the elements with smooth steps making the color changes not awkward.

transition: [transition property] [transition-duration] [transition-timing-function] [transition-delay]

  • transition-property: which property (or properties) will transition.
  • transition-duration: how long the transition takes.
  • transition-timing-function: the transition speed takes place at a constant speed or if it accelerates and decelerates. The default value is linear. There are other settings like ease, ease-out, ease-in-out etc. There are more detail about timing functions in MDN
  • transition-delay: how long to wait until the transition takes place.

How to use it? Define a element with before and after state with pseudo classes like :hover, :active and add the transition property to the begin state. Here is an example snippet.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        a:link {
            transition: font-size 5s linear 0s;
            font-size: 14px;
        }
        a:hover {
            font-size: 26px;
        }
        blockquote {
            transition: all 3s ease 0s;
            font-size: 14px;
            color: #08c;

        }
        blockquote:hover {
            font-size: 28px;
            color: #09d;
        }
        #testEaseOut {
            transition: font-size 5s ease-out 0s, margin-left 3s ease-out 0s;
            font-size: 12px;
            margin-left: 0px;
        }
        #testEaseOut:hover {
            font-size: 30px;
            margin-left: 20px;
        }
        #testEaseInOut {
            transition: all 3s ease-in-out 0s;
            font-size: 12px;
            margin-left: 0px;
            color: green;
        }
        #testEaseInOut:hover {
            font-size: 36px;
            margin-left: 20px;
            color: red;
        }
    </style>
</head>
<body>
    <div>
        <a href="http://www.google.com">linear</a>
    </div>
    <div>
        <blockquote>Ease</blockquote>
    </div>
    <div>
        <p id="testEaseOut">Ease-Out</p>
    </div>
    <div>
        <p id="testEaseInOut">Ease-in-Out</p>
    </div>
</body>
</html>

The most interesting one might be the transit function in the #testEaseOut. Observe the syntax structure, we can find out transition allows multiple properties.

Transformations

Transformation properties can let you change the shape elements. There are lots of properties can use:

rotating: Rotate the object with the wanted degrees. Syntax: transform: rotate([n]deg)

skewing: Do the shear mapping to the object. What is the shear Syntax: transform: skew([x]deg, [y]deg);

scaling: Modify the size of the object by scaling the its x and y axes. Syntax: transform: scale([x], [y])

translating: Move the object with the x and displacements from the objects' origin. Syntax: transform: translate([x]px, [y]px). The effect is quite alike position:relative with direction properties.

For more information, there are more mathematical details in MDN

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        div {
            height: 100px;
            width: 100px;
        }
        .wrapper {
            height: 200px;
            margin: 25px 0px;
        }
        .wrapper > div {
            margin-right: auto;
            margin-left: auto;
        }
        #rotating {
            background-color: red;
            transform: rotate(-100deg);
        }
        #skewing {
            background-color: blue;
            transform: skewY(10deg);
        }
        #scaling {
            background-color: orange;
            transform: scale(4, 0.5);
        }
        #translating {
            background-color: green;
            transform: translate(200px, 100px);
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <div id="rotating"></div>
    </div>
    <div class="wrapper">
        <div id="skewing"></div>
    </div>
    <div class="wrapper">
        <div id="scaling"></div>
    </div>
    <div class="wrapper" style="background-color: red;">
        <div id="translating"></div>
    </div>
</body>
</html>

Sometimes we might want to do the multiple transforms to an object. We add the multiple transform properties in one transform code like the below snippet shows:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        div {
            height: 100px;
            width: 100px;
        }
        .wrapper {
            height: 200px;
            margin: 100px auto;
        }
        .wrapper > div {
            margin-right: auto;
            margin-left: auto;
        }
        #mult_1 {
            background-color: red;
            transform: rotate(100deg) scale(1.5, 2);
        }
        #mult_2 {
            background-color: blue;
            transform: scale(1.5, 2) rotate(100deg);
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <div id="mult_1"></div>
    </div>
    <div class="wrapper">
        <div id="mult_2"></div>
    </div>
</body>
</html>

When the result shows up, you might surprise that both are not equal. Why does it happen? The truth is every transform is a matrix calculation. In linear algebra, the different calculation orders bring the different results. (AB != BA)

In CSS, we can compressed those transforms into one matrix: transform: matrix([a], [b], [c], [d], [e], [f]).

One more property we have to aware is the origin. Every kind of transform is relative to its origin. The default value is 0, 0, the top-left point of the box element. We can change the transform property with syntax: transform-origin: [x value], [y value].

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        div {
            height: 100px;
            width: 100px;
        }
        .wrapper {
            height: 200px;
            margin: 100px auto;
        }
        .wrapper > div {
            margin-right: auto;
            margin-left: auto;
        }
        #rotating {
            background-color: red;
            transform: rotate(100deg);
        }
        #o-rotating {
            background-color: blue;
            transform-origin: 20px 0;
            transform: rotate(100deg);
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <div id="rotating"></div>
    </div>
    <div class="wrapper">
        <div id="o-rotating"></div>
    </div>
</body>
</html>

Gradients

Gradients shows the smooth dissolve from one color to another. They are often used to the background design and make the background looks much softer. We can not take the gradient property as a color type. Instead, it's an image without intrinsic dimensions.

CSS provides three major types of the gradients: linear gradient, radical gradient and repeat gradient.

linear-gradient: The color changes along the direction we defined. Syntax: linear-gradient([direction], [color1], [color2], [color3] ...) and linear-gradient([direction in deg], [color1], [color2], [color3] ...)

radical-gradient: The farther to the center, the more different the color is than the origin one's. Syntax: radial-gradient([color1], [color2], ...);

repeat-gradient: There are fixed sized linear or radial gradients repeated as much as needed to fill the entire box. Syntax: repeating-linear-gradient([direction], [color], [color] [width pixels], [color] [width pixels], [color] [width pixels]). repeating-radial-gradient([center of the circle], [color], [color] [width pixels]) .Only the last color's width decides the width of the color square. Really a mystery to me.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        div {
            height: 100px;
            width: 100px;
        }
        .wrapper {
            height: 200px;
            margin: 100px auto;
        }
        .wrapper > div {
            margin-right: auto;
            margin-left: auto;
        }
        #linear-gradient {
            background: 
            linear-gradient(to right,red,orange,yellow,green,blue,indigo,violet);
        }
        #linear-gradient-2 {
            background: 
            linear-gradient(20deg,red,orange,yellow,green,blue,indigo,violet);
        }
        #radial-gradient {
            background: radial-gradient(red, yellow, blue);
        }
        #repeat-linear-gradient {
            background: repeating-linear-gradient(to top left, red, red 5px, white 5px, white 10px);
        }
        #repeat-radial-gradient {
            background: repeating-radial-gradient(circle at 0 0, #eee, #ccc 50px);
        }
        #repeat-radial-gradient-2 {
            background: repeating-radial-gradient(circle at bottom right, #eee, #ccc 50px);
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <div id="linear-gradient"></div>
    </div>
    <div class="wrapper">
        <div id="linear-gradient-2"></div>
    </div>
    <div class="wrapper">
        <div id="radial-gradient"></div>
    </div>
    <div class="wrapper">
        <div id="repeat-linear-gradient"></div>
    </div>
    <div class="wrapper">
        <div id="repeat-radial-gradient"></div>
    </div>
    <div class="wrapper">
        <div id="repeat-radial-gradient-2"></div>
    </div>
</body>
</html>

Media Queries

Media Query are important to layout the specific CSS for different kinds of devices. Especially, there are user using mobiles and tablets everywhere and every mobile company release the products with various screen sizes. To make our websites friendly to different devices users, the media query @meida plays an important role.

For iPhone devices we set up the media like:

/* ----------- iPhone 4 and 4S ----------- */

/* Portrait and Landscape */
@media only screen 
  and (min-device-width: 320px) 
  and (max-device-width: 480px)
  and (-webkit-min-device-pixel-ratio: 2) {

}

/* Portrait */
@media only screen 
  and (min-device-width: 320px) 
  and (max-device-width: 480px)
  and (-webkit-min-device-pixel-ratio: 2)
  and (orientation: portrait) {
}

/* Landscape */
@media only screen 
  and (min-device-width: 320px) 
  and (max-device-width: 480px)
  and (-webkit-min-device-pixel-ratio: 2)
  and (orientation: landscape) {

}

/* ----------- iPhone 5 and 5S ----------- */

/* Portrait and Landscape */
@media only screen 
  and (min-device-width: 320px) 
  and (max-device-width: 568px)
  and (-webkit-min-device-pixel-ratio: 2) {

}

/* Portrait */
@media only screen 
  and (min-device-width: 320px) 
  and (max-device-width: 568px)
  and (-webkit-min-device-pixel-ratio: 2)
  and (orientation: portrait) {
}

/* Landscape */
@media only screen 
  and (min-device-width: 320px) 
  and (max-device-width: 568px)
  and (-webkit-min-device-pixel-ratio: 2)
  and (orientation: landscape) {

}

/* ----------- iPhone 6 ----------- */

/* Portrait and Landscape */
@media only screen 
  and (min-device-width: 375px) 
  and (max-device-width: 667px) 
  and (-webkit-min-device-pixel-ratio: 2) { 

}

/* Portrait */
@media only screen 
  and (min-device-width: 375px) 
  and (max-device-width: 667px) 
  and (-webkit-min-device-pixel-ratio: 2)
  and (orientation: portrait) { 

}

/* Landscape */
@media only screen 
  and (min-device-width: 375px) 
  and (max-device-width: 667px) 
  and (-webkit-min-device-pixel-ratio: 2)
  and (orientation: landscape) { 

}

/* ----------- iPhone 6+ ----------- */

/* Portrait and Landscape */
@media only screen 
  and (min-device-width: 414px) 
  and (max-device-width: 736px) 
  and (-webkit-min-device-pixel-ratio: 3) { 

}

/* Portrait */
@media only screen 
  and (min-device-width: 414px) 
  and (max-device-width: 736px) 
  and (-webkit-min-device-pixel-ratio: 3)
  and (orientation: portrait) { 

}

/* Landscape */
@media only screen 
  and (min-device-width: 414px) 
  and (max-device-width: 736px) 
  and (-webkit-min-device-pixel-ratio: 3)
  and (orientation: landscape) { 

}

We can set up the css rules in the @media ... { [set the rules here] }. Media queries allow us to use logic operator to concat different conditions. screen tell the browsers these css rules are only for the handheld devices. max-device-width and min-device-width are the limitation about the devices' width. orientation is the rule for "the way you hold your devices". There are two value for orientation, the one is portrait and the other is landscape. portrait is valid when you hold your device which width is shorter than its height. By contrast, landscape is valid when the hold device's width is longer than its height.

CSS Border Shaping