CSS

CSS

Blog AdminLeave A CommentOn CSS

Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to simplify the process of making web pages presentable.

CSS handles the look and feel part of a web page. Using CSS, you can control the color of the text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out, what background images or colors are used, layout designs,variations in display for different devices and screen sizes as well as a variety of other effects.

CSS is easy to learn and understand but it provides powerful control over the presentation of an HTML document. Most commonly, CSS is combined with the markup languages HTML or XHTML.

Advantages of CSS

  • CSS saves time − You can write CSS once and then reuse same sheet in multiple HTML pages. You can define a style for each HTML element and apply it to as many Web pages as you want.
  • Pages load faster − If you are using CSS, you do not need to write HTML tag attributes every time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag. So less code means faster download times.
  • Easy maintenance − To make a global change, simply change the style, and all elements in all the web pages will be updated automatically.
  • Superior styles to HTML − CSS has a much wider array of attributes than HTML, so you can give a far better look to your HTML page in comparison to HTML attributes.
  • Multiple Device Compatibility − Style sheets allow content to be optimized for more than one type of device. By using the same HTML document, different versions of a website can be presented for handheld devices such as PDAs and cell phones or for printing.
  • Global web standards − Now HTML attributes are being deprecated and it is being recommended to use CSS. So its a good idea to start using CSS in all the HTML pages to make them compatible to future browsers.

Who Creates and Maintains CSS?

CSS is created and maintained through a group of people within the W3C called the CSS Working Group. The CSS Working Group creates documents called specifications. When a specification has been discussed and officially ratified by the W3C members, it becomes a recommendation.

NOTE − The World Wide Web Consortium, or W3C is a group that makes recommendations about how the Internet works and how it should evolve.

CSS Versions

Cascading Style Sheets level 1 (CSS1) came out of W3C as a recommendation in December 1996. This version describes the CSS language as well as a simple visual formatting model for all the HTML tags.

CSS2 became a W3C recommendation in May 1998 and builds on CSS1. This version adds support for media-specific style sheets e.g. printers and aural devices, downloadable fonts, element positioning and tables.

CSS – Syntax


A CSS comprises of style rules that are interpreted by the browser and then applied to the corresponding elements in your document. A style rule is made of three parts −

  • Selector − A selector is an HTML tag at which a style will be applied. This could be any tag like <h1> or <table> etc.
  • Property − A property is a type of attribute of HTML tag. Put simply, all the HTML attributes are converted into CSS properties. They could be colorborder etc.
  • Value − Values are assigned to properties. For example, colorproperty can have value either red or #F1F1F1 etc.

You can put CSS Style Rule Syntax as follows −

selector { property: value }
Syntax

Example − You can define a table border as follows −

table{ border :1px solid #C00; }

Here table is a selector and border is a property and given value 1px solid #C00 is the value of that property.

You can define selectors in various simple ways based on your comfort. Let me put these selectors one by one.

The Type Selectors

h1 {
   color: #36CFFF; 
}

The Universal Selectors

* { 
   color: #000000; 
}

This rule renders the content of every element in our document in black.

The Descendant Selectors

Suppose you want to apply a style rule to a particular element only when it lies inside a particular element. As given in the following example, style rule will apply to <em> element only when it lies inside <ul> tag.

ul em {
   color: #000000; 
}

The Class Selectors

You can define style rules based on the class attribute of the elements. All the elements having that class will be formatted according to the defined rule.

<!DOCTYPE html>
<html>
<head>
<style>
.center {
  text-align: center;
  color: red;
}
</style>
</head>
<body>

<h1 class="center">Red and center-aligned heading</h1>
<p class="center">Red and center-aligned paragraph.</p> 

</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
p.center {
  text-align: center;
  color: red;
}
</style>
</head>
<body>

<h1 class="center">This heading will not be affected</h1>
<p class="center">This paragraph will be red and center-aligned.</p> 

</body>
</html>

HTML elements can also refer to more than one class.

In the example below, the <p> element will be styled according to class=”center” and to class=”large”:

<!DOCTYPE html>
<html>
<head>
<style>
p.center {
  text-align: center;
  color: red;
}

p.large {
  font-size: 300%;
}
</style>
</head>
<body>

<h1 class="center">This heading will not be affected</h1>
<p class="center">This paragraph will be red and center-aligned.</p>
<p class="center large">This paragraph will be red, center-aligned, and in a large font-size.</p> 

</body>
</html>

The ID Selectors

The id selector uses the id attribute of an HTML element to select a specific element.

The id of an element should be unique within a page, so the id selector is used to select one unique element!

To select an element with a specific id, write a hash (#) character, followed by the id of the element.

<!DOCTYPE html>
<html>
<head>
<style>
#para1 {
  text-align: center;
  color: red;
}
</style>
</head>
<body>

<p id="para1">Hello World!</p>
<p>This paragraph is not affected by the style.</p>

</body>
</html>

Note: An id name cannot start with a number!

Grouping Selectors

If you have elements with the same style definitions, like this:

<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, p {
  text-align: center;
  color: red;
}
</style>
</head>
<body>

<h1>Hello World!</h1>
<h2>Smaller heading!</h2>
<p>This is a paragraph.</p>

</body>
</html>

There are three ways of inserting a style sheet:

  • External style sheet
  • Internal style sheet
  • Inline style

External Style Sheet

With an external style sheet, you can change the look of an entire website by changing just one file!

Each page must include a reference to the external style sheet file inside the <link> element. The <link> element goes inside the <head> section:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

An external style sheet can be written in any text editor. The file should not contain any html tags. The style sheet file must be saved with a .css extension.

Here is how the “mystyle.css” looks:

Internal Style Sheet

An internal style sheet may be used if one single page has a unique style.

Internal styles are defined within the <style> element, inside the <head> section of an HTML page:

<!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>

Inline Styles

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. The style attribute can contain any CSS property.

The example below shows how to change the color and the left margin of a <h1> element:

<!DOCTYPE html>
<html>
<body>

<h1 style="color:blue;margin-left:30px;">This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

Multiple Style Sheets

If some properties have been defined for the same selector (element) in different style sheets, the value from the last read style sheet will be used. 

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<style>
h1 {
  color: orange;
}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>The style of this document is a combination of an external stylesheet, and internal style</p>

</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
  color: orange;
}
</style>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>

<h1>This is a heading</h1>
<p>The style of this document is a combination of an external stylesheet, and internal style</p>

</body>
</html>

However, if the internal style is defined before the link to the external style sheet, the <h1> elements will be “navy”:

CSS Comments

Comments are used to explain the code, and may help when you edit the source code at a later date.

Comments are ignored by browsers.

A CSS comment starts with /* and ends with */. Comments can also span multiple lines:

<!DOCTYPE html>
<html>
<head>
<style>
p {
  color: red;
  /* This is a single-line comment */
  text-align: center;
} 

/* This is
a multi-line
comment */
</style>
</head>
<body>

<p>Hello World!</p>
<p>This paragraph is styled with CSS.</p>
<p>CSS comments are not shown in the output.</p>

</body>
</html>

RGB Value

In HTML, a color can be specified as an RGB value, using this formula:

rgb(red, greenblue)

Each parameter (red, green, and blue) defines the intensity of the color between 0 and 255.

<!DOCTYPE html>
<html>
<body>

<h1 style="background-color:rgb(255, 0, 0);">rgb(255, 0, 0)</h1>
<h1 style="background-color:rgb(0, 0, 255);">rgb(0, 0, 255)</h1>
<h1 style="background-color:rgb(60, 179, 113);">rgb(60, 179, 113)</h1>
<h1 style="background-color:rgb(238, 130, 238);">rgb(238, 130, 238)</h1>
<h1 style="background-color:rgb(255, 165, 0);">rgb(255, 165, 0)</h1>
<h1 style="background-color:rgb(106, 90, 205);">rgb(106, 90, 205)</h1>

<p>In HTML, you can specify colors using RGB values.</p>

</body>
</html>
  • Example for Background color — using a class
<!DOCTYPE html>
<title>My Example</title>
<style>
	.box {
		background: gold;
	}
	div {
		width: 20vw;
		height: 20vh;
		float: left;
		margin: 1vw;
		padding: 1vw;
		border: solid;		
	}
</style>

<div class="box">Class</div>
<div>No class</div>
<div class="box">Class</div>

Chapter – 0 (Introduction to CSS)

HTML is just a skeletal layout of a website. We need CSS to design a website, add styles to it and make it look beautiful.

What is CSS?

CSS stands for cascading style sheets

CSS is optional but it converts an off looking HTML page into a beautiful & responsive website

Installing VS Code Or Notpad++

We will use Microsoft Visual Code as a tool to edit our code. It is very powerful, free, and customizable.

What Learn CSS?

CSS is a much-demanded skill in the world of web development If you are successfully able to master CSS, you can customize your website as per your liking.

Your first line of CSS

Create a .css file inside your directory and add it to your HTML. Add the following line to your CSS

body {
          background-color: red;
}

This will make your page background red.

HTML Refresher

HTML is a bunch of tags used to lay the structure of a page.

HTML id and class attributes

When an HTML element is given an id, it serves as a unique identifier for that element.

On the other hand, when an HTML element is given a class, it now belongs to that class. More than one element can belong to a single class but every element must have a unique id (if assigned).

We can add multiple classes to an element like this,

<div id = ‘first’ class = ‘C1 C2 C3’>
          …
</div>

# first is the unique id

# C1, C2 and C3 are the multiple classes followed by spaces

Three ways to add CSS to HTML

There are 3 ways to add CSS to HTML:

  1. <style> tag : Adding <style> … </style> to HTML
  2. Inline CSS : Adding CSS using style attribute
  3. External CSS : Adding a stylesheet(.css) to HTML using <link> tag

CSS Selectors

A CSS Selector is used to select an HTML element(s) for styling

body {
          color: red;                      #Declaration (property: value)
          background: pink;         #Declaration
}

Copy

#body is the selector

Element Selector

It is used to select an element based on the tag name

For example:

H2 {
          color: blue;
}

Copy

Id Selector

It is used to select an element with a given id

For example:

#first {
          color: white;
          background: black;
}

Copy

Class Selector

It is used to select an element with a given class

For example:

.red {
          background: red;
}

Copy

Important Notes:

  • We can group selectors like this:
h1,h2,h3,div {
          color:blue;           /*h1,h2,h3 and div will be blue*/
}

Copy

  • We can use element class as a selector like this:
p.red {
          color: red;            /*all paragraphs will get color of red*/
}

Copy

  • * can be used as a universal selector to select all the elements
*  {
          margin: 0;
          padding: 0;
}

Copy

  • An inline style will override external and internal styles

Comments in CSS

Comments in CSS are the text which is not parsed and is thus ignored.

Chapter – 1 (Practice Set)
  1. Create a website with a class red div which has a background color of the red and color white.
  2. Create an element with id head and verify that background color works on it as inline, external as well as using style tag CSS.
  3. Create a CSS class one and verify that it works on multiple elements.
  4. Create multiple CSS classes and verify that all of these work on the same element.
  5. Have a look at the MDN CSS reference and try to play around with few key-value CSS rules.

Chapter – 2 (Colors & Backgrounds)

CSS rules are simple key-value pairs with a selector. We can write CSS rules to change color and set backgrounds.

The color property

The CSS color property can be used to set the text color inside an element

p{
          color: red;            /*Text color will be changed to red*/
}

Copy

Similarly, we can set color for different elements

Types of color values

Following are the most commonly used color values in CSS

  1. RGB: Specify color using Red, green, blue values. E.g. rgb(200,98,70)
  2. HEX Code: Specify color using hex code. E.g. #ff7180
  3. HSL: Specify the color using hsl values. E.g. hsl(8,90%,63%)

HSL stands for Hue, saturation, and lightness

The value of the color or background color is provided as any one of these values.

Note: We also have RGBA and HSLA values for color but they are rarely used by beginners. A stand for alpha

The background-color property

The CSS background-color property specifies the background color of a container.

For e.g.

.brown {
          background-color: brown;
}

Copy

The background-image property

Used to set an image as the background

body {
background-image: url(“harry.jpg”)
}

Copy

The image is by default repeated in X & Y directions

The background-repeat property

Can be any of:

  • repeat-x : repeat in the horizontal direction
  • repeat-y : repeat in the vertical direction
  • no-repeat : image not repeat

The background-size property

Can be following:

  • cover : fits & no empty space remains
  • contain : fits & image is fully visible
  • auto : display in original size
  • {{width}} : set width & height will be set automatically
  • {{width}} {{height}} : set width & height

Note: Always check the MDN docs to dissect a given CSS property. Remember, practice will make you perfect

The background-position property

Sets the starting position of a background image

.div1{
          background-position: left top;
}

Copy

The background-attachment property

Defines a scrollable/non-scrollable character of a background image

.div2{
          background-attachment: fixed
}

Copy

The background shorthand

A single property to set multiple background properties

.div3{
          background: red url(‘img.png’) no-repeat fixed right top;
}

Copy

One of the properties can be missing given the others are in order.

  • {{width}} {{height}} : set width & height

Note: Always check the MDN docs to dissect a given CSS property. Remember, practice will make you perfect

The background-position property:

Sets the starting position of a background image

.div1{
          background-position: left top;
}

Copy

The background-attachment property

Defines a scrollable/non-scrollable character of a background image.

.div2{
          background-attachment: fixed;
}

Copy

The background shorthand

A single property to set multiple background properties

.div3{
          background: red url(‘img.png’) no-repeat fixed right top;
}

Copy

One of the properties can be missing given the others are in order.

Chapter – 2 (Practice Set)
  1. Create a dark blue navigation bar with light color items.
  2. Change the color of the main container on your page to dark red.
  3. Create a div and add a background image with a given width and height.
  4. Create a vertical box and add a fixed non-scrolling background to it.
  5. Verify that the background shorthand property works with some of the values skipped.

Chapter – 3 (CSS Box Model)

The CSS box model looks at all the HTML elements as boxes

Setting Width & Height

We can set width and height in CSS as follows

#box {
          height: 70px;
          width: 70px;
}

Copy

Note that the total width/height is calculated as follows:

Total height = height + top/bottom padding + top/bottom border + top/bottom margin

Setting Margin & Padding

We can set margin and padding as follows:

.box{
          margin: 3px;        /* Sets top, bottom, left & right values*/
          padding: 4px;       /* Sets top, bottom, left & right values*/
}

Copy

.boxMain{
          margin: 7px 0px 2px 11px;      /*top, right, bottom, left*/
}

Copy

.boxLast{
          margin: 7px 3px;           /*(top & bottom) (left & right)*/
}

Copy

We can also set individual margins/padding like this:

margin-top: 70px

margin-bottom: 3px

margin-left: 8px

margin-right: 9px

#Same goes with padding also

Setting Borders

We can set the border as follows

.bx{
          border-width: 2px;
          border-style: solid;
          border-color: red;
}

Copy

Shorthand for above codes,

set border: 2px solid red;

Border Radius

We can set border-radius to create rounded borders

.div2{
          border-radius: 7px;
}

Copy

Margin Collapse

When two margins from different elements overlap, the equivalent margin is the greater of the two. This is called margin collapse.

Box Sizing

Determines what out of padding and border is included in elements width and height

Can be content-box or border-box

# Include only content in width/height

.div1{
          box-sizing: border-box;
}

Copy

The content width and height includes, content + padding + border

Chapter – 3 (Practice Set)
  1. Create a website layout. Add a header box, one content box, and one footer.
  2. Add borders and margins to question 1 (website layout)
  3. Did the margin collapse between the content box and footer?
  4. Add the box-sizing property to the content box. What changes did you notice?

Chapter – 4 (Fonts & Display)

The display property

The CSS display property is used to determine whether an element is treated as a block/inline element & the layout used for its children (flexbox/grid/etc.)

display: inline

Takes only the space required by the element. No line breaks before and after. Setting width/height (or margin/padding) not allowed.

display: block

Takes full space available in width and leaves a newline before and after the element

display: inline-block

Similar to inline but setting height, width, margin, and padding is allowed. Elements can sit next to each other

display: none vs visibility: hidden

With display: none, the element is removed from the document flow. Its space is not blocked.

With visibility: hidden, the element is hidden but its space is reserved.

text-align property

Used to set the horizontal alignment of a text

.div1{
          text-align: center;
}

Copy

text-decoration property

Used to decorate the text

Can be overline, line-through, underline, none

text-transform property

Used to specify uppercase and lowercase letters in a text

p.uppercase{
          text-transform: uppercase;
}

Copy

line-height property

Used to specify the space between lines

.Small{
          line-height: 0.7;
}

Font

Font plays a very important role in the look and feel of a website

Font-family

Font family specifies the font of a text.

It can hold multiple values as a “fallback” system

p{
          font-family: “Times new Roman”, monospace;
}

Copy

#always follow the above technique to ensure the correct font of your choice is rendered

Web Safe Fonts

These fonts are universally installed across browsers

How to add Google Fonts

In order to use custom google fonts, go to google fonts then select a style, and finally paste it to the style.css of your page.

Other Font Properties

Some of the other font properties are listed below:

font-size: Sets the size of the font

font-style: Sets the font style

font-variant: Sets whether the text is displayed in small-caps

font-weight: sets the weight of the font

Generic Families

A broad class of similar fonts e.g. Serif, Sans-Serif

Just like when we say fruit, it can be any fruit

 When we say Serif it can be any Serif font

font-family – Specific

Generic family – Generic

Chapter – 4 (Practice Set)
  1. Create the following website layout,
  1. Add a footer with Google Font “Ballu Bhai” to question 1.
  2. Remove the underlines from links in question 1.
  3. Demonstrate the difference between display: none and visibility: hidden using a div.
  4. Change the footer to all uppercase in question 1.

Chapter – 5 (Size, Position & Lists)

There are more units for describing size other than ‘px’

There are rem, em, vw, vh, percentages, etc.

What’s wrong with pixels?

Pixels (px) are relative to the viewing device.

For a device with the size 1920×1080, 1px is 1unit out of 1080/1920.

Relative lengths

These units are relative to the other length property.

Following are some of the most commonly used relative lengths,

  1. em – unit relative to the parent font size

em means “my parent element’s font-size”

  1. rem – unit relative to the root font size (<html> tag)
  2. vw – unit relative to 1% viewport width
  3. vh – unit relative to 1% viewport height
  4. % – unit relative to the parent element

Min/max- height/width property

CSS has a min-height, max-height, and min-width, max-width property.

If the content is smaller than the minimum height, minimum height will be applied.

The position property

Used to manipulate the location of an element

Following are the possible values:

  • static: The default position. top/bottom/left/right/z-index has no effect
  • relative : The top/bottom/left/right/z-index will now work. Otherwise, the element is in the flow of the document like static.
  • absolute: The element is removed from the flow and is relatively positioned to its first non-static ancestor. top/bottom etc. works
  • fixed: Just like absolute except the element is positioned relative to the browser window
  • sticky: The element is positioned based on the user’s scroll position

list-style property

The list-style property is a shorthand for type, position, and image

ul{
          list-style: square inside url(‘harry.jpg’)
}

Copy

# ‘square’ in the above code is the list-style-type, ‘inside’ is the list-style-position and ‘harry.jpg’ is the list-style-image.

z-index property

The z-index property specifies the stack order of an element.

It defines which layer will be above which in case of overlapping elements. 

Chapter – 5 (Practice Set)
  1. Create a responsive navbar using relative lengths.
  2. Create a sticky navbar using the position property.
  3. Demonstrate the use of list-style property using a ul as an example.
  4. Demonstrate the use of z-index using an example.

Chapter – 6 (Flexbox)

Before we look into the CSS flexbox, we will look into float and clear properties.

The float property

float property is simple. It just flows the element towards left/right

The clear property

Used to clear the float. It specifies what elements can float beside a given element

The CSS Flexbox

Aims at providing a better way to layout, align, and distribute space among items in a container.

.container{
          display: flex;                  /*Initialize a flexbox*/
}

Copy

flex-direction property

Defines the direction towards which items are laid.

Can be row (default), row-reverse, column and column-reverse

Flex properties for parent (flex container)

Following are the properties for the flex parent:

  1. flex-wrap: Can be wrap, nowrap, wrap-reverse. Wrap items as needed with this property
  2. justify-content: Defines alignment along the main axis
  3. align-items: Defines alignment along the cross axis
  4. align-content: Aligns a flex container’s lines when there is extra space in the cross axis

Flex properties for the children (flex items)

Following are the properties for the flex children:

  1. order: Controls the order in which the items appear in the flex container
  2. align-self: Allows default alignment to be overridden for the individual flex items
  3. flex-grow: Defines the ability for a flex item to grow
  4. flex-shrink: Specifies how much a flex item will shrink relative to the rest of the flex items
Chapter – 6 (Practice Set)
  1. Create a layout of your choice using float.
  2. Create the same layout in question 1 using flexbox.
  3. Create the following navigation bar using flexbox

4. Create the following layout using flexbox,

Chapter – 7 (CSS Grid & Media Queries)

A CSS grid can be initialized using:

.container {
          display: grid;
}

Copy

All direct children automatically become grid items

The grid-column-gap property

Used to adjust the space between the columns of a CSS grid

The grid-row-gap property

Used to adjust the space between the rows of a CSS grid

The grid-gap property

Shorthand property for grid-row-gap & grid-column-gap

.container {
          display: grid;
          grid-gap: 40px 100px;            /*40px for row and 100px for column*/
}

Copy

Note: For a single value of grid-gap, both row and column gaps can be set in one value.

Following are the properties for grid container:

  1. The grid-template-columns property can be used to specify the width of columns
.container {
          display: grid;
          grid-template-columns: 80px 120px auto;
}

Copy

  1. The grid-template-rows property can be used to specify the height of each row
.container {
          display: grid;
          grid-template-rows: 70px 150px;
}

Copy

  1. The justify-content property is used to align the whole grid inside the container.
  2. The align-content property is used to vertically align the whole grid inside the container.

Following are the properties for grid item:

  1. The grid-column property defines how many columns an items will span.
.grid-item{
          grid-column: 1/5;
}

Copy

  1. The grid-row property defines how many rows an item will span.
  2. We can make an item to start on column 1 and space 3 columns like this:
.item{
          grid-column: 1/span 3;
}

Copy

CSS Media Queries

Used to apply CSS only when a certain condition is true.

Syntax:

@media only screen and (max-width: 800px) {
                   body{
                             background: red;
                            }
          }

Copy

Chapter – 7 (Practice Set)
  1. Create a header with content using CSS grid.
  2. Create the layouts created in chapter-6 practice set using CSS grid.
  3. Create a webpage that is green on large devices, red on medium, and yellow on small devices.

Chapter – 8 (Transforms, Transitions & Animations)

Transforms are used to rotate, move, skew or scale elements. They are used to create a 3-D effect.

The transform property

Used to apply a 2-D or 3-D transformation to an element

The transform-origin property

Allows to change the position of transformed elements

2D transforms – can change x & y-axis

3D transforms – can change Z-axis as well

CSS 2D transform methods

You can use the following 2-D transforms in CSS:

  1. translate()
  2. rotate()
  3. scaleX()
  4. scaleY()
  5. skew()
  6. matrix()
  7. scale()

CSS 3D transform methods

  1. rotateX()
  2. rotateY()
  3. rotateZ()

CSS Transitions

The transition property

The transition property is used to add a transition in CSS.

Following are the properties used for CSS transition:

  1. transition-property: The property you want to transition
  2. transition-duration: Time for which you want the transition to apply
  3. transition-timing-function: How you want the property to transition
  4. transition-delay: Specifies the delay for the transition

All these properties can be set using a single shorthand property

Syntax:

transition: property duration timing-function delay;
transition: width 35 ease-in 25;

Copy

Transitioning multiple properties

We can transition multiple properties as follows:

transition: opacity 15 ease-out 15, transform 25 ease-in;

Copy

CSS Animations

Used to animate CSS properties with more control.

We can use the @keyframes rule to change the animation from a given style to a new style.

@keyframes harry {
          from { width: 20px; }              /*Can change multiple properties*/
          to { width: 31px; }
}

Copy

Properties to add Animations

Following are the properties used to set animation in CSS:

  1. animation-name: name of the animation
  2. animation-duration: how long does the animation run?
  3. animation-timing-function: determines speed curve of the animation
  4. animation-delay: delay for the start of an animation
  5. animation-iteration-count: number of times an animation should run
  6. animation-direction: specifies the direction of the animation

Animation Shorthand

All the animation properties from 1-6 can be applied like this:

animation: harry 65 linear 15 infinite reverse;

Copy

Using percentage value states with animation

We can use % values to indicate what should happen when a certain percent of animation is completed

@keyframes harry {
          0% {
                   width: 20px;
                   }
          50% {
                   width: 80px;
                   }
          100% {
                   width: 200px;
                   }
          }

Copy

  • Can add as many intermediate properties as possible
Chapter – 8 (Practice Set)
  1. Create a thin progress bar animation for a website.
  2. Create the same progress bar using transition.
  3. Create a rotating image animation using CSS.
  4. Create a slider with 3 images using CSS.
  • Example for Background color — using an ID
<!DOCTYPE html>
<title>My Example</title>
<style>
	#unique {
		background: gold;
	}
	div {
		width: 20vw;
		height: 20vh;
		float: left;
		margin: 1vw;
		padding: 1vw;
		border: solid;		
	}
	p {
		clear: both;
	}
</style>

<div id="unique">ID</div>
<div>No ID</div>

<p>Note that only one element on the page can use a given ID. To style multiple elements, use a class.</p>

Sample website code

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="style.css" />
        
        <title>Zozor - Travel diaries</title>
    </head>
    
    
        <div id="main_wrapper">
            <header>
                <div id="main_title">
                    <img src="images/zozor_logo.png" alt="Zozor logo" id="logo" />
                    <h1>Zozor</h1>
                    <h2>Travel diaries</h2>
                </div>
                
                <nav>
                    <ul>
                        <li><a href="#">Home</a></li>
                        <li><a href="#">Blog</a></li>
                        <li><a href="#">Resume</a></li>
                        <li><a href="#">Contact</a></li>
                    </ul>
                </nav>
            </header>
            
            <div id="banner_image" class="animatedBox">
                <div id="banner_description">
                    Reflections on my holiday in the United States...
                    <a href="#" class="red_button">See article <img src="images/small_arrow.png" alt="" /></a>
                </div>
            </div>
            
            <section>
                <article>
                    <h1><img src="images/pin.png" alt="Travel category" class="cat_icon" />I'm a great traveller</h1>
                    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam nec sagittis massa. Nulla facilisi. Cras id arcu lorem, et semper purus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Duis vel enim mi, in lobortis sem. Vestibulum luctus elit eu libero ultrices id fermentum sem sagittis. Nulla imperdiet mauris sed sapien dignissim id aliquam est aliquam. Maecenas non odio ipsum, a elementum nisi. Mauris non erat eu erat placerat convallis. Mauris in pretium urna. Cras laoreet molestie odio, consequat consequat velit commodo eu. Integer vitae lectus ac nunc posuere pellentesque non at eros. Suspendisse non lectus lorem.</p>
                    <p>Vivamus sed libero nec mauris pulvinar facilisis ut non sem. Quisque mollis ullamcorper diam vel faucibus. Vestibulum sollicitudin facilisis feugiat. Nulla euismod sodales hendrerit. Donec quis orci arcu. Vivamus fermentum magna a erat ullamcorper dignissim pretium nunc aliquam. Aenean pulvinar condimentum enim a dignissim. Vivamus sit amet lectus at ante adipiscing adipiscing eget vitae felis. In at fringilla est. Cras id velit ut magna rutrum commodo. Etiam ut scelerisque purus. Duis risus elit, venenatis vel rutrum in, imperdiet in quam. Sed vestibulum, libero ut bibendum consectetur, eros ipsum ultrices nisl, in rutrum diam augue non tortor. Fusce nec massa et risus dapibus aliquam vitae nec diam.</p>
                    <p>Phasellus ligula massa, congue ac vulputate non, dignissim at augue. Sed auctor fringilla quam quis porttitor. Praesent vitae dignissim magna. Pellentesque quis sem purus, vel elementum mi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas consectetur euismod urna. In hac habitasse platea dictumst. Quisque tincidunt porttitor vestibulum. Ut iaculis, lacus at molestie lacinia, ipsum mi adipiscing ligula, vel mollis sem risus eu lectus. Nunc elit quam, rutrum ut dignissim sit amet, egestas at sem.</p>
                </article>
                <aside>
                    <h1>About the author</h1>
                    <img src="images/arrow.png" alt="" id="arrow" />
                    <p id="zozor_picture" ><img src="images/zozor.png" alt="Zozor Picture" /></p>
                    <p>Let me introduce myself: My name's Zozor. I was born on 23 November 2005.</p>
                    <p>A bit meager, is it not? This is why I've now decided to write my biography to let my readers know who I really am.</p>
                    <p><img src="images/facebook.png" alt="Facebook" /><img src="images/twitter.png" alt="Twitter" /><img src="images/vimeo.png" alt="Vimeo" /><img src="images/flickr.png" alt="Flickr" /><img src="images/rss.png" alt="RSS" /></p>
                </aside>
            </section>
            
            <footer>
                <div id="tweet">
                    <h1>My last tweet</h1>
                    <p>Hee-haw!</p>
                    <p>12/05 23:12</p>
                </div>
                <div id="my_pictures">
                    <h1>My pictures</h1>
                    <p><img src="images/pic1.jpg" alt="Picture" /><img src="images/pic2.jpg" alt="Picture" /><img src="images/pic3.jpg" alt="Picture" /><img src="images/pic4.jpg" alt="Picture" /></p>
                </div>
                <div id="my_friends">
                    <h1>My friends</h1>
                    <ul>
                        <li><a href="#">Pupi the rabbit</a></li>
                        <li><a href="#">Mr Baobab</a></li>
                        <li><a href="#">Kaiwaii</a></li>
                        <li><a href="#">Perceval.eu</a></li>
                    </ul>
                    <ul>
                        <li><a href="#">Ji</a></li>
                        <li><a href="#">Super cucumber</a></li>
                        <li><a href="#">Prince</a></li>
                        <li><a href="#">Mr Fan</a></li>
                    </ul>
                </div>
            </footer>
        </div>
    </body>
</html>

Sample Website Style.css Code

/* Define custom fonts */

@font-face
{
    font-family: 'Amazing Kids';
    font-weight: normal;
    font-style: normal;
}

@font-face
{
    font-family: 'Amazing Kids';
    
    font-weight: normal;
    font-style: normal;
}
.animatedBox {
  width: 900px;
  height: 200px;
  text-align: center;
  font: 24px sans-serif;
  color: white;
  text-shadow: 0px 0px 12px black;
  background-image: url('images/sanfrancisco.jpg');
  background-position: bottom left;
  border: 1px solid black;
  animation: moveBg 10s ease 1s 2 alternate none;
}

@keyframes moveBg {
	100% {
	  background-position: bottom right;
	}
}

/* Main elements of the page */

body
{
    background: url('images/yellow_background.png');
    font-family: 'Trebuchet MS', Arial, sans-serif;
    color: #181818;
}

#main_wrapper
{
    width: 900px;
    margin: auto;
}

section h1, footer h1, nav a
{
    font-family: Dayrom, serif;
    font-weight: normal;
    text-transform: uppercase;
}

/* Header */

header
{
    background: url('images/line.png') repeat-x bottom;
}

#main_title
{
    display: inline-block;
}

header h1
{
    font-family: 'BallparkWeiner', serif;
    font-size: 2.5em;
    font-weight: normal;
}

#logo, header h1
{
    display: inline-block;
    margin-bottom: 0px;
}

header h2
{
    font-family: Dayrom, serif;
    font-size: 1.1em;
    margin-top: 0px;
    font-weight: normal;
}

/* Navigation */

nav
{
    display: inline-block;
    width: 740px;
    text-align: right;
}

nav ul
{
    list-style-type: none;
}

nav li
{
    display: inline-block;
    margin-right: 15px;
}

nav a
{
    font-size: 1.3em;
    color: #181818;
    padding-bottom: 3px;
    text-decoration: none;
}

nav a:hover
{
    color: #760001;
    border-bottom: 3px solid #760001;
}

/* Banner */

#banner_image
{
    margin-top: 15px;
    height: 200px;
    border-radius: 5px;
    background: url('images/sanfrancisco.jpg') no-repeat;
    position: relative;
    box-shadow: 0px 4px 4px #1c1a19;
    margin-bottom: 25px;
}

#banner_description
{
    position: absolute;
    bottom: 0;
    border-radius: 0px 0px 5px 5px;
    width: 99.5%;
    height: 33px;
    padding-top: 15px;
    padding-left: 4px;
    background-color: rgb(24,24,24); /* Old browsers will read this */
    background-color: rgba(24,24,24,0.8); /* New browsers will read this */
    color: white;
    font-size: 0.8em;
    
}

.red_button
{
    display: inline-block;
    height: 25px;
    position: absolute;
    right: 5px;
    bottom: 5px;
    background: url('images/red_background.png') repeat-x;
    border: 1px solid #760001;
    border-radius: 5px;
    font-size: 1.2em;
    text-align: center;
    padding: 3px 8px 0px 8px;
    color: white;
    text-decoration: none;
}

.red_button img
{
    border: 0;
}

/* Body */

article, aside
{
    display: inline-block;
    vertical-align: top;
    text-align: justify;
}

article
{
    width: 625px;
    margin-right: 15px;
}

.cat_icon
{
    vertical-align: middle;
    margin-right: 8px;
}

article p
{
    font-size: 0.8em;
}

aside
{
    position: relative;
    width: 235px;
    background-color: #706b64;
    box-shadow: 0px 2px 5px #1c1a19;
    border-radius: 5px;
    padding: 10px;
    color: white;
    font-size: 0.9em;
}

#arrow
{
    position: absolute;
    top: 100px;
    left: -12px;
}

#zozor_picture
{
    text-align: center;
}

#zozor_picture img
{
    border: 1px solid #181818;
}

aside img
{
    margin-right: 5px;
}

/* Footer */

footer
{
    background:  url('images/top.png') no-repeat top center, url('images/line.png') repeat-x top, url('images/shadow.png') repeat-x top;
    padding-top: 25px;
}

footer p, footer ul
{
    font-size: 0.8em;
}

footer h1
{
    font-size: 1.1em;
}

#tweet, #my_pictures, #my_friends
{
    display: inline-block;
    vertical-align: top;
}

#tweet
{
    width: 28%;
}

#my_pictures
{
    width: 35%;
}

#my_friends
{
    width: 31%;
}

#my_pictures img
{
    border: 1px solid #181818;
    margin-right: 2px;
}

#my_friends ul
{
    display: inline-block;
    vertical-align: top;
    margin-top: 0;
    width: 48%;
    list-style-image: url('images/external_link.png');
    padding-left: 2px;
}

#my_friends a
{
    text-decoration: none;
    color: #760001;
}


/* Applied to older versions of Internet Explorer */

/* To activate inline-block positioning */

.old_ie #main_title, .old_ie #logo, .old_ie header h1, .old_ie nav, .old_ie nav li, .old_ie .red_button, .old_ie article, .old_ie aside, .old_ie #tweet, .old_ie #my_pictures, .old_ie #my_friends, .old_ie #my_friends ul
{
    display: inline;
    zoom: 1;
}

/* Some other tweaks */

.old_ie section h1, .ie8 section h1
{
    font-size: 1.1em;
}

.old_ie footer div, .ie8 footer div
{
    margin-top: 30px;
    background: url('images/line.png') repeat-x top;
}

Leave a Reply

Your email address will not be published. Required fields are marked *