CodeIgniter and HMVC SetUp Tutorial

  1. Download and unzip the framework from site
  2. Paste it in htdocs folder in xampp
  3. Download HMVC files from website (google for HMVC in codeingiter)
  4. Paste files in config folder and third party folder
  5. Create module folders in application folder of codeigniter
  6. Remove index.php file by adding .htaccess file

On Page SEO Tutorial

Table of Contents – On-Page SEO Guide

WordPress Speed Optimization

Our WordPress speed optimization guide is quite possibly one of the most thorough guides on improving the load time of WordPress websites. This section is geared towards intermediate users, i.e. you are not a beginner you definitely know your way around WordPress, you know HTML but not an expert. We’ve gone way above and beyond the obvious, including sections such as:

  • pre-fetching and pre-rendering
  • domain sharding
  • database optimization
  • cahcing
  • compression
  • and more!

E-A-T & YMYL

We started hearing about E-A-T and YMYL in 2015 when Google launched their latest version of the Google Quality Rater guidelines. Since then, a lot has happened. Google has essentially baked E-A-T and YMYL into the core algorihm and it is now considered “must have” knowledge.

  • expertise
  • authority
  • trust
  • Your Money or Your Life type of sites
  • how it all fits together
  • some solid examples

Image Optimization

Many SEO’s believe that they are optimizing their images, but don’t realize they are missing the boat entirely. In our guide to image optimization for SEO we outline the most essential tactics for image optimization. Image optimization isn’t just inserting an alt tag, there are over a dozen more factors when it comes to image optimization!

  • image alts and description tags
  • image size
  • organizing your images
  • image format
  • Google Images

Internal Linking

For many SEO’s internal linking is a random act carried out throughout their day. Professional SEO’s know that internal linking is a very deliberate strategy that can change the entire direction of a website. Aspects of internal linking include:

  • internal links for navigation
  • using widgets like “related posts”
  • finding your most inner-linked pages using Google Search Console
  • and more!

Some say internal linking is one of the most important aspects of on-page SEO, and we believe that as well!

Robots.txt and Meta Robots

The robots.txt file and the meta robots tag both act as traffic signals for search engine crawlers. Get to know them, and you can begin to understand how crawlers such as Googlebot move throughout your website.

  • Robots.txt formatting
  • What is robots.txt
  • the meta robots tag
  • meta robots tag parameters

Server Optimization

If you are an SEO and don’t know about servers, then it is time to go back to basics. At the very least we recommend having a basic understanding of the points contained within this guide.

  • server status codes
  • 404’s, 301’s and more
  • hosting and CDN’s
  • subdomains and subfolders

URL Structure and Permalinks

Having an optimized URL structure and permalinks is mandatory in the 2020version of SEO. Both humans and robots don’t want to read gibberish URL’s and parameters. In this guide we show you how to make your URL’s more user friendly, and how to optimize them for SEO.

  • relative vs absolute URL’s
  • URL’s in the SERPs
  • wording / keywords in URLs
  • breadcrumbs
  • redirects

Meta Description Optimization

Just updated! As of this past December Google made a major change to the SERPs and how they display their own descriptions. At the core of any SEO campaign are meta descriptions. In this section we’ll teach you what they are, how to write them, how to measure them and so much more. In 2020 meta descriptions have grown in importance now more than ever. While they aren’t officially a ranking factor, they play a huge part in SEO with the fact that Google has been known to use them within the search engine results page.

  • meta description length
  • meta description best practices
  • are meta descriptions a ranking signal?
  • examples of meta descriptions

Title Tag Optimization

Like meta descriptions, title tags are a core part of any SEO campaign. In addition to teaching you how to write them and optimize for SEO, we’ll show you some real world examples as well. Title tags are not only an important part of on page search engine optimization, they are extremely important part of user experience as well.

  • title tag lengths
  • examples of title tags
  • bulk title tag analysis
  • title tag optimization

Headings / H Tags

Learn more about how headings or “h tags” play a role in on-page SEO and how to properly implement them without going overboard. More than any other style of text, the H tag stands out the most, learn to use them to your advantage.

  • H tags relevance in SEO
  • H tag optimization
  • h1 through h6

Structured Data and Schema Markup

Quite possibly one of the hottest topics right now in SEO is structured data and schema markup. Since the onset of Google’s Knowledge Graph SEO’s around the globe have been in a frenzy marking up their websites with semantic markup. In this section of our on-page tutorial guide we’ll give you the basics and how to get started using structured data in your website.

With the introduction of JSON-LD, the new kid on the schema markup block SEO’s now have the ability to embed structured data into a website, without having to “attach” it to a particular website.

  • json-ld vs microdata
  • what is structured data?
  • other types of structured data e.g. OGP and Twitter Cards

Anchor Text Optimization

SEO is all about backlinks, right? Backlinks, backlinks, backlinks! Well, anchor text is the human readable part of a link, and is oh-so-essential in any on-page SEO strategy. Get to know and love anchor text and it will love you back.

Anchor text is not only a primary element of SEO, but also a secondary as well. For instance anchor text plays a huge part in keyword prominence, internal linking, and more!

  • over optimization of anchor text
  • analyzing anchor text
  • anchor text distribution
  • rel=nofollow and anchor text

Blogging

Blogging plays such an important role in SEO we dedicated an entire section all to itself. In this section we’ll show you how to get started with blogging and how to optimize your blog for search engine friendliness. There are many different ways to blog, examples include:

  • general updates about your company
  • posting newsletters
  • fun facts about your industry
  • articles about your industry
  • and more!

Responsiveness and Mobile Friendliness

The mobile revolution is here, and SEO plays a major part in it, but it’s not enough just to have a mobile or responsive website. You’ll learn how to optimize your responsive website for SEO, common SEO pitfalls and how responsive and mobile websites work. Google doesn’t often come out and say “this is a ranking factor” but in 2016 Google stated that having a mobile friendly website may in fact give you a boost in the search engine rankings. With that, we must pay close attention to this!

  • responsive vs mobile friendly
  • common mistakes
  • mobile index

Content

We won’t bore you with cliches like “content is king” but instead dive right into how content will help your SEO efforts and how to avoid common pitfalls that might cause a Google algorithm adjustment or penalty. Content plays a vital role in on-page SEO, it is base for which all SEO depends on. Content can come in the form of pure text, images, videos, and more.

  • types of content
  • quality over quantity
  • Google Panda
  • content formats

Page Speed and SEO

One of the first things we look at when optimizing a new website is how fast it loads. This is another aspect of SEO that Google has publicly confirmed is a factor when it ranks websites, so with that it should not be ignored. Page speed and moreover site speed as a whole is one of the most important factors of on-page SEO that we focus on as an agency. Many times we’ll spend days optimizing a website for speed.

  • page speed vs website speed
  • analyzing your website
  • gzip compression
  • reducing requests

Keywords: Proximity, Density and Prominence

Close your eyes and what is the first word that comes to mind when I say SEO. Was it “keywords?” If so your just like most other SEO’s, and rightfully so! It is a huge part of on-page SEO and a lot to take in, so grab a coffee and get comfortable.

  • keyword proximity
  • keyword density
  • keyword prominence

HTTPS / SSL

One of the few actually confirmed ranking factors, Google recently announced that having an HTTPS enabled website could in fact boost your rankings in the search engines. But it’s not that simple, there are a few on-page SEO caveats you should know as an SEO.

  • HTTPS / SSL as a ranking factor
  • SSL and on-page factors
  • common mistakes

Domain Names

Choosing a domain name is a near permanent decision, and one that shouldn’t be taken lightly. Learn more about domain names and SEO, EMD’s, new gTLD’s and so much more. While having a good domain name won’t make or break your entire SEO strategy, it could help move things along in other ways.

  • exact match domains
  • moving domains
  • gTLD’s

Social Sharing and Social Media

While social media is another way to generate traffic in and of itself, it also plays a vital role in search engine optimization. In this section we’ll learn how to use social media to your advantage and the role it plays in SEO.

  • social sharing
  • social reputation
  • social media and on-page SEO

HTML, CSS and JavaScript

Another mandatory aspect of on-page SEO that all aspiring SEO’s should learn is HTML, CSS and JavaScript. These are the building blocks of the web, and an essential part of search engine optimization.

  • validated HTML / CSS JavaScript and Googlebot

Rel=Canonical Tag

The rel=canonical tag is a simple solution to the very complex problem of duplicate content within a website framework. In this section we’ll talk about how to implement it, when to implement it and some common pitfalls.

  • the definition of rel=canonical
  • cross domain canonicalization
  • canonical HTTP headers

Advertising

Learn more about the role that advertisements play in SEO and how you can minimize the risk of being penalized by Google. Advertisements are a huge part of the web and part of Google’s business model, but there is a fine line to walk when implementing ads on your website. In this section we talk more about embedding ads in your site, and how that plays a role in on-page SEO.

  • advertising and on-page SEO
  • ads and Google rankings
  • Google Panda

XML and Website Sitemaps

An XML sitemap can help create a map for Google to follow when crawling your website. Learn the difference between an XML sitemap and a website sitemap, and why we recommend having both for your website.

  • XML sitemaps vs website sitemaps
  • Google Search Console
  • Image and Video Sitemaps

jQuery Tutorial

jQuery Tutorial

Example

$(document).ready(function(){
  $(“p”).click(function(){
    $(this).hide();
  });
});

Example

$(document).ready(function(){
  $(“button”).click(function(){
    $(“p”).hide();
  });
});

Example

$(document).ready(function(){
  $(“button”).click(function(){
    $(“#test”).hide();
  });
});

jQuery is tailor-made to respond to events in an HTML page.


What are Events?

All the different visitors’ actions that a web page can respond to are called events.

An event represents the precise moment when something happens.

Examples:

  • moving a mouse over an element
  • selecting a radio button
  • clicking on an element

The term “fires/fired” is often used with events. Example: “The keypress event is fired, the moment you press a key”.

Here are some common DOM events:

Mouse EventsKeyboard EventsForm EventsDocument/Window Events
clickkeypresssubmitload
dblclickkeydownchangeresize
mouseenterkeyupfocusscroll
mouseleave blurunload

jQuery hide() and show()

With jQuery, you can hide and show HTML elements with the hide() and show() methods:

Example

$(“#hide”).click(function(){
  $(“p”).hide();
});

$(“#show”).click(function(){
  $(“p”).show();
});

jQuery Fading Methods

With jQuery you can fade an element in and out of visibility.

jQuery has the following fade methods:

  • fadeIn()
  • fadeOut()
  • fadeToggle()
  • fadeTo()

jQuery fadeIn() Method

The jQuery fadeIn() method is used to fade in a hidden element.

Syntax:

$(selector).fadeIn(speed,callback);

The optional speed parameter specifies the duration of the effect. It can take the following values: “slow”, “fast”, or milliseconds.

The optional callback parameter is a function to be executed after the fading completes.

The following example demonstrates the fadeIn() method with different parameters:

Example

$(“button”).click(function(){
  $(“#div1”).fadeIn();
  $(“#div2”).fadeIn(“slow”);
  $(“#div3”).fadeIn(3000);
});

jQuery Sliding Methods

With jQuery you can create a sliding effect on elements.

jQuery has the following slide methods:

  • slideDown()
  • slideUp()
  • slideToggle()

jQuery slideDown() Method

The jQuery slideDown() method is used to slide down an element.

Syntax:

$(selector).slideDown(speed,callback);

The optional speed parameter specifies the duration of the effect. It can take the following values: “slow”, “fast”, or milliseconds.

The optional callback parameter is a function to be executed after the sliding completes.

The following example demonstrates the slideDown() method:

Example

$(“#flip”).click(function(){
  $(“#panel”).slideDown();
});

jQuery Animations – The animate() Method

The jQuery animate() method is used to create custom animations.

Syntax:

$(selector).animate({params},speed,callback);

The required params parameter defines the CSS properties to be animated.

The optional speed parameter specifies the duration of the effect. It can take the following values: “slow”, “fast”, or milliseconds.

The optional callback parameter is a function to be executed after the animation completes.

The following example demonstrates a simple use of the animate() method; it moves a <div> element to the right, until it has reached a left property of 250px:

Example

$(“button”).click(function(){
  $(“div”).animate({left: ‘250px’});
});

jQuery stop() Method

The jQuery stop() method is used to stop an animation or effect before it is finished.

The stop() method works for all jQuery effect functions, including sliding, fading and custom animations.

Syntax:

$(selector).stop(stopAll,goToEnd);

The optional stopAll parameter specifies whether also the animation queue should be cleared or not. Default is false, which means that only the active animation will be stopped, allowing any queued animations to be performed afterwards.

The optional goToEnd parameter specifies whether or not to complete the current animation immediately. Default is false.

So, by default, the stop() method kills the current animation being performed on the selected element.

The following example demonstrates the stop() method, with no parameters:

Example

$(“#stop”).click(function(){
  $(“#panel”).stop();
});

A callback function is executed after the current effect is 100% finished.


jQuery Callback Functions

JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors.

To prevent this, you can create a callback function.

A callback function is executed after the current effect is finished.

Typical syntax: $(selector).hide(speed,callback);

Examples

The example below has a callback parameter that is a function that will be executed after the hide effect is completed:

Example with Callback

$(“button”).click(function(){
  $(“p”).hide(“slow”, function(){
    alert(“The paragraph is now hidden”);
  });
});

With jQuery, you can chain together actions/methods.

Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.


jQuery Method Chaining

Until now we have been writing jQuery statements one at a time (one after the other).

However, there is a technique called chaining, that allows us to run multiple jQuery commands, one after the other, on the same element(s).

Tip: This way, browsers do not have to find the same element(s) more than once.

To chain an action, you simply append the action to the previous action.

The following example chains together the css(), slideUp(), and slideDown() methods. The “p1” element first changes to red, then it slides up, and then it slides down:

Example

$(“#p1”).css(“color”, “red”).slideUp(2000).slideDown(2000);

Get Content – text(), html(), and val()

Three simple, but useful, jQuery methods for DOM manipulation are:

  • text() – Sets or returns the text content of selected elements
  • html() – Sets or returns the content of selected elements (including HTML markup)
  • val() – Sets or returns the value of form fields

The following example demonstrates how to get content with the jQuery text() and html() methods:

Example

$(“#btn1”).click(function(){
  alert(“Text: ” + $(“#test”).text());
});
$(“#btn2”).click(function(){
  alert(“HTML: ” + $(“#test”).html());
});

Set Content – text(), html(), and val()

We will use the same three methods from the previous page to set content:

  • text() – Sets or returns the text content of selected elements
  • html() – Sets or returns the content of selected elements (including HTML markup)
  • val() – Sets or returns the value of form fields

The following example demonstrates how to set content with the jQuery text(), html(), and val() methods:

Example

$(“#btn1”).click(function(){
  $(“#test1”).text(“Hello world!”);
});
$(“#btn2”).click(function(){
  $(“#test2”).html(“<b>Hello world!</b>”);
});
$(“#btn3”).click(function(){
  $(“#test3”).val(“Dolly Duck”);
});

With jQuery, it is easy to add new elements/content.


Add New HTML Content

We will look at four jQuery methods that are used to add new content:

  • append() – Inserts content at the end of the selected elements
  • prepend() – Inserts content at the beginning of the selected elements
  • after() – Inserts content after the selected elements
  • before() – Inserts content before the selected elements

jQuery append() Method

The jQuery append() method inserts content AT THE END of the selected HTML elements.

Example

$(“p”).append(“Some appended text.”);

jQuery prepend() Method

The jQuery prepend() method inserts content AT THE BEGINNING of the selected HTML elements.

Example

$(“p”).prepend(“Some prepended text.”);

Add Several New Elements With append() and prepend()

In both examples above, we have only inserted some text/HTML at the beginning/end of the selected HTML elements.

However, both the append() and prepend() methods can take an infinite number of new elements as parameters. The new elements can be generated with text/HTML (like we have done in the examples above), with jQuery, or with JavaScript code and DOM elements.

In the following example, we create several new elements. The elements are created with text/HTML, jQuery, and JavaScript/DOM. Then we append the new elements to the text with the append() method (this would have worked for prepend() too) :

Example

function appendText() {
  var txt1 = “<p>Text.</p>”;               // Create element with HTML 
  var txt2 = $(“<p></p>”).text(“Text.”);   // Create with jQuery
  var txt3 = document.createElement(“p”);  // Create with DOM
  txt3.innerHTML = “Text.”;
  $(“body”).append(txt1, txt2, txt3);      // Append the new elements
}

jQuery after() and before() Methods

The jQuery after() method inserts content AFTER the selected HTML elements.

The jQuery before() method inserts content BEFORE the selected HTML elements.

Example

$(“img”).after(“Some text after”);

$(“img”).before(“Some text before”);

Add Several New Elements With after() and before()

Also, both the after() and before() methods can take an infinite number of new elements as parameters. The new elements can be generated with text/HTML (like we have done in the example above), with jQuery, or with JavaScript code and DOM elements.

In the following example, we create several new elements. The elements are created with text/HTML, jQuery, and JavaScript/DOM. Then we insert the new elements to the text with the after() method (this would have worked for before() too) :

Example

function afterText() {
  var txt1 = “<b>I </b>”;                    // Create element with HTML 
  var txt2 = $(“<i></i>”).text(“love “);     // Create with jQuery
  var txt3 = document.createElement(“b”);    // Create with DOM
  txt3.innerHTML = “jQuery!”;
  $(“img”).after(txt1, txt2, txt3);          // Insert new elements after <img>
}

With jQuery, it is easy to remove existing HTML elements.


Remove Elements/Content

To remove elements and content, there are mainly two jQuery methods:

  • remove() – Removes the selected element (and its child elements)
  • empty() – Removes the child elements from the selected element

jQuery remove() Method

The jQuery remove() method removes the selected element(s) and its child elements.

Example

$(“#div1”).remove();

jQuery empty() Method

The jQuery empty() method removes the child elements of the selected element(s).

Example

$(“#div1”).empty();

Filter the Elements to be Removed

The jQuery remove() method also accepts one parameter, which allows you to filter the elements to be removed.

The parameter can be any of the jQuery selector syntaxes.

The following example removes all <p> elements with class="test":  

Example

$(“p”).remove(“.test”);

This example removes all <p> elements with class="test" or class="demo":  

Example

$(“p”).remove(“.test, .demo”);

jQuery Manipulating CSS

jQuery has several methods for CSS manipulation. We will look at the following methods:

  • addClass() – Adds one or more classes to the selected elements
  • removeClass() – Removes one or more classes from the selected elements
  • toggleClass() – Toggles between adding/removing classes from the selected elements
  • css() – Sets or returns the style attribute

Example Stylesheet

The following stylesheet will be used for all the examples on this page:

.important {
  font-weight: bold;
  font-size: xx-large;
}

.blue {
  color: blue;
}


jQuery addClass() Method

The following example shows how to add class attributes to different elements. Of course you can select multiple elements, when adding classes:

Example

$(“button”).click(function(){
  $(“h1, h2, p”).addClass(“blue”);
  $(“div”).addClass(“important”);
});

You can also specify multiple classes within the addClass() method:

Example

$(“button”).click(function(){
  $(“#div1”).addClass(“important blue”);
});

jQuery removeClass() Method

The following example shows how to remove a specific class attribute from different elements:

Example

$(“button”).click(function(){
  $(“h1, h2, p”).removeClass(“blue”);
});

jQuery toggleClass() Method

The following example will show how to use the jQuery toggleClass() method. This method toggles between adding/removing classes from the selected elements:

Example

$(“button”).click(function(){
  $(“h1, h2, p”).toggleClass(“blue”);
});

jQuery css() Method

The css() method sets or returns one or more style properties for the selected elements.


Return a CSS Property

To return the value of a specified CSS property, use the following syntax:

css(“propertyname“);

The following example will return the background-color value of the FIRST matched element:

Example

$(“p”).css(“background-color”);

Set a CSS Property

To set a specified CSS property, use the following syntax:

css(“propertyname“,”value“);

The following example will set the background-color value for ALL matched elements:

Example

$(“p”).css(“background-color”, “yellow”);

Set Multiple CSS Properties

To set multiple CSS properties, use the following syntax:

css({“propertyname“:”value“,”propertyname“:”value“,…});

The following example will set a background-color and a font-size for ALL matched elements:

Example

$(“p”).css({“background-color”: “yellow”, “font-size”: “200%”});

jQuery width() and height() Methods

The width() method sets or returns the width of an element (excludes padding, border and margin).

The height() method sets or returns the height of an element (excludes padding, border and margin).

The following example returns the width and height of a specified <div> element:

Example

$(“button”).click(function(){
  var txt = “”;
  txt += “Width: ” + $(“#div1”).width() + “</br>”;
  txt += “Height: ” + $(“#div1”).height();
  $(“#div1”).html(txt);
});

jQuery innerWidth() and innerHeight() Methods

The innerWidth() method returns the width of an element (includes padding).

The innerHeight() method returns the height of an element (includes padding).

The following example returns the inner-width/height of a specified <div> element:

Example

$(“button”).click(function(){
  var txt = “”;
  txt += “Inner width: ” + $(“#div1”).innerWidth() + “</br>”;
  txt += “Inner height: ” + $(“#div1”).innerHeight();
  $(“#div1”).html(txt);
});

jQuery outerWidth() and outerHeight() Methods

The outerWidth() method returns the width of an element (includes padding and border).

The outerHeight() method returns the height of an element (includes padding and border).

The following example returns the outer-width/height of a specified <div> element:

Example

$(“button”).click(function(){
  var txt = “”;
  txt += “Outer width: ” + $(“#div1”).outerWidth() + “</br>”;
  txt += “Outer height: ” + $(“#div1”).outerHeight();
  $(“#div1”).html(txt);
});

The outerWidth(true) method returns the width of an element (includes padding, border, and margin).

The outerHeight(true) method returns the height of an element (includes padding, border, and margin).

Example

$(“button”).click(function(){
  var txt = “”;
  txt += “Outer width (+margin): ” + $(“#div1”).outerWidth(true) + “</br>”;
  txt += “Outer height (+margin): ” + $(“#div1”).outerHeight(true);
  $(“#div1”).html(txt);
});

jQuery More width() and height()

The following example returns the width and height of the document (the HTML document) and window (the browser viewport):

Example

$(“button”).click(function(){
  var txt = “”;
  txt += “Document width/height: ” + $(document).width();
  txt += “x” + $(document).height() + “\n”;
  txt += “Window width/height: ” + $(window).width();
  txt += “x” + $(window).height();
  alert(txt);
});

jQuery More width() and height()

The following example returns the width and height of the document (the HTML document) and window (the browser viewport):

Example

$(“button”).click(function(){
  var txt = “”;
  txt += “Document width/height: ” + $(document).width();
  txt += “x” + $(document).height() + “\n”;
  txt += “Window width/height: ” + $(window).width();
  txt += “x” + $(window).height();
  alert(txt);
});

What is Traversing?

jQuery traversing, which means “move through”, are used to “find” (or select) HTML elements based on their relation to other elements. Start with one selection and move through that selection until you reach the elements you desire.

The image below illustrates an HTML page as a tree (DOM tree). With jQuery traversing, you can easily move up (ancestors), down (descendants) and sideways (siblings) in the tree, starting from the selected (current) element. This movement is called traversing – or moving through – the DOM tree.

Traversing Up the DOM Tree

Three useful jQuery methods for traversing up the DOM tree are:

  • parent()
  • parents()
  • parentsUntil()

jQuery parent() Method

The parent() method returns the direct parent element of the selected element.

This method only traverse a single level up the DOM tree.

The following example returns the direct parent element of each <span> elements:

Example

$(document).ready(function(){
  $(“span”).parent();
});

jQuery parents() Method

The parents() method returns all ancestor elements of the selected element, all the way up to the document’s root element (<html>).

The following example returns all ancestors of all <span> elements:

Example

$(document).ready(function(){
  $(“span”).parents();
});

You can also use an optional parameter to filter the search for ancestors.

The following example returns all ancestors of all <span> elements that are <ul> elements:

Example

$(document).ready(function(){
  $(“span”).parents(“ul”);
});

jQuery parentsUntil() Method

The parentsUntil() method returns all ancestor elements between two given arguments.

The following example returns all ancestor elements between a <span> and a <div> element:

Example

$(document).ready(function(){
  $(“span”).parentsUntil(“div”);
});

With jQuery you can traverse down the DOM tree to find descendants of an element.

A descendant is a child, grandchild, great-grandchild, and so on.


Traversing Down the DOM Tree

Two useful jQuery methods for traversing down the DOM tree are:

  • children()
  • find()

jQuery children() Method

The children() method returns all direct children of the selected element.

This method only traverses a single level down the DOM tree.

The following example returns all elements that are direct children of each <div> elements:

Example

$(document).ready(function(){
  $(“div”).children();
});

You can also use an optional parameter to filter the search for children.

The following example returns all <p> elements with the class name “first”, that are direct children of <div>:

Example

$(document).ready(function(){
  $(“div”).children(“p.first”);
});

jQuery find() Method

The find() method returns descendant elements of the selected element, all the way down to the last descendant.

The following example returns all <span> elements that are descendants of <div>:

Example

$(document).ready(function(){
  $(“div”).find(“span”);
});

The following example returns all descendants of <div>:

Example

$(document).ready(function(){
  $(“div”).find(“*”);
});

jQuery Traversing – Siblings

With jQuery you can traverse sideways in the DOM tree to find siblings of an element.

Siblings share the same parent. 


Traversing Sideways in The DOM Tree

There are many useful jQuery methods for traversing sideways in the DOM tree:

  • siblings()
  • next()
  • nextAll()
  • nextUntil()
  • prev()
  • prevAll()
  • prevUntil()

jQuery siblings() Method

The siblings() method returns all sibling elements of the selected element.

The following example returns all sibling elements of <h2>:

Example

$(document).ready(function(){
  $(“h2”).siblings();
});

You can also use an optional parameter to filter the search for siblings.

The following example returns all sibling elements of <h2> that are <p> elements:

Example

$(document).ready(function(){
  $(“h2”).siblings(“p”);
});

jQuery next() Method

The next() method returns the next sibling element of the selected element.

The following example returns the next sibling of <h2>:

Example

$(document).ready(function(){
  $(“h2”).next();
});

jQuery nextAll() Method

The nextAll() method returns all next sibling elements of the selected element.

The following example returns all next sibling elements of <h2>:

Example

$(document).ready(function(){
  $(“h2”).nextAll();
});

jQuery nextUntil() Method

The nextUntil() method returns all next sibling elements between two given arguments.

The following example returns all sibling elements between a <h2> and a <h6> element:

Example

$(document).ready(function(){
  $(“h2”).nextUntil(“h6”);
});

jQuery prev(), prevAll() & prevUntil() Methods

The prev(), prevAll() and prevUntil() methods work just like the methods above but with reverse functionality: they return previous sibling elements (traverse backwards along sibling elements in the DOM tree, instead of forward).

The first(), last(), eq(), filter() and not() Methods

The most basic filtering methods are first(), last() and eq(), which allow you to select a specific element based on its position in a group of elements.

Other filtering methods, like filter() and not() allow you to select elements that match, or do not match, a certain criteria.

jQuery first() Method

The first() method returns the first element of the specified elements.

The following example selects the first <div> element:

Example

$(document).ready(function(){
  $(“div”).first();
});

jQuery last() Method

The last() method returns the last element of the specified elements.

The following example selects the last <div> element:

Example

$(document).ready(function(){
  $(“div”).last();
});

jQuery eq() method

The eq() method returns an element with a specific index number of the selected elements.

The index numbers start at 0, so the first element will have the index number 0 and not 1. The following example selects the second <p> element (index number 1):

Example

$(document).ready(function(){
  $(“p”).eq(1);
});

jQuery filter() Method

The filter() method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned.

The following example returns all <p> elements with class name “intro”:

Example

$(document).ready(function(){
  $(“p”).filter(“.intro”);
});

jQuery not() Method

The not() method returns all elements that do not match the criteria.

Tip: The not() method is the opposite of filter().

The following example returns all <p> elements that do not have class name “intro”:

Example

$(document).ready(function(){
  $(“p”).not(“.intro”);
});

jQuery Selectors

Use our jQuery Selector Tester to demonstrate the different selectors.

SelectorExampleSelects
*$(“*”)All elements
#id$(“#lastname”)The element with id=”lastname”
.class$(“.intro”)All elements with class=”intro”
.class,.class$(“.intro,.demo”)All elements with the class “intro” or “demo”
element$(“p”)All <p> elements
el1,el2,el3$(“h1,div,p”)All <h1>, <div> and <p> elements
   
:first$(“p:first”)The first <p> element
:last$(“p:last”)The last <p> element
:even$(“tr:even”)All even <tr> elements
:odd$(“tr:odd”)All odd <tr> elements
   
:first-child$(“p:first-child”)All <p> elements that are the first child of their parent
:first-of-type$(“p:first-of-type”)All <p> elements that are the first <p> element of their parent
:last-child$(“p:last-child”)All <p> elements that are the last child of their parent
:last-of-type$(“p:last-of-type”)All <p> elements that are the last <p> element of their parent
:nth-child(n)$(“p:nth-child(2)”)All <p> elements that are the 2nd child of their parent
:nth-last-child(n)$(“p:nth-last-child(2)”)All <p> elements that are the 2nd child of their parent, counting from the last child
:nth-of-type(n)$(“p:nth-of-type(2)”)All <p> elements that are the 2nd <p> element of their parent
:nth-last-of-type(n)$(“p:nth-last-of-type(2)”)All <p> elements that are the 2nd <p> element of their parent, counting from the last child
:only-child$(“p:only-child”)All <p> elements that are the only child of their parent
:only-of-type$(“p:only-of-type”)All <p> elements that are the only child, of its type, of their parent
   
parent > child$(“div > p”)All <p> elements that are a direct child of a <div> element
parent descendant$(“div p”)All <p> elements that are descendants of a <div> element
element + next$(“div + p”)The <p> element that are next to each <div> elements
element ~ siblings$(“div ~ p”)All <p> elements that are siblings of a <div> element
   
:eq(index)$(“ul li:eq(3)”)The fourth element in a list (index starts at 0)
:gt(no)$(“ul li:gt(3)”)List elements with an index greater than 3
:lt(no)$(“ul li:lt(3)”)List elements with an index less than 3
:not(selector)$(“input:not(:empty)”)All input elements that are not empty
   
:header$(“:header”)All header elements <h1>, <h2> …
:animated$(“:animated”)All animated elements
:focus$(“:focus”)The element that currently has focus
:contains(text)$(“:contains(‘Hello’)”)All elements which contains the text “Hello”
:has(selector)$(“div:has(p)”)All <div> elements that have a <p> element
:empty$(“:empty”)All elements that are empty
:parent$(“:parent”)All elements that are a parent of another element
:hidden$(“p:hidden”)All hidden <p> elements
:visible$(“table:visible”)All visible tables
:root$(“:root”)The document’s root element
:lang(language)$(“p:lang(de)”)All <p> elements with a lang attribute value starting with “de”
   
[attribute]$(“[href]”)All elements with a href attribute
[attribute=value]$(“[href=’default.htm’]”)All elements with a href attribute value equal to “default.htm”
[attribute!=value]$(“[href!=’default.htm’]”)All elements with a href attribute value not equal to “default.htm”
[attribute$=value]$(“[href$=’.jpg’]”)All elements with a href attribute value ending with “.jpg”
[attribute|=value]$(“[title|=’Tomorrow’]”)All elements with a title attribute value equal to ‘Tomorrow’, or starting with ‘Tomorrow’ followed by a hyphen
[attribute^=value]$(“[title^=’Tom’]”)All elements with a title attribute value starting with “Tom”
[attribute~=value]$(“[title~=’hello’]”)All elements with a title attribute value containing the specific word “hello”
[attribute*=value]$(“[title*=’hello’]”)All elements with a title attribute value containing the word “hello”
   
:input$(“:input”)All input elements
:text$(“:text”)All input elements with type=”text”
:password$(“:password”)All input elements with type=”password”
:radio$(“:radio”)All input elements with type=”radio”
:checkbox$(“:checkbox”)All input elements with type=”checkbox”
:submit$(“:submit”)All input elements with type=”submit”
:reset$(“:reset”)All input elements with type=”reset”
:button$(“:button”)All input elements with type=”button”
:image$(“:image”)All input elements with type=”image”
:file$(“:file”)All input elements with type=”file”
:enabled$(“:enabled”)All enabled input elements
:disabled$(“:disabled”)All disabled input elements
:selected$(“:selected”)All selected input elements
:checked$(“:checked”)All checked input elements

jQuery Event Methods

Event methods trigger or attach a function to an event handler for the selected elements.

The following table lists all the jQuery methods used to handle events.

Method / PropertyDescription
bind()Deprecated in version 3.0. Use the on() method instead. Attaches event handlers to elements
blur()Attaches/Triggers the blur event
change()Attaches/Triggers the change event
click()Attaches/Triggers the click event
dblclick()Attaches/Triggers the double click event
delegate()Deprecated in version 3.0. Use the on() method instead. Attaches a handler to current, or future, specified child elements of the matching elements
die()Removed in version 1.9. Removes all event handlers added with the live() method
error()Removed in version 3.0. Attaches/Triggers the error event
event.currentTargetThe current DOM element within the event bubbling phase
event.dataContains the optional data passed to an event method when the current executing handler is bound
event.delegateTargetReturns the element where the currently-called jQuery event handler was attached
event.isDefaultPrevented()Returns whether event.preventDefault() was called for the event object
event.isImmediatePropagationStopped()Returns whether event.stopImmediatePropagation() was called for the event object
event.isPropagationStopped()Returns whether event.stopPropagation() was called for the event object
event.namespaceReturns the namespace specified when the event was triggered
event.pageXReturns the mouse position relative to the left edge of the document
event.pageYReturns the mouse position relative to the top edge of the document
event.preventDefault()Prevents the default action of the event
event.relatedTargetReturns which element being entered or exited on mouse movement
event.resultContains the last/previous value returned by an event handler triggered by the specified event
event.stopImmediatePropagation()Prevents other event handlers from being called
event.stopPropagation()Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event
event.targetReturns which DOM element triggered the event
event.timeStampReturns the number of milliseconds since January 1, 1970, when the event is triggered
event.typeReturns which event type was triggered
event.whichReturns which keyboard key or mouse button was pressed for the event
focus()Attaches/Triggers the focus event
focusin()Attaches an event handler to the focusin event
focusout()Attaches an event handler to the focusout event
hover()Attaches two event handlers to the hover event
keydown()Attaches/Triggers the keydown event
keypress()Attaches/Triggers the keypress event
keyup()Attaches/Triggers the keyup event
live()Removed in version 1.9. Adds one or more event handlers to current, or future, selected elements
load()Removed in version 3.0. Attaches an event handler to the load event
mousedown()Attaches/Triggers the mousedown event
mouseenter()Attaches/Triggers the mouseenter event
mouseleave()Attaches/Triggers the mouseleave event
mousemove()Attaches/Triggers the mousemove event
mouseout()Attaches/Triggers the mouseout event
mouseover()Attaches/Triggers the mouseover event
mouseup()Attaches/Triggers the mouseup event
off()Removes event handlers attached with the on() method
on()Attaches event handlers to elements
one()Adds one or more event handlers to selected elements. This handler can only be triggered once per element
$.proxy()Takes an existing function and returns a new one with a particular context
ready()Specifies a function to execute when the DOM is fully loaded
resize()Attaches/Triggers the resize event
scroll()Attaches/Triggers the scroll event
select()Attaches/Triggers the select event
submit()Attaches/Triggers the submit event
toggle()Removed in version 1.9. Attaches two or more functions to toggle between for the click event
trigger()Triggers all events bound to the selected elements
triggerHandler()Triggers all functions bound to a specified event for the selected elements
unbind()Deprecated in version 3.0. Use the off() method instead. Removes an added event handler from selected elements
undelegate()Deprecated in version 3.0. Use the off() method instead. Removes an event handler to selected elements, now or in the future
unload()Removed in version 3.0. Attaches an event handler to the unload event

jQuery Effect Methods

The following table lists all the jQuery methods for creating animation effects.

MethodDescription
animate()Runs a custom animation on the selected elements
clearQueue()Removes all remaining queued functions from the selected elements
delay()Sets a delay for all queued functions on the selected elements
dequeue()Removes the next function from the queue, and then executes the function
fadeIn()Fades in the selected elements
fadeOut()Fades out the selected elements
fadeTo()Fades in/out the selected elements to a given opacity
fadeToggle()Toggles between the fadeIn() and fadeOut() methods
finish()Stops, removes and completes all queued animations for the selected elements
hide()Hides the selected elements
queue()Shows the queued functions on the selected elements
show()Shows the selected elements
slideDown()Slides-down (shows) the selected elements
slideToggle()Toggles between the slideUp() and slideDown() methods
slideUp()Slides-up (hides) the selected elements
stop()Stops the currently running animation for the selected elements
toggle()Toggles between the hide() and show() methods

jQuery HTML / CSS Methods

The following table lists all the methods used to manipulate the HTML and CSS.

The methods below work for both HTML and XML documents. Exception: the html() method.

MethodDescription
addClass()Adds one or more class names to selected elements
after()Inserts content after selected elements
append()Inserts content at the end of selected elements
appendTo()Inserts HTML elements at the end of selected elements
attr()Sets or returns attributes/values of selected elements
before()Inserts content before selected elements
clone()Makes a copy of selected elements
css()Sets or returns one or more style properties for selected elements
detach()Removes selected elements (keeps data and events)
empty()Removes all child nodes and content from selected elements
hasClass()Checks if any of the selected elements have a specified class name
height()Sets or returns the height of selected elements
html()Sets or returns the content of selected elements
innerHeight()Returns the height of an element (includes padding, but not border)
innerWidth()Returns the width of an element (includes padding, but not border)
insertAfter()Inserts HTML elements after selected elements
insertBefore()Inserts HTML elements before selected elements
offset()Sets or returns the offset coordinates for selected elements (relative to the document)
offsetParent()Returns the first positioned parent element
outerHeight()Returns the height of an element (includes padding and border)
outerWidth()Returns the width of an element (includes padding and border)
position()Returns the position (relative to the parent element) of an element
prepend()Inserts content at the beginning of selected elements
prependTo()Inserts HTML elements at the beginning of selected elements
prop()Sets or returns properties/values of selected elements
remove()Removes the selected elements (including data and events)
removeAttr()Removes one or more attributes from selected elements
removeClass()Removes one or more classes from selected elements
removeProp()Removes a property set by the prop() method
replaceAll()Replaces selected elements with new HTML elements
replaceWith()Replaces selected elements with new content
scrollLeft()Sets or returns the horizontal scrollbar position of selected elements
scrollTop()Sets or returns the vertical scrollbar position of selected elements
text()Sets or returns the text content of selected elements
toggleClass()Toggles between adding/removing one or more classes from selected elements
unwrap()Removes the parent element of the selected elements
val()Sets or returns the value attribute of the selected elements (for form elements)
width()Sets or returns the width of selected elements
wrap()Wraps HTML element(s) around each selected element
wrapAll()Wraps HTML element(s) around all selected elements
wrapInner()Wraps HTML element(s) around the content of each selected element

jQuery Traversing Methods

MethodDescription
add()Adds elements to the set of matched elements
addBack()Adds the previous set of elements to the current set
andSelf()Deprecated in version 1.8. An alias for addBack()
children()Returns all direct children of the selected element
closest()Returns the first ancestor of the selected element
contents()Returns all direct children of the selected element (including text and comment nodes)
each()Executes a function for each matched element
end()Ends the most recent filtering operation in the current chain, and return the set of matched elements to its previous state
eq()Returns an element with a specific index number of the selected elements
filter()Reduce the set of matched elements to those that match the selector or pass the function’s test
find()Returns descendant elements of the selected element
first()Returns the first element of the selected elements
has()Returns all elements that have one or more elements inside of them
is()Checks the set of matched elements against a selector/element/jQuery object, and return true if at least one of these elements matches the given arguments
last()Returns the last element of the selected elements
map()Passes each element in the matched set through a function, producing a new jQuery object containing the return values
next()Returns the next sibling element of the selected element
nextAll()Returns all next sibling elements of the selected element
nextUntil()Returns all next sibling elements between two given arguments
not()Returns elements that do not match a certain criteria
offsetParent()Returns the first positioned parent element
parent()Returns the direct parent element of the selected element
parents()Returns all ancestor elements of the selected element
parentsUntil()Returns all ancestor elements between two given arguments
prev()Returns the previous sibling element of the selected element
prevAll()Returns all previous sibling elements of the selected element
prevUntil()Returns all previous sibling elements between two given arguments
siblings()Returns all sibling elements of the selected element
slice()Reduces the set of matched elements to a subset specified by a range of indices

jQuery AJAX Methods

AJAX is the art of exchanging data with a server, and update parts of a web page – without reloading the whole page.

The following table lists all the jQuery AJAX methods:

MethodDescription
$.ajax()Performs an async AJAX request
$.ajaxPrefilter()Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax()
$.ajaxSetup()Sets the default values for future AJAX requests
$.ajaxTransport()Creates an object that handles the actual transmission of Ajax data
$.get()Loads data from a server using an AJAX HTTP GET request
$.getJSON()Loads JSON-encoded data from a server using a HTTP GET request
$.parseJSON()Deprecated in version 3.0, use JSON.parse() instead. Takes a well-formed JSON string and returns the resulting JavaScript value
$.getScript()Loads (and executes) a JavaScript from a server using an AJAX HTTP GET request
$.param()Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests)
$.post()Loads data from a server using an AJAX HTTP POST request
ajaxComplete()Specifies a function to run when the AJAX request completes
ajaxError()Specifies a function to run when the AJAX request completes with an error
ajaxSend()Specifies a function to run before the AJAX request is sent
ajaxStart()Specifies a function to run when the first AJAX request begins
ajaxStop()Specifies a function to run when all AJAX requests have completed
ajaxSuccess()Specifies a function to run when an AJAX request completes successfully
load()Loads data from a server and puts the returned data into the selected element
serialize()Encodes a set of form elements as a string for submission
serializeArray()Encodes a set of form elements as an array of names and values

jQuery Misc Methods

MethodDescription
data()Attaches data to, or gets data from, selected elements
each()Execute a function for each matched element
get()Get the DOM elements matched by the selector
index()Search for a given element from among the matched elements
$.noConflict()Release jQuery’s control of the $ variable
$.param()Create a serialized representation of an array or object (can be used as URL query string for AJAX requests)
removeData()Removes a previously-stored piece of data
size()Removed in version 3.0. Use the length property instead
toArray()Retrieve all the DOM elements contained in the jQuery set, as an array

jQuery Properties

PropertyDescription
contextRemoved in version 3.0. Contains the original context passed to jQuery()
jqueryContains the jQuery version number
jQuery.fx.intervalChange the animation firing rate in milliseconds
jQuery.fx.offGlobally disable/enable all animations
jQuery.supportA collection of properties representing different browser features or bugs (Intended for jQuery’s internal use)
lengthContains the number of elements in the jQuery object

SQL Joins Tutorial

SQL LEFT JOIN Keyword

Different Types of SQL JOINs

Here are the different types of the JOINs in SQL:

  • (INNER) JOIN: Returns records that have matching values in both tables
  • LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right table
  • RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left table
  • FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table

The LEFT JOIN keyword returns all records from the left table (table1), and the matched records from the right table (table2). The result is NULL from the right side, if there is no match.

LEFT JOIN Syntax

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

SQL LEFT JOIN Example

The following SQL statement will select all customers, and any orders they might have:

Example

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;

PHP Mysqli

Example (MySQLi Object-Oriented)

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die(“Connection failed: ” . $conn->connect_error);
}
echo “Connected successfully”;
?>

Create a MySQL Database Using MySQLi and PDO

The CREATE DATABASE statement is used to create a database in MySQL.

The following examples create a database named “myDB”:

Example (MySQLi Object-oriented)

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
    die(“Connection failed: ” . $conn->connect_error);
}

// Create database
$sql = “CREATE DATABASE myDB”;
if ($conn->query($sql) === TRUE) {
    echo “Database created successfully”;
} else {
    echo “Error creating database: ” . $conn->error;
}

$conn->close();
?>

Note: When you create a new database, you must only specify the first three arguments to the mysqli object (servername, username and password).

Create a MySQL Table Using MySQLi and PDO

The CREATE TABLE statement is used to create a table in MySQL.

We will create a table named “MyGuests”, with five columns: “id”, “firstname”, “lastname”, “email” and “reg_date”:

CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

Notes on the table above:

The data type specifies what type of data the column can hold. For a complete reference of all the available data types, go to our Data Types reference.

After the data type, you can specify other optional attributes for each column:

  • NOT NULL – Each row must contain a value for that column, null values are not allowed
  • DEFAULT value – Set a default value that is added when no other value is passed
  • UNSIGNED – Used for number types, limits the stored data to positive numbers and zero
  • AUTO INCREMENT – MySQL automatically increases the value of the field by 1 each time a new record is added
  • PRIMARY KEY – Used to uniquely identify the rows in a table. The column with PRIMARY KEY setting is often an ID number, and is often used with AUTO_INCREMENT

Each table should have a primary key column (in this case: the “id” column). Its value must be unique for each record in the table.

The following examples shows how to create the table in PHP:

Example (MySQLi Object-oriented)

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “myDB”;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die(“Connection failed: ” . $conn->connect_error);
}

// sql to create table
$sql = “CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)”;

if ($conn->query($sql) === TRUE) {
    echo “Table MyGuests created successfully”;
} else {
    echo “Error creating table: ” . $conn->error;
}

$conn->close();
?>

Insert Data Into MySQL Using MySQLi and PDO

After a database and a table have been created, we can start adding data in them.

Here are some syntax rules to follow:

  • The SQL query must be quoted in PHP
  • String values inside the SQL query must be quoted
  • Numeric values must not be quoted
  • The word NULL must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,…)
VALUES (value1, value2, value3,…)

To learn more about SQL, please visit our SQL tutorial.

In the previous chapter we created an empty table named “MyGuests” with five columns: “id”, “firstname”, “lastname”, “email” and “reg_date”. Now, let us fill the table with data.

Note: If a column is AUTO_INCREMENT (like the “id” column) or TIMESTAMP with default update of current_timesamp (like the “reg_date” column), it is no need to be specified in the SQL query; MySQL will automatically add the value.

The following examples add a new record to the “MyGuests” table:

Example (MySQLi Object-oriented)

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “myDB”;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die(“Connection failed: ” . $conn->connect_error);
}

$sql = “INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)”;

if ($conn->query($sql) === TRUE) {
    echo “New record created successfully”;
} else {
    echo “Error: ” . $sql . “<br>” . $conn->error;
}

$conn->close();
?>

Get ID of The Last Inserted Record

If we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field, we can get the ID of the last inserted/updated record immediately.

In the table “MyGuests”, the “id” column is an AUTO_INCREMENT field:

CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

The following examples are equal to the examples from the previous page (PHP Insert Data Into MySQL), except that we have added one single line of code to retrieve the ID of the last inserted record. We also echo the last inserted ID:

Example (MySQLi Object-oriented)

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “myDB”;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die(“Connection failed: ” . $conn->connect_error);
}

$sql = “INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)”;

if ($conn->query($sql) === TRUE) {
    $last_id = $conn->insert_id;
    echo “New record created successfully. Last inserted ID is: ” . $last_id;
} else {
    echo “Error: ” . $sql . “<br>” . $conn->error;
}

$conn->close();
?>

Insert Multiple Records Into MySQL Using MySQLi and PDO

Multiple SQL statements must be executed with the mysqli_multi_query() function.

The following examples add three new records to the “MyGuests” table:

Example (MySQLi Object-oriented)

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “myDB”;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die(“Connection failed: ” . $conn->connect_error);
}

$sql = “INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’);”;
$sql .= “INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘Mary’, ‘Moe’, ‘mary@example.com’);”;
$sql .= “INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘Julie’, ‘Dooley’, ‘julie@example.com’)”;

if ($conn->multi_query($sql) === TRUE) {
    echo “New records created successfully”;
} else {
    echo “Error: ” . $sql . “<br>” . $conn->error;
}

$conn->close();
?>

Note that each SQL statement must be separated by a semicolon.

Select Data With MySQLi

The following example selects the id, firstname and lastname columns from the MyGuests table and displays it on the page:

Example (MySQLi Object-oriented)

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “myDB”;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die(“Connection failed: ” . $conn->connect_error);
}

$sql = “SELECT id, firstname, lastname FROM MyGuests”;
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo “id: ” . $row[“id”]. ” – Name: ” . $row[“firstname”]. ” ” . $row[“lastname”]. “<br>”;
    }
} else {
    echo “0 results”;
}
$conn->close();
?>

Select and Filter Data From a MySQL Database

The WHERE clause is used to filter records.

The WHERE clause is used to extract only those records that fulfill a specified condition.

SELECT column_name(s) FROM table_name WHERE column_name operator value 

To learn more about SQL, please visit our SQL tutorial.


Select and Filter Data With MySQLi

The following example selects the id, firstname and lastname columns from the MyGuests table where the lastname is “Doe”, and displays it on the page:

Example (MySQLi Object-oriented)

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “myDB”;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die(“Connection failed: ” . $conn->connect_error);
}

$sql = “SELECT id, firstname, lastname FROM MyGuests WHERE lastname=’Doe'”;
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo “id: ” . $row[“id”]. ” – Name: ” . $row[“firstname”]. ” ” . $row[“lastname”]. “<br>”;
    }
} else {
    echo “0 results”;
}
$conn->close();
?>

Code lines to explain from the example above:

First, we set up the SQL query that selects the id, firstname and lastname columns from the MyGuests table where the lastname is “Doe”. The next line of code runs the query and puts the resulting data into a variable called $result.

Then, the function num_rows() checks if there are more than zero rows returned.

If there are more than zero rows returned, the function fetch_assoc() puts all the results into an associative array that we can loop through. The while() loop loops through the result set and outputs the data from the id, firstname and lastname columns.

Select and Order Data From a MySQL Database

The ORDER BY clause is used to sort the result-set in ascending or descending order.

The ORDER BY clause sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC 

To learn more about SQL, please visit our SQL tutorial.


Select and Order Data With MySQLi

The following example selects the id, firstname and lastname columns from the MyGuests table. The records will be ordered by the lastname column:

Example (MySQLi Object-oriented)

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “myDB”;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die(“Connection failed: ” . $conn->connect_error);
}

$sql = “SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname”;
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo “id: ” . $row[“id”]. ” – Name: ” . $row[“firstname”]. ” ” . $row[“lastname”]. “<br>”;
    }
} else {
    echo “0 results”;
}
$conn->close();
?>

Code lines to explain from the example above:

First, we set up the SQL query that selects the id, firstname and lastname columns from the MyGuests table. The records will be ordered by the lastname column. The next line of code runs the query and puts the resulting data into a variable called $result.

Then, the function num_rows() checks if there are more than zero rows returned.

If there are more than zero rows returned, the function fetch_assoc() puts all the results into an associative array that we can loop through. The while() loop loops through the result set and outputs the data from the id, firstname and lastname columns.

Delete Data From a MySQL Table Using MySQLi and PDO

The DELETE statement is used to delete records from a table:

DELETE FROM table_name
WHERE some_column = some_value

Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted!

To learn more about SQL, please visit our SQL tutorial.

Let’s look at the “MyGuests” table:

idfirstnamelastnameemailreg_date
1JohnDoejohn@example.com2014-10-22 14:26:15
2MaryMoemary@example.com2014-10-23 10:22:30
3JulieDooleyjulie@example.com2014-10-26 10:48:23

The following examples delete the record with id=3 in the “MyGuests” table:

Example (MySQLi Object-oriented)

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “myDB”;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die(“Connection failed: ” . $conn->connect_error);
}

// sql to delete a record
$sql = “DELETE FROM MyGuests WHERE id=3”;

if ($conn->query($sql) === TRUE) {
    echo “Record deleted successfully”;
} else {
    echo “Error deleting record: ” . $conn->error;
}

$conn->close();
?>

Update Data In a MySQL Table Using MySQLi and PDO

The UPDATE statement is used to update existing records in a table:

UPDATE table_name
SET column1=value, column2=value2,…
WHERE some_column=some_value 

Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!

To learn more about SQL, please visit our SQL tutorial.

Let’s look at the “MyGuests” table:

idfirstnamelastnameemailreg_date
1JohnDoejohn@example.com2014-10-22 14:26:15
2MaryMoemary@example.com2014-10-23 10:22:30

The following examples update the record with id=2 in the “MyGuests” table:

Example (MySQLi Object-oriented)

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “myDB”;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die(“Connection failed: ” . $conn->connect_error);
}

$sql = “UPDATE MyGuests SET lastname=’Doe’ WHERE id=2”;

if ($conn->query($sql) === TRUE) {
    echo “Record updated successfully”;
} else {
    echo “Error updating record: ” . $conn->error;
}

$conn->close();
?>

Limit Data Selections From a MySQL Database

MySQL provides a LIMIT clause that is used to specify the number of records to return.

The LIMIT clause makes it easy to code multi page results or pagination with SQL, and is very useful on large tables. Returning a large number of records can impact on performance.

Assume we wish to select all records from 1 – 30 (inclusive) from a table called “Orders”. The SQL query would then look like this:

$sql = “SELECT * FROM Orders LIMIT 30”;

When the SQL query above is run, it will return the first 30 records.

What if we want to select records 16 – 25 (inclusive)?

Mysql also provides a way to handle this: by using OFFSET.

The SQL query below says “return only 10 records, start on record 16 (OFFSET 15)”:

$sql = “SELECT * FROM Orders LIMIT 10 OFFSET 15”;

You could also use a shorter syntax to achieve the same result:

$sql = “SELECT * FROM Orders LIMIT 15, 10”;

Notice that the numbers are reversed when you use a comma.

PHP Tutorial

SWITCH CASE

Example

<?php
$favcolor = “red”;

switch ($favcolor) {
    case “red”:
        echo “Your favorite color is red!”;
        break;
    case “blue”:
        echo “Your favorite color is blue!”;
        break;
    case “green”:
        echo “Your favorite color is green!”;
        break;
    default:
        echo “Your favorite color is neither red, blue, nor green!”;
}
?>

The PHP while Loop

The while loop executes a block of code as long as the specified condition is true.

Syntax

while (condition is true) {
    code to be executed;
}

Examples

The example below displays the numbers from 1 to 5:

Example

<?php
$x = 1;

while($x <= 5) {
    echo “The number is: $x <br>”;
    $x++;
}
?>

The PHP do…while Loop

The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.

Syntax

do {
    code to be executed;
} while (condition is true);

Examples

The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:

Example

<?php
$x = 1;

do {
    echo “The number is: $x <br>”;
    $x++;
} while ($x <= 5);
?>

The PHP for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax

for (init counter; test counter; increment counter) {
    code to be executed for each iteration;
}

Parameters:

  • init counter: Initialize the loop counter value
  • test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • increment counter: Increases the loop counter value

Examples

The example below displays the numbers from 0 to 10:

Example

<?php
for ($x = 0; $x <= 10; $x++) {
    echo “The number is: $x <br>”;
}
?>

The PHP foreach Loop

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Syntax

foreach ($array as$value) {
  code to be executed;
}

For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

Examples

The following example will output the values of the given array ($colors):

Example

<?php
$colors = array(“red”, “green”, “blue”, “yellow”);

foreach ($colors as $value) {
  echo “$value <br>”;
}
?>

What is an Array?

An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

$cars1 = “Volvo”;
$cars2 = “BMW”;
$cars3 = “Toyota”;

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is to create an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.


Create an Array in PHP

In PHP, the array() function is used to create an array:

array();

In PHP, there are three types of arrays:

  • Indexed arrays – Arrays with a numeric index
  • Associative arrays – Arrays with named keys
  • Multidimensional arrays – Arrays containing one or more arrays

Get The Length of an Array – The count() Function

The count() function is used to return the length (the number of elements) of an array:

Example

<?php
$cars = array(“Volvo”, “BMW”, “Toyota”);
echo count($cars);
?>

PHP Indexed Arrays

There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0), like this:

$cars = array(“Volvo”, “BMW”, “Toyota”);

or the index can be assigned manually:

$cars[0] = “Volvo”;
$cars[1] = “BMW”;
$cars[2] = “Toyota”;

The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text containing the array values:

Example

<?php
$cars = array(“Volvo”, “BMW”, “Toyota”);
echo “I like ” . $cars[0] . “, ” . $cars[1] . ” and ” . $cars[2] . “.”;
?>

Loop Through an Associative Array

To loop through and print all the values of an associative array, you could use a foreach loop, like this:

Example

<?php
$age = array(“Peter”=>”35”, “Ben”=>”37”, “Joe”=>”43”);

foreach($age as $x => $x_value) {
    echo “Key=” . $x . “, Value=” . $x_value;
    echo “<br>”;
}
?>

We can store the data from the table above in a two-dimensional array, like this:

$cars = array
  (
  array(“Volvo”,22,18),
  array(“BMW”,15,13),
  array(“Saab”,5,2),
  array(“Land Rover”,17,15)
  );

We can also put a for loop inside another for loop to get the elements of the $cars array (we still have to point to the two indices):

Example

<?php
for ($row = 0; $row < 4; $row++) {
  echo “<p><b>Row number $row</b></p>”;
  echo “<ul>”;
  for ($col = 0; $col < 3; $col++) {
    echo “<li>”.$cars[$row][$col].”</li>”;
  }
  echo “</ul>”;
}
?>

PHP File Upload

Configure The “php.ini” File

First, ensure that PHP is configured to allow file uploads.

In your “php.ini” file, search for the file_uploads directive, and set it to On:

file_uploads = On

Complete Upload File PHP Script

The complete “upload.php” file now looks like this:

<?php
$target_dir = “uploads/”;
$target_file = $target_dir . basename($_FILES[“fileToUpload”][“name”]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST[“submit”])) {
    $check = getimagesize($_FILES[“fileToUpload”][“tmp_name”]);
    if($check !== false) {
        echo “File is an image – ” . $check[“mime”] . “.”;
        $uploadOk = 1;
    } else {
        echo “File is not an image.”;
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo “Sorry, file already exists.”;
    $uploadOk = 0;
}
// Check file size
if ($_FILES[“fileToUpload”][“size”] > 500000) {
    echo “Sorry, your file is too large.”;
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != “jpg” && $imageFileType != “png” && $imageFileType != “jpeg”
&& $imageFileType != “gif” ) {
    echo “Sorry, only JPG, JPEG, PNG & GIF files are allowed.”;
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo “Sorry, your file was not uploaded.”;
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES[“fileToUpload”][“tmp_name”], $target_file)) {
        echo “The file “. basename( $_FILES[“fileToUpload”][“name”]). ” has been uploaded.”;
    } else {
        echo “Sorry, there was an error uploading your file.”;
    }
}
?>

What is a Cookie?

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

PHP Create/Retrieve a Cookie

The following example creates a cookie named “user” with the value “John Doe”. The cookie will expire after 30 days (86400 * 30). The “/” means that the cookie is available in entire website (otherwise, select the directory you prefer).

We then retrieve the value of the cookie “user” (using the global variable $_COOKIE). We also use the isset() function to find out if the cookie is set:

Example

<?php
$cookie_name = “user”;
$cookie_value = “John Doe”;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), “/”); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
    echo “Cookie named ‘” . $cookie_name . “‘ is not set!”;
} else {
    echo “Cookie ‘” . $cookie_name . “‘ is set!<br>”;
    echo “Value is: ” . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

Delete a Cookie

To delete a cookie, use the setcookie() function with an expiration date in the past:

Example

<?php
// set the expiration date to one hour ago
setcookie(“user”, “”, time() – 3600);
?>
<html>
<body>

<?php
echo “Cookie ‘user’ is deleted.”;
?>

</body>
</html>

PHP Sessions

A session is a way to store information (in variables) to be used across multiple pages.

Unlike a cookie, the information is not stored on the users computer.


What is a PHP Session?

When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn’t maintain state.

Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.

So; Session variables hold information about one single user, and are available to all pages in one application.

Tip: If you need a permanent storage, you may want to store the data in a database.


Start a PHP Session

A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

Now, let’s create a new page called “demo_session1.php”. In this page, we start a new PHP session and set some session variables:

Example

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION[“favcolor”] = “green”;
$_SESSION[“favanimal”] = “cat”;
echo “Session variables are set.”;
?>

</body>
</html>

Destroy a PHP Session

To remove all global session variables and destroy the session, use session_unset() and session_destroy():

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session
session_destroy();
?>

</body>
</html>

PHP What is OOP?

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or functions that perform operations on the data, while object-oriented programming is about creating objects that contain both data and functions.

Object-oriented programming has several advantages over procedural programming:

  • OOP is faster and easier to execute
  • OOP provides a clear structure for the programs
  • OOP helps to keep the PHP code DRY “Don’t Repeat Yourself”, and makes the code easier to maintain, modify and debug
  • OOP makes it possible to create full reusable applications with less code and shorter development time

Tip: The “Don’t Repeat Yourself” (DRY) principle is about reducing the repetition of code. You should extract out the codes that are common for the application, and place them at a single place and reuse them instead of repeating it.

A class is a template for objects, and an object is an instance of class.


OOP Case

Let’s assume we have a class named Fruit. A Fruit can have properties like name, color, weight, etc. We can define variables like $name, $color, and $weight to hold the values of these properties.

When the individual objects (apple, banana, etc.) are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.


Define a Class

A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces ({}). All its properties and methods goes inside the braces:

Define Objects

Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values.

Objects of a class is created using the new keyword.

The $this keyword refers to the current object, and is only available inside methods.

Example

<?php
class Fruit {
  // Properties
  public $name;
  public $color;

  // Methods
  function set_name($name) {
    $this->name = $name;
  }
  function get_name() {
    return $this->name;
  }
  function set_color($color) {
    $this->color = $color;
  }
  function get_color() {
    return $this->color;
  }
}

$apple = new Fruit();
$apple->set_name(‘Apple’);
$apple->set_color(‘Red’);
echo “Name: ” . $apple->get_name();
echo “<br>”;
echo “Color: ” . $apple->get_color();
?>

PHP – The __construct Function

A constructor allows you to initialize an object’s properties upon creation of the object.

If you create a __construct() function, PHP will automatically call this function when you create an object from a class.

Notice that the construct function starts with two underscores (__)!

We see in the example below, that using a constructor saves us from calling the set_name() method which reduces the amount of code:

Example

<?php
class Fruit {
  public $name;
  public $color;

  function __construct($name) {
    $this->name = $name;
  }
  function get_name() {
    return $this->name;
  }
}

$apple = new Fruit(“Apple”);
echo $apple->get_name();
?>

PHP – What is Inheritance?

Inheritance in OOP = When a class derives from another class.

The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods.

An inherited class is defined by using the extends keyword.

Let’s look at an example:

Example

<?php
class Fruit {
  public $name;
  public $color;
  public function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }
  public function intro() {
    echo “The fruit is {$this->name} and the color is {$this->color}.”;
  }
}

// Strawberry is inherited from Fruit
class Strawberry extends Fruit {
  public function message() {
    echo “Am I a fruit or a berry? “;
  }
}
$strawberry = new Strawberry(“Strawberry”, “red”);
$strawberry->message();
$strawberry->intro();
?>

Example Explained

The Strawberry class is inherited from the Fruit class.

This means that the Strawberry class can use the public $name and $color properties as well as the public __construct() and intro() methods from the Fruit class because of inheritance.

The Strawberry class also has its own method: message().

PHP – What are Abstract Classes and Methods?

Abstract classes and methods are when the parent class has a named method, but need its child class(es) to fill out the tasks.

An abstract class is a class that contains at least one abstract method. An abstract method is a method that is declared, but not implemented in the code.

An abstract class or method is defined with the abstract keyword:

Syntax

<?php
abstract class ParentClass {
  abstract public function someMethod1();
  abstract public function someMethod2($name, $color);
  abstract public function someMethod3() : string;
}
?>

When inheriting from an abstract class, the child class method must be defined with the same name, and the same or a less restricted access modifier. So, if the abstract method is defined as protected, the child class method must be defined as either protected or public, but not private. Also, the type and number of required arguments must be the same. However, the child classes may have optional arguments in addition.

So, when a child class is inherited from an abstract class, we have the following rules:

  • The child class method must be defined with the same name and it redeclares the parent abstract method
  • The child class method must be defined with the same or a less restricted access modifier
  • The number of required arguments must be the same. However, the child class may have optional arguments in addition

Let’s look at an example:

Example

<?php
// Parent class
abstract class Car {
  public $name;
  public function __construct($name) {
    $this->name = $name;
  }
  abstract public function intro() : string;
}

// Child classes
class Audi extends Car {
  public function intro() : string {
    return “Choose German quality! I’m an $this->name!”;
  }
}

class Volvo extends Car {
  public function intro() : string {
    return “Proud to be Swedish! I’m a $this->name!”;
  }
}

class Citroen extends Car {
  public function intro() : string {
    return “French extravagance! I’m a $this->name!”;
  }
}

// Create objects from the child classes
$audi = new audi(“Audi”);
echo $audi->intro();
echo “<br>”;

$volvo = new volvo(“Volvo”);
echo $volvo->intro();
echo “<br>”;

$citroen = new citroen(“Citroen”);
echo $citroen->intro();
?>

Example Explained

The Audi, Volvo, and Citroen classes are inherited from the Car class. This means that the Audi, Volvo, and Citroen classes can use the public $name property as well as the public __construct() method from the Car class because of inheritance.

But, intro() is an abstract method that should be defined in all the child classes and they should return a string.

PHP – What are Traits?

PHP only supports single inheritance: a child class can inherit only from one single parent.

So, what if a class needs to inherit multiple behaviors? OOP traits solve this problem.

Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).

Traits are declared with the trait keyword

Syntax

<?php
trait TraitName {
  // some code…
}
?>

To use a trait in a class, use the use keyword:

Syntax

<?php
class MyClass {
  use TraitName;
}
?>

Example

<?php
trait message1 {
public function msg1() {
    echo “OOP is fun! “;
  }
}

class Welcome {
  use message1;
}

$obj = new Welcome();
$obj->msg1();
?>

Example Explained

Here, we declare one trait: message1. Then, we create a class: Welcome. The class uses the trait, and all the methods in the trait will be available in the class.

If other classes need to use the msg1() function, simply use the message1 trait in those classes. This reduces code duplication, because there is no need to redeclare the same method over and

PHP Array Functions

FunctionDescription
array()Creates an array
array_change_key_case()Changes all keys in an array to lowercase or uppercase
array_chunk()Splits an array into chunks of arrays
array_column()Returns the values from a single column in the input array
array_combine()Creates an array by using the elements from one “keys” array and one “values” array
array_count_values()Counts all the values of an array
array_diff()Compare arrays, and returns the differences (compare values only)
array_diff_assoc()Compare arrays, and returns the differences (compare keys and values)
array_diff_key()Compare arrays, and returns the differences (compare keys only)
array_diff_uassoc()Compare arrays, and returns the differences (compare keys and values, using a user-defined key comparison function)
array_diff_ukey()Compare arrays, and returns the differences (compare keys only, using a user-defined key comparison function)
array_fill()Fills an array with values
array_fill_keys()Fills an array with values, specifying keys
array_filter()Filters the values of an array using a callback function
array_flip()Flips/Exchanges all keys with their associated values in an array
array_intersect()Compare arrays, and returns the matches (compare values only)
array_intersect_assoc()Compare arrays and returns the matches (compare keys and values)
array_intersect_key()Compare arrays, and returns the matches (compare keys only)
array_intersect_uassoc()Compare arrays, and returns the matches (compare keys and values, using a user-defined key comparison function)
array_intersect_ukey()Compare arrays, and returns the matches (compare keys only, using a user-defined key comparison function)
array_key_exists()Checks if the specified key exists in the array
array_keys()Returns all the keys of an array
array_map()Sends each value of an array to a user-made function, which returns new values
array_merge()Merges one or more arrays into one array
array_merge_recursive()Merges one or more arrays into one array recursively
array_multisort()Sorts multiple or multi-dimensional arrays
array_pad()Inserts a specified number of items, with a specified value, to an array
array_pop()Deletes the last element of an array
array_product()Calculates the product of the values in an array
array_push()Inserts one or more elements to the end of an array
array_rand()Returns one or more random keys from an array
array_reduce()Returns an array as a string, using a user-defined function
array_replace()Replaces the values of the first array with the values from following arrays
array_replace_recursive()Replaces the values of the first array with the values from following arrays recursively
array_reverse()Returns an array in the reverse order
array_search()Searches an array for a given value and returns the key
array_shift()Removes the first element from an array, and returns the value of the removed element
array_slice()Returns selected parts of an array
array_splice()Removes and replaces specified elements of an array
array_sum()Returns the sum of the values in an array
array_udiff()Compare arrays, and returns the differences (compare values only, using a user-defined key comparison function)
array_udiff_assoc()Compare arrays, and returns the differences (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
array_udiff_uassoc()Compare arrays, and returns the differences (compare keys and values, using two user-defined key comparison functions)
array_uintersect()Compare arrays, and returns the matches (compare values only, using a user-defined key comparison function)
array_uintersect_assoc()Compare arrays, and returns the matches (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
array_uintersect_uassoc()Compare arrays, and returns the matches (compare keys and values, using two user-defined key comparison functions)
array_unique()Removes duplicate values from an array
array_unshift()Adds one or more elements to the beginning of an array
array_values()Returns all the values of an array
array_walk()Applies a user function to every member of an array
array_walk_recursive()Applies a user function recursively to every member of an array
arsort()Sorts an associative array in descending order, according to the value
asort()Sorts an associative array in ascending order, according to the value
compact()Create array containing variables and their values
count()Returns the number of elements in an array
current()Returns the current element in an array
each()Deprecated from PHP 7.2. Returns the current key and value pair from an array
end()Sets the internal pointer of an array to its last element
extract()Imports variables into the current symbol table from an array
in_array()Checks if a specified value exists in an array
key()Fetches a key from an array
krsort()Sorts an associative array in descending order, according to the key
ksort()Sorts an associative array in ascending order, according to the key
list()Assigns variables as if they were an array
natcasesort()Sorts an array using a case insensitive “natural order” algorithm
natsort()Sorts an array using a “natural order” algorithm
next()Advance the internal array pointer of an array
pos()Alias of current()
prev()Rewinds the internal array pointer
range()Creates an array containing a range of elements
reset()Sets the internal pointer of an array to its first element
rsort()Sorts an indexed array in descending order
shuffle()Shuffles an array
sizeof()Alias of count()
sort()Sorts an indexed array in ascending order
uasort()Sorts an array by values using a user-defined comparison function
uksort()Sorts an array by keys using a user-defined comparison function
usort()Sorts an array using a user-defined comparison function

Bootstrap Tutorial

Bootstrap

Containers are used to pad the content inside of them, and there are two container classes available:

  1. The .container class provides a responsive fixed width container
  2. The .container-fluid class provides a full width container, spanning the entire width of the viewport

Fixed Container

Use the .container class to create a responsive, fixed-width container.

Note that its width (max-width) will change on different screen sizes:

Extra small
<576px
Small
≥576px
Medium
≥768px
Large
≥992px
Extra large
≥1200px
max-width100%540px720px960px1140px

Open the example below and resize the browser window to see that the container width will change at different breakpoints:

Example

<div class=”container”>
  <h1>My First Bootstrap Page</h1>
  <p>This is some text.</p>
</div>

Fluid Container

Use the .container-fluid class to create a full width container, that will always span the entire width of the screen (width is always 100%):

Example

<div class=”container-fluid”>
  <h1>My First Bootstrap Page</h1>


  <p>This is some text.</p>
</div>

Responsive Containers

You can also use the .container-sm|md|lg|xl classes to create responsive containers.

The max-width of the container will change on different screen sizes/viewports:

ClassExtra small
<576px
Small
≥576px
Medium
≥768px
Large
≥992px
Extra large
≥1200px
.container-sm100%540px720px960px1140px
.container-md100%100%720px960px1140px
.container-lg100%100%100%960px1140px
.container-xl100%100%100%100%1140px

Example

<div class=”container-sm”>.container-sm</div>
<div class=”container-md”>.container-md</div>
<div class=”container-lg”>.container-lg</div>
<div class=”container-xl”>.container-xl</div>

Bootstrap 4 Grid System

Bootstrap’s grid system is built with flexbox and allows up to 12 columns across the page.

If you do not want to use all 12 columns individually, you can group the columns together to create wider columns:

The grid system is responsive, and the columns will re-arrange automatically depending on the screen size.

Make sure that the sum adds up to 12 or fewer (it is not required that you use all 12 available columns).

Grid Classes

The Bootstrap 4 grid system has five classes:

  • .col- (extra small devices – screen width less than 576px)
  • .col-sm- (small devices – screen width equal to or greater than 576px)
  • .col-md- (medium devices – screen width equal to or greater than 768px)
  • .col-lg- (large devices – screen width equal to or greater than 992px)
  • .col-xl- (xlarge devices – screen width equal to or greater than 1200px)

The classes above can be combined to create more dynamic and flexible layouts.

Tip: Each class scales up, so if you wish to set the same widths for sm and md, you only need to specify sm.

Basic Structure of a Bootstrap 4 Grid

The following is a basic structure of a Bootstrap 4 grid:

<!– Control the column width, and how they should appear on different devices –>
<div class=”row”>
  <div class=”col-*-*”></div>
  <div class=”col-*-*”></div>
</div>
<div class=”row”>
  <div class=”col-*-*”></div>
  <div class=”col-*-*”></div>
  <div class=”col-*-*”></div>
</div>

<!– Or let Bootstrap automatically handle the layout –>
<div class=”row”>
  <div class=”col”></div>
  <div class=”col”></div>
  <div class=”col”></div>
</div>

First example: create a row (<div class="row">). Then, add the desired number of columns (tags with appropriate .col-*-* classes). The first star (*) represents the responsiveness: sm, md, lg or xl, while the second star represents a number, which should add up to 12 for each row.

Second example: instead of adding a number to each col, let bootstrap handle the layout, to create equal width columns: two "col" elements = 50% width to each col. three cols = 33.33% width to each col. four cols = 25% width, etc. You can also use .col-sm|md|lg|xl to make the columns responsive.

Below we have collected some examples of basic Bootstrap 4 grid layouts.

Three Equal Columns

.col

.col

.col

The following example shows how to create three equal-width columns, on all devices and screen widths:

Example

<div class=”row”>
  <div class=”col”>.col</div>
  <div class=”col”>.col</div>
  <div class=”col”>.col</div>
</div>

Responsive Columns

.col-sm-3

.col-sm-3

.col-sm-3

.col-sm-3

The following example shows how to create four equal-width columns starting at tablets and scaling to extra large desktops. On mobile phones or screens that are less than 576px wide, the columns will automatically stack on top of each other:

Example

<div class=”row”>
  <div class=”col-sm-3″>.col-sm-3</div>
  <div class=”col-sm-3″>.col-sm-3</div>
  <div class=”col-sm-3″>.col-sm-3</div>
  <div class=”col-sm-3″>.col-sm-3</div>
</div>

Two Unequal Responsive Columns

.col-sm-4

.col-sm-8

The following example shows how to get two various-width columns starting at tablets and scaling to large extra desktops:

Example

<div class=”row”>
  <div class=”col-sm-4″>.col-sm-4</div>
  <div class=”col-sm-8″>.col-sm-8</div>
</div>

Bootstrap 4 Text/Typography

Bootstrap 4 Default Settings

Bootstrap 4 uses a default font-size of 16px, and its line-height is 1.5.

The default font-family is “Helvetica Neue”, Helvetica, Arial, sans-serif.

In addition, all <p> elements have margin-top: 0 and margin-bottom: 1rem (16px by default).

ClassDescriptionExample
.font-weight-boldBold text
.font-weight-bolderBolder text
.font-italicItalic text
.font-weight-lightLight weight text
.font-weight-lighterLighter weight text
.font-weight-normalNormal text
.leadMakes a paragraph stand out
.smallIndicates smaller text (set to 80% of the size of the parent)
.text-leftIndicates left-aligned text
.text-*-leftIndicates left-aligned text on small, medium, large or xlarge screens
.text-breakPrevents long text from breaking layout
.text-centerIndicates center-aligned text
.text-*-centerIndicates center-aligned text on small, medium, large or xlarge screens
.text-decoration-noneRemoves the underline from a link
.text-rightIndicates right-aligned text
.text-*-rightIndicates right-aligned text on small, medium, large or xlarge screens
.text-justifyIndicates justified text
.text-monospaceMonospaced text
.text-nowrapIndicates no wrap text
.text-lowercaseIndicates lowercased text
.text-resetResets the color of a text or a link (inherits the color from its parent)
.text-uppercaseIndicates uppercased text
.text-capitalizeIndicates capitalized text
.initialismDisplays the text inside an <abbr> element in a slightly smaller font size
.list-unstyledRemoves the default list-style and left margin on list items (works on both <ul> and <ol>). This class only applies to immediate children list items (to remove the default list-style from any nested lists, apply this class to any nested lists as well)
.list-inlinePlaces all list items on a single line (used together with .list-inline-item on each <li> elements)
.pre-scrollableMakes a <pre> element scrollable

Bootstrap 4 Colors

Text Colors

Bootstrap 4 has some contextual classes that can be used to provide “meaning through colors”.

The classes for text colors are: .text-muted, .text-primary, .text-success, .text-info, .text-warning, .text-danger, .text-secondary, .text-white, .text-dark, .text-body (default body color/often black) and .text-light:

Background Colors

The classes for background colors are: .bg-primary, .bg-success, .bg-info, .bg-warning, .bg-danger, .bg-secondary, .bg-dark and .bg-light.

Note that background colors do not set the text color, so in some cases you’ll want to use them together with a .text-* class.

Bootstrap 4 Basic Table

A basic Bootstrap 4 table has a light padding and horizontal dividers.

The .table class adds basic styling to a table:

Bordered Table

The .table-bordered class adds borders on all sides of the table and cells

Hover Rows

The .table-hover class adds a hover effect (grey background color) on table rows

Black/Dark Table

The .table-dark class adds a black background to the table

Dark Striped Table

Combine .table-dark and .table-striped to create a dark, striped table

Hoverable Dark Table

The .table-hover class adds a hover effect (grey background color) on table rows

Borderless Table

The .table-borderless class removes borders from the table

The contextual classes that can be used are:

ClassDescription
.table-primaryBlue: Indicates an important action
.table-successGreen: Indicates a successful or positive action
.table-dangerRed: Indicates a dangerous or potentially negative action
.table-infoLight blue: Indicates a neutral informative change or action
.table-warningOrange: Indicates a warning that might need attention
.table-activeGrey: Applies the hover color to the table row or table cell
.table-secondaryGrey: Indicates a slightly less important action
.table-lightLight grey table or table row background
.table-darkDark grey table or table row background

Responsive Tables

The .table-responsive class creates a responsive table: an horizontal scrollbar is added to the table on screens that are less than 992px wide (if needed). When viewing on anything larger than 992px wide, there is no difference

You can also decide when the table should get a scrollbar, depending on screen width:

ClassScreen width
.table-responsive-sm< 576px
.table-responsive-md< 768px
.table-responsive-lg< 992px
.table-responsive-xl< 1200px

Example

<div class=”table-responsive-sm”>
  <table class=”table”>
    …
  </table>
</div>

Bootstrap 4 Images

Rounded Corners

The .rounded class adds rounded corners to an image:

Example

<img src=”cinqueterre.jpg” class=”rounded” alt=”Cinque Terre”>

Circle

The .rounded-circle class shapes the image to a circle:

Example

<img src=”cinqueterre.jpg” class=”rounded-circle” alt=”Cinque Terre”>

Bootstrap 4 Jumbotron

A jumbotron indicates a big grey box for calling extra attention to some special content or information.

Bootstrap 4 Alerts

Alerts are created with the .alert class, followed by one of the contextual classes .alert-success, .alert-info, .alert-warning, .alert-danger, .alert-primary, .alert-secondary, .alert-light or .alert-dark:

Example

<div class=”alert alert-success”>
  <strong>Success!</strong> Indicates a successful or positive action.
</div>

Alert Links

Add the alert-link class to any links inside the alert box to create “matching colored links”:

<div class=”alert alert-success”>
  <strong>Success!</strong> You should <a href=”#” class=”alert-link”>read this message</a>.
</div>

Closing Alerts

To close the alert message, add a .alert-dismissible class to the alert container. Then add class="close" and data-dismiss="alert" to a link or a button element (when you click on this the alert box will disappear).

<div class=”alert alert-success alert-dismissible”>
  <button type=”button” class=”close” data-dismiss=”alert”>&times;</button>
  <strong>Success!</strong> Indicates a successful or positive action.
</div>  

Button Outline

Bootstrap 4 provides eight outline/bordered buttons:

Example

<button type=”button” class=”btn btn-outline-primary”>Primary</button>
<button type=”button” class=”btn btn-outline-secondary”>Secondary</button>
<button type=”button” class=”btn btn-outline-success”>Success</button>
<button type=”button” class=”btn btn-outline-info”>Info</button>
<button type=”button” class=”btn btn-outline-warning”>Warning</button>
<button type=”button” class=”btn btn-outline-danger”>Danger</button>
<button type=”button” class=”btn btn-outline-dark”>Dark</button>
<button type=”button” class=”btn btn-outline-light text-dark”>Light</button>

Active/Disabled Buttons

A button can be set to an active (appear pressed) or a disabled (unclickable) state:

Example

<button type=”button” class=”btn btn-primary active”>Active Primary</button>
<button type=”button” class=”btn btn-primary” disabled>Disabled Primary</button>
<a href=”#” class=”btn btn-primary disabled”>Disabled Link</a>

Spinner Buttons

You can also add “spinners” to a button,

<button class=”btn btn-primary”>
  <span class=”spinner-border spinner-border-sm”></span>
</button>

<button class=”btn btn-primary”>
  <span class=”spinner-border spinner-border-sm”></span>
  Loading..
</button>

<button class=”btn btn-primary” disabled>
  <span class=”spinner-border spinner-border-sm”></span>
  Loading..
</button>

<button class=”btn btn-primary” disabled>
  <span class=”spinner-grow spinner-grow-sm”></span>
  Loading..
</button>

Button Groups

Bootstrap 4 allows you to group a series of buttons together (on a single line) in a button group:

Use a <div> element with class .btn-group to create a button group:

<div class=”btn-group”>
  <button type=”button” class=”btn btn-primary”>Apple</button>
  <button type=”button” class=”btn btn-primary”>Samsung</button>
  <button type=”button” class=”btn btn-primary”>Sony</button>
</div>

Use the class .btn-group-vertical to create a vertical button group:

<div class=”btn-group-vertical”>
  <button type=”button” class=”btn btn-primary”>Apple</button>
  <button type=”button” class=”btn btn-primary”>Samsung</button>
  <button type=”button” class=”btn btn-primary”>Sony</button>
</div>

Bootstrap 4 Badges

Badges are used to add additional information to any content. Use the .badge class together with a contextual class (like .badge-secondary) within <span> elements to create rectangular badges. Note that badges scale to match the size of the parent element (if any):

Example

<h1>Example heading <span class=”badge badge-secondary”>New</span></h1>
<h2>Example heading <span class=”badge badge-secondary”>New</span></h2>
<h3>Example heading <span class=”badge badge-secondary”>New</span></h3>
<h4>Example heading <span class=”badge badge-secondary”>New</span></h4>
<h5>Example heading <span class=”badge badge-secondary”>New</span></h5>
<h6>Example heading <span class=”badge badge-secondary”>New</span></h6>

Contextual Badges

Use any of the contextual classes (.badge-*) to change the color of a badge:

Example

<span class=”badge badge-primary”>Primary</span>
<span class=”badge badge-secondary”>Secondary</span>
<span class=”badge badge-success”>Success</span>
<span class=”badge badge-danger”>Danger</span>
<span class=”badge badge-warning”>Warning</span>
<span class=”badge badge-info”>Info</span>
<span class=”badge badge-light”>Light</span>
<span class=”badge badge-dark”>Dark</span>

Basic Progress Bar

A progress bar can be used to show a user how far along he/she is in a process.

To create a default progress bar, add a .progress class to a container element and add the .progress-bar class to its child element. Use the CSS width property to set the width of the progress bar:

Example

<div class=”progress”>
  <div class=”progress-bar” style=”width:70%”></div>
</div>

Use the .progress-bar-striped class to add stripes to the progress bars:

<div class=”progress”>
  <div class=”progress-bar progress-bar-striped” style=”width:40%”></div>
</div>

Growing Spinners

Use the .spinner-grow class if you want the spinner/loader to grow instead of “spin”:

Example

<div class=”spinner-grow text-muted”></div>
<div class=”spinner-grow text-primary”></div>
<div class=”spinner-grow text-success”></div>
<div class=”spinner-grow text-info”></div>
<div class=”spinner-grow text-warning”></div>
<div class=”spinner-grow text-danger”></div>
<div class=”spinner-grow text-secondary”></div>
<div class=”spinner-grow text-dark”></div>
<div class=”spinner-grow text-light”></div>

Basic Pagination

If you have a web site with lots of pages, you may wish to add some sort of pagination to each page.

To create a basic pagination, add the .pagination class to an <ul> element. Then add the .page-item to each <li> element and a .page-link class to each link inside <li>:

Example

<ul class=”pagination”>
  <li class=”page-item”><a class=”page-link” href=”#”>Previous</a></li>
  <li class=”page-item”><a class=”page-link” href=”#”>1</a></li>
  <li class=”page-item”><a class=”page-link” href=”#”>2</a></li>
  <li class=”page-item”><a class=”page-link” href=”#”>3</a></li>
  <li class=”page-item”><a class=”page-link” href=”#”>Next</a></li>
</ul>

Active State

The .active class is used to “highlight” the current page:

Example

<ul class=”pagination”>
  <li class=”page-item”><a class=”page-link” href=”#”>Previous</a></li>
  <li class=”page-item”><a class=”page-link” href=”#”>1</a></li>
  <li class=”page-item active”><a class=”page-link” href=”#”>2</a></li>
  <li class=”page-item”><a class=”page-link” href=”#”>3</a></li>
  <li class=”page-item”><a class=”page-link” href=”#”>Next</a></li>
</ul>

Bootstrap 4 Cards

Cards

A card in Bootstrap 4 is a bordered box with some padding around its content. It includes options for headers, footers, content, colors, etc.

Basic Card

A basic card is created with the .card class, and content inside the card has a .card-body class:

Basic card

Example

<div class=”card”>
  <div class=”card-body”>Basic card</div>
</div>

The .card-header class adds a heading to the card and the .card-footer class adds a footer to the card:

Example

<div class=”card”>
  <div class=”card-header”>Header</div>
  <div class=”card-body”>Content</div>
  <div class=”card-footer”>Footer</div>
</div>

Contextual Cards

To add a background color the card, use contextual classes (.bg-primary, .bg-success, .bg-info, .bg-warning, .bg-danger, .bg-secondary, .bg-dark and .bg-light.

Titles, text, and links

Card title

Some example text. Some example text.

Card link Another link

Use .card-title to add card titles to any heading element. The .card-text class is used to remove bottom margins for a <p> element if it is the last child (or the only one) inside .card-body. The .card-link class adds a blue color to any link, and a hover effect.

Example

<div class=”card”>
  <div class=”card-body”>
    <h4 class=”card-title”>Card title</h4>
    <p class=”card-text”>Some example text. Some example text.</p>
    <a href=”#” class=”card-link”>Card link</a>
    <a href=”#” class=”card-link”>Another link</a>
  </div>
</div>

Add .card-img-top or .card-img-bottom to an <img> to place the image at the top or at the bottom inside the card. Note that we have added the image outside of the .card-body to span the entire width:

Example

<div class=”card” style=”width:400px”>
  <img class=”card-img-top” src=”img_avatar1.png” alt=”Card image”>
  <div class=”card-body”>
    <h4 class=”card-title”>John Doe</h4>
    <p class=”card-text”>Some example text.</p>
    <a href=”#” class=”btn btn-primary”>See Profile</a>
  </div>
</div>

The .card-columns class creates a masonry-like grid of cards (like pinterest). The layout will automatically adjust as you insert more cards.

Note: The cards are displayed vertically on small screens (less than 576px):

Example

<div class=”card-columns”>
  <div class=”card bg-primary”>
    <div class=”card-body text-center”>
      <p class=”card-text”>Some text inside the first card</p>
    </div>
  </div>
  <div class=”card bg-warning”>
    <div class=”card-body text-center”>
      <p class=”card-text”>Some text inside the second card</p>
    </div>
  </div>
  <div class=”card bg-success”>
    <div class=”card-body text-center”>
      <p class=”card-text”>Some text inside the third card</p>
    </div>
  </div>
  <div class=”card bg-danger”>
    <div class=”card-body text-center”>
      <p class=”card-text”>Some text inside the fourth card</p>
    </div>
  </div>
  <div class=”card bg-light”>
    <div class=”card-body text-center”>
      <p class=”card-text”>Some text inside the fifth card</p>
    </div>
  </div>
  <div class=”card bg-info”>
    <div class=”card-body text-center”>
      <p class=”card-text”>Some text inside the sixth card</p>
    </div>
  </div>
</div>

Basic Collapsible

Collapsibles are useful when you want to hide and show large amount of content:

<button data-toggle=”collapse” data-target=”#demo”>Collapsible</button>

<div id=”demo” class=”collapse”>
Lorem ipsum dolor text….
</div>

Example Explained

The .collapse class indicates a collapsible element (a <div> in our example); this is the content that will be shown or hidden with a click of a button.

To control (show/hide) the collapsible content, add the data-toggle="collapse" attribute to an <a> or a <button> element. Then add the data-target="#id" attribute to connect the button with the collapsible content (<div id=”demo”>).

Note: For <a> elements, you can use the href attribute instead of the data-target attribute:

Accordion

Example

<div id=”accordion”>

  <div class=”card”>
    <div class=”card-header”>
      <a class=”card-link” data-toggle=”collapse” href=”#collapseOne”>
        Collapsible Group Item #1
      </a>
    </div>
    <div id=”collapseOne” class=”collapse show” data-parent=”#accordion”>
      <div class=”card-body”>
        Lorem ipsum..
      </div>
    </div>
  </div>

  <div class=”card”>
    <div class=”card-header”>
      <a class=”collapsed card-link” data-toggle=”collapse” href=”#collapseTwo”>
        Collapsible Group Item #2
      </a>
    </div>
    <div id=”collapseTwo” class=”collapse” data-parent=”#accordion”>
      <div class=”card-body”>
        Lorem ipsum..
      </div>
    </div>
  </div>

  <div class=”card”>
    <div class=”card-header”>
      <a class=”collapsed card-link” data-toggle=”collapse” href=”#collapseThree”>
        Collapsible Group Item #3
      </a>
    </div>
    <div id=”collapseThree” class=”collapse” data-parent=”#accordion”>
      <div class=”card-body”>
        Lorem ipsum..
      </div>
    </div>
  </div>

</div>

Navbar

Very often, especially on small screens, you want to hide the navigation links and replace them with a button that should reveal them when clicked on.

To create a collapsible navigation bar, use a button with class="navbar-toggler", data-toggle="collapse" and data-target="#thetarget". Then wrap the navbar content (links, etc) inside a div element with class="collapse navbar-collapse", followed by an id that matches the data-target of the button: “thetarget“.

Example

<nav class=”navbar navbar-expand-md bg-dark navbar-dark”>
  <!– Brand –>
  <a class=”navbar-brand” href=”#”>Navbar</a>

  <!– Toggler/collapsibe Button –>
  <button class=”navbar-toggler” type=”button” data-toggle=”collapse” data-target=”#collapsibleNavbar”>
    <span class=”navbar-toggler-icon”></span>
  </button>

  <!– Navbar links –>
  <div class=”collapse navbar-collapse” id=”collapsibleNavbar”>
    <ul class=”navbar-nav”>
      <li class=”nav-item”>
        <a class=”nav-link” href=”#”>Link</a>
      </li>
      <li class=”nav-item”>
        <a class=”nav-link” href=”#”>Link</a>
      </li>
      <li class=”nav-item”>
        <a class=”nav-link” href=”#”>Link</a>
      </li>
    </ul>
  </div>
</nav>

Form Validation

You can use different validation classes to provide valuable feedback to users. Add either .was-validated or .needs-validation to the <form> element, depending on whether you want to provide validation feedback before or after submitting the form. The input fields will have a green (valid) or red (invalid) border to indicate what’s missing in the form. You can also add a .valid-feedback or .invalid-feedback message to tell the user explicitly what’s missing, or needs to be done before submitting the form.

Example

In this example, we use .was-validated to indicate what’s missing before submitting the form:

<form action=”/action_page.php” class=”was-validated”>
  <div class=”form-group”>
    <label for=”uname”>Username:</label>
    <input type=”text” class=”form-control” id=”uname” placeholder=”Enter username” name=”uname” required>
    <div class=”valid-feedback”>Valid.</div>
    <div class=”invalid-feedback”>Please fill out this field.</div>
  </div>
  <div class=”form-group”>
    <label for=”pwd”>Password:</label>
    <input type=”password” class=”form-control” id=”pwd” placeholder=”Enter password” name=”pswd” required>
    <div class=”valid-feedback”>Valid.</div>
    <div class=”invalid-feedback”>Please fill out this field.</div>
  </div>
  <div class=”form-group form-check”>
    <label class=”form-check-label”>
      <input class=”form-check-input” type=”checkbox” name=”remember” required> I agree on blabla.
      <div class=”valid-feedback”>Valid.</div>
      <div class=”invalid-feedback”>Check this checkbox to continue.</div>
    </label>
  </div>
  <button type=”submit” class=”btn btn-primary”>Submit</button>
</form>

Bootstrap supports the following form controls:

  • input
  • textarea
  • checkbox
  • radio
  • select

Bootstrap 4 Input Groups

The .input-group class is a container to enhance an input by adding an icon, text or a button in front or behind the input field as a “help text”.

Use .input-group-prepend to add the help text in front of the input, and .input-group-append to add it behind the input.

At last, add the .input-group-text class to style the specified help text.

<form>
  <div class=”input-group mb-3″>
    <div class=”input-group-prepend”>
      <span class=”input-group-text”>@</span>
    </div>
    <input type=”text” class=”form-control” placeholder=”Username”>
  </div>

  <div class=”input-group mb-3″>
    <input type=”text” class=”form-control” placeholder=”Your Email”>
    <div class=”input-group-append”>
      <span class=”input-group-text”>@example.com</span>
    </div>
  </div>
</form>

How To Create a Carousel

The following example shows how to create a basic carousel with indicators and controls:

Example

<div id=”demo” class=”carousel slide” data-ride=”carousel”>

  <!– Indicators –>
  <ul class=”carousel-indicators”>
    <li data-target=”#demo” data-slide-to=”0″ class=”active”></li>
    <li data-target=”#demo” data-slide-to=”1″></li>
    <li data-target=”#demo” data-slide-to=”2″></li>
  </ul>

  <!– The slideshow –>
  <div class=”carousel-inner”>
    <div class=”carousel-item active”>
      <img src=”la.jpg” alt=”Los Angeles”>
    </div>
    <div class=”carousel-item”>
      <img src=”chicago.jpg” alt=”Chicago”>
    </div>
    <div class=”carousel-item”>
      <img src=”ny.jpg” alt=”New York”>
    </div>
  </div>

  <!– Left and right controls –>
  <a class=”carousel-control-prev” href=”#demo” data-slide=”prev”>
    <span class=”carousel-control-prev-icon”></span>
  </a>
  <a class=”carousel-control-next” href=”#demo” data-slide=”next”>
    <span class=”carousel-control-next-icon”></span>
  </a>

</div>

Example explained

A description of what each class from the example above do:

ClassDescription
.carouselCreates a carousel
.carousel-indicatorsAdds indicators for the carousel. These are the little dots at the bottom of each slide (which indicates how many slides there are in the carousel, and which slide the user are currently viewing)
.carousel-innerAdds slides to the carousel
.carousel-itemSpecifies the content of each slide
.carousel-control-prevAdds a left (previous) button to the carousel, which allows the user to go back between the slides
.carousel-control-nextAdds a right (next) button to the carousel, which allows the user to go forward between the slides
.carousel-control-prev-iconUsed together with .carousel-control-prev to create a “previous” button
.carousel-control-next-iconUsed together with .carousel-control-next to create a “next” button
.slideAdds a CSS transition and animation effect when sliding from one item to the next. Remove this class if you do not want this effect

How To Create a Modal

The following example shows how to create a basic modal:

Example

<!– Button to Open the Modal –>
<button type=”button” class=”btn btn-primary” data-toggle=”modal” data-target=”#myModal”>
  Open modal
</button>

<!– The Modal –>
<div class=”modal” id=”myModal”>
  <div class=”modal-dialog”>
    <div class=”modal-content”>

      <!– Modal Header –>
      <div class=”modal-header”>
        <h4 class=”modal-title”>Modal Heading</h4>
        <button type=”button” class=”close” data-dismiss=”modal”>&times;</button>
      </div>

      <!– Modal body –>
      <div class=”modal-body”>
        Modal body..
      </div>

      <!– Modal footer –>
      <div class=”modal-footer”>
        <button type=”button” class=”btn btn-danger” data-dismiss=”modal”>Close</button>
      </div>

    </div>
  </div>
</div>

How To Create a Tooltip

To create a tooltip, add the data-toggle="tooltip" attribute to an element.

Use the title attribute to specify the text that should be displayed inside the tooltip:

<a href=”#” data-toggle=”tooltip” title=”Hooray!”>Hover over me</a>

Note: Tooltips must be initialized with jQuery: select the specified element and call the tooltip() method.

The following code will enable all tooltips in the document:

Example

<script>
$(document).ready(function(){
  $(‘[data-toggle=”tooltip”]’).tooltip();
});
</script>

How To Create a Popover

To create a popover, add the data-toggle="popover" attribute to an element.

Use the title attribute to specify the header text of the popover, and use the data-content attribute to specify the text that should be displayed inside the popover’s body:

<a href=”#” data-toggle=”popover” title=”Popover Header” data-content=”Some content inside the popover”>Toggle popover</a>

Note: Popovers must be initialized with jQuery: select the specified element and call the popover() method.

The following code will enable all popovers in the document:

Example

<script>
$(document).ready(function(){
  $(‘[data-toggle=”popover”]’).popover();
});
</script>

How To Create a Scrollspy

The following example shows how to create a scrollspy:

Example

<!– The scrollable area –>
<body data-spy=”scroll” data-target=”.navbar” data-offset=”50″>

<!– The navbar – The <a> elements are used to jump to a section in the scrollable area –>
<nav class=”navbar navbar-expand-sm bg-dark navbar-dark fixed-top”>

  <ul class=”navbar-nav”>
    <li><a href=”#section1″>Section 1</a></li>
    …
</nav>

<!– Section 1 –>
<div id=”section1″>
  <h1>Section 1</h1>
  <p>Try to scroll this page and look at the navigation bar while scrolling!</p>
</div>


</body>

Example Explained

Add data-spy="scroll" to the element that should be used as the scrollable area (often this is the <body> element).

Then add the data-target attribute with a value of the id or the class name of the navigation bar (.navbar). This is to make sure that the navbar is connected with the scrollable area.

Note that scrollable elements must match the ID of the links inside the navbar’s list items (<div id="section1"> matches <a href="#section1">).

The optional data-offset attribute specifies the number of pixels to offset from top when calculating the position of scroll. This is useful when you feel that the links inside the navbar changes the active state too soon or too early when jumping to the scrollable elements. Default is 10 pixels.

Requires relative positioning: The element with data-spy=”scroll” requires the CSS position property, with a value of “relative” to work properly.

Responsive Flex Classes

All flex classes comes with additional responsive classes, which makes it easy to set a specific flex class on a specific screen size.

The * symbol can be replaced with sm, md, lg or xl, which represents small, medium, large or xlarge screens.

ClassDescriptionExample
Flex Container  
.d-*-flexCreates a flexbox container for different screens
.d-*-inline-flexCreates an inline flexbox container for different screens
Direction  
.flex-*-rowDisplay flex items horizontally on different screens
.flex-*-row-reverseDisplay flex items horizontally, and right-aligned, on different screens
.flex-*-columnDisplay flex items vertically on different screens
.flex-*-column-reverseDisplay flex items vertically, with reversed order, on different screens screens
Justified Content  
.justify-content-*-startDisplay flex items from the start (left-aligned) on different screens
.justify-content-*-endDisplay flex items at the end (right-aligned) on different screens
.justify-content-*-centerDisplay flex items in the center of a flex container on different screens
.justify-content-*-betweenDisplay flex items in “between” on different screens
.justify-content-*-aroundDisplay flex items “around” on different screens
Fill / Equal Width  
.flex-*-fillForce flex items into equal widths on different screens
Grow  
.flex-*-grow-0Don’t make the items grow on different screens 
.flex-*-grow-1Make items grow on different screens 
Shrink  
.flex-*-shrink-0Don’t make the items shrink on diferent screens 
.flex-*-shrink-1Make items shrink on different screens 
Order  
.order-*-0-12Change the order from 0 to 12 on small screens
Wrap  
.flex-*-nowrapDon’t wrap items on different screens
.flex-*-wrapWrap items on different screens
.flex-*-wrap-reverseReverse the wrapping of items on different screens
Align Content  
.align-content-*-startAlign gathered items from the start on different screens
.align-content-*-endAlign gathered items at the end on different screens
.align-content-*-centerAlign gathered items in the center on different screens
.align-content-*-aroundAlign gathered items “around” on different screens
.align-content-*-stretchStretch gathered items on different screens
Align Items  
.align-items-*-startAlign single rows of items from the start on different screens
.align-items-*-endAlign single rows of items at the end on different screens
.align-items-*-centerAlign single rows of items in the center on different screens
.align-items-*-baselineAlign single rows of items on the baseline on different screens
.align-items-*-stretchStretch single rows of items on different screens
Align Self  
.align-self-*-startAlign a flex item from the start on different screens
.align-self-*-endAlign a flex item at the end on different screens
.align-self-*-centerAlign a flex item in the center on different screens
.align-self-*-baselineAlign a flex item on the baseline on different screens
.align-self-*-stretchStretch a flex item on different screens

Filter Tables

Perform a case-insensitive search for items in a table:

jQuery

<script>
$(document).ready(function(){
  $(“#myInput”).on(“keyup”, function() {
    var value = $(this).val().toLowerCase();
    $(“#myTable tr”).filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
</script>

Example explained: We use jQuery to loop through each table rows to check if there are any text values that matches the value of the input field. The toggle method hides the row (display:none) that does not match the search. We use the toLowerCase() method to convert the text to lower case, which makes the search case insensitive (allows “john”, “John”, and even “JOHN” on search).

Bootstrap 4 Grid System

Bootstrap’s grid system is responsive, and the columns will re-arrange depending on the screen size: On a big screen it might look better with the content organized in three columns, but on a small screen it would be better if the content items were stacked on top of each other.


Grid Classes

The Bootstrap 4 grid system has five classes:

  • .col- (extra small devices – screen width less than 576px)
  • .col-sm- (small devices – screen width equal to or greater than 576px)
  • .col-md- (medium devices – screen width equal to or greater than 768px)
  • .col-lg- (large devices – screen width equal to or greater than 992px)
  • .col-xl- (xlarge devices – screen width equal to or greater than 1200px)

The classes above can be combined to create more dynamic and flexible layouts.

Tip: Each class scales up, so if you wish to set the same widths for sm and md, you only need to specify sm.


Grid System Rules

Some Bootstrap 4 grid system rules:

  • Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper alignment and padding
  • Use rows to create horizontal groups of columns
  • Content should be placed within columns, and only columns may be immediate children of rows
  • Predefined classes like .row and .col-sm-4 are available for quickly making grid layouts
  • Columns create gutters (gaps between column content) via padding. That padding is offset in rows for the first and last column via negative margin on .rows
  • Grid columns are created by specifying the number of 12 available columns you wish to span. For example, three equal columns would use three .col-sm-4
  • Column widths are in percentage, so they are always fluid and sized relative to their parent element
  • The biggest difference between Bootstrap 3 and Bootstrap 4 is that Bootstrap 4 now uses flexbox, instead of floats. One big advantage with flexbox is that grid columns without a specified width will automatically layout as “equal width columns” (and equal height). Example: Three elements with .col-sm will each automatically be 33.33% wide from the small breakpoint and up. Tip: If you want to learn more about Flexbox, you can read our CSS Flexbox Tutorial.

Note that Flexbox is not supported in IE9 and earlier versions.

Basic Structure of a Bootstrap 4 Grid

The following is a basic structure of a Bootstrap 4 grid:

<!– Control the column width, and how they should appear on different devices –>
<div class=”row”>
  <div class=”col-*-*”></div>
  <div class=”col-*-*”></div>
  <div class=”col-*-*”></div>
</div>

<!– Or let Bootstrap automatically handle the layout –>
<div class=”row”>
  <div class=”col”></div>
  <div class=”col”></div>
  <div class=”col”></div>
  <div class=”col”></div>
</div>

First example: create a row (<div class="row">). Then, add the desired number of columns (tags with appropriate .col-*-* classes). The first star (*) represents the responsiveness: sm, md, lg or xl, while the second star represents a number, which should always add up to 12 for each row.

Second example: instead of adding a number to each col, let bootstrap handle the layout, to create equal width columns: two "col" elements = 50% width to each col. three cols = 33.33% width to each col. four cols = 25% width, etc. You can also use .col-sm|md|lg|xl to make the columns responsive.

Grid Options

The following table summarizes how the Bootstrap 4 grid system works across different screen sizes:

 Extra small (<576px)Small (>=576px)Medium (>=768px)Large (>=992px)Extra Large (>=1200px)
Class prefix.col-.col-sm-.col-md-.col-lg-.col-xl-
Grid behaviourHorizontal at all timesCollapsed to start, horizontal above breakpointsCollapsed to start, horizontal above breakpointsCollapsed to start, horizontal above breakpointsCollapsed to start, horizontal above breakpoints
Container widthNone (auto)540px720px960px1140px
Suitable forPortrait phonesLandscape phonesTabletsLaptopsLaptops and Desktops
# of columns1212121212
Gutter width30px (15px on each side of a column)30px (15px on each side of a column)30px (15px on each side of a column)30px (15px on each side of a column)30px (15px on each side of a column)
NestableYesYesYesYesYes
OffsetsYesYesYesYesYes
Column orderingYesYesYesYesYes

Complete List of All Bootstrap 4 Classes

.activeAdds a white text color to the active link in a navbar.
Navbar
.activeAdds a blue background color to the active list item in a list group
List Groups
.activeAdds a dark-blue background color to simulate a “pressed” button
Buttons
.activeAdds a blue background color to the active dropdown item in a dropdown
Dropdowns
.activeAdds a blue background color to the active pagination link (to highlight the current page)
Pagination
.activeDisplays/shows the current carousel item
Carousel
.alertCreates an alert message box
Alerts
.alert-dangerRed alert. Indicates a dangerous or potentially negative action
Alerts
.alert-darkDark alert. Dark grey alert box
Alerts
.alert-dismissibleIndicates a closable alert box. Together with the .close class, this class is used to close the alert (adds extra padding)
Alerts
.alert-headingAdds color:inherit to the specified element
Alerts
.alert-infoTeal alert. Indicates a neutral informative change or action
Alerts
.alert-lightLight alert. Light grey alert box
Alerts
.alert-linkUsed on links inside alerts to provide matching colored links
Alerts
.alert-primaryBlue alert. Indicates an important action
Alerts
.alert-secondaryGrey alert. Indicates a “less” important action
Alerts
.alert-successGreen alert. Indicates a successful or positive action
Alerts
.alert-warningYellow alert. Indicates caution should be taken with this action
Alerts
.align-baselineThe element is aligned with the baseline of the parent. This is default
Utilities
.align-bottomThe element is aligned with the lowest element on the line
Utilities
.align-middleThe element is placed in the middle of the parent element
Utilities
.align-topThe element is aligned with the top of the tallest element on the line
Utilities
.align-text-topThe element is aligned with the top of the parent element’s font
Utilities
.align-text-bottomThe element is aligned with the bottom of the parent element’s font
Utilities
.align-content-aroundAlign gathered items “around”
Flex
.align-content-*-aroundAlign gathered items “around” on different screens
Flex
.align-content-centerAlign gathered items in the center
Flex
.align-content-*-centerAlign gathered items in the center on different screens
Flex
.align-content-endAlign gathered items at the end
Flex
.align-content-*-endAlign gathered items at the end on different screens
Flex
.align-content-startAlign gathered items from the start
Flex
.align-content-*-startAlign gathered items from the start on different screens
Flex
.align-content-stretchStretch gathered items
Flex
.align-content-*-stretchStretch gathered items on different screens
Flex
.align-items-startAlign single rows of items from the start
Flex
.align-items-*-startAlign single rows of items from the start on different screens
Flex
.align-items-endAlign single rows of items at the end
Flex
.align-items-*-endAlign single rows of items at the end on different screens
Flex
.align-items-centerAlign single rows of items in the center
Flex
.align-items-*-centerAlign single rows of items in the center on different screens
Flex
.align-items-baselineAlign single rows of items at the baseline
Flex
.align-items-*-baselineAlign single rows of items at the baseline on different screens
Flex
.align-items-stretchStretch single rows of items
Flex
.align-items-*-stretchStretch single rows of items on different screens
Flex
.align-self-startAlign a flex item from the start
Flex
.align-self-*-startAlign a flex item from the start on different screens
Flex
.align-self-endAlign a flex item at the end
Flex
.align-self-*-endAlign a flex item at the end on different screens
Flex
.align-self-centerAlign a flex item in the center
Flex
.align-self-*-centerAlign a flex item in the center on different screens
Flex
.align-self-baselineAlign a flex item at the baseline
Flex
.align-self-*-baselineAlign a flex item at the baseline on different screens
Flex
.align-self-stretchStretch a flex item
Flex
.align-self-*-stretchStretch a flex item on different screens
Flex
.badgeCreates a circular badge (grey circle – often used as a numerical indicator)
Badges
.badge-dangerRed badge. Indicates a dangerous or potentially negative action
Badges
.badge-darkDark badge. Dark grey alert box
Badges
.badge-infoTeal badge. Indicates a neutral informative change or action
Badges
.badge-lightLight badge. Light grey alert box
Badges
.badge-pillMakes a badge more round
Badges
.badge-primaryBlue badge. Indicates an important action
Badges
.badge-secondaryGrey badge. Indicates a “less” important action
Badges
.badge-successGreen badge. Indicates a successful or positive action
Badges
.badge-warningYellow badge. Indicates caution should be taken with this action
Badges
.bg-dangerAdds a red background color to an element. Represents danger or a negative action
Colors
.bg-darkAdds a dark grey background color to an element
Colors
.bg-infoAdds a teal background color to an element. Represents some information
Colors
.bg-lightAdds a light grey background color to an element
Colors
.bg-primaryAdds a blue background color to an element. Represents something important
Colors
.bg-secondaryAdds a grey background color to an element. Indicates a “less” important action
Colors
.bg-successAdds a green background color to an element. Indicates success or a positive action
Colors
.bg-warningAdds a yellow/orange background color to an element. Represents a warning or a negative action
Colors
.blockquoteStyles quoted blocks of content from another source (adds a larger font-size (1.25rem))
Typography
.blockquote-footerStyles the source title inside the blockquote (light grey text with indentation)
Typography
.borderAdds a border to an element
Utilities
.border-bottom-0Removes the bottom border from an element
Utilities
.border-dangerAdds a red border to an element (indicates danger)
Utilities
.border-darkAdds a dark border to an element
Utilities
.border-infoAdds a teal border to an element (indicates information)
Utilities
.border-left-0Removes the left border from an element
Utilities
.border-lgAdds a large border to an element
Utilities
.border-lightAdds a light grey border to an element
Utilities
.border-primaryAdds a blue border to an element
Utilities
.border-right-0Removes the right border from an element
Utilities
.border-top-0Removes the top border from an element
Utilities
.border-secondaryAdds a grey border to an element
Utilities
.border-smAdds a small border to an element
Utilities
.border-successAdds a green border to an element (indicates success)
Utilities
.border-warningAdds a orange border to an element (indicates warning)
Utilities
.border-whiteAdds a white border to an element
Utilities
.border-0Removes all borders from an element
Utilities
.breadcrumbA pagination. Indicates the current page’s location within a navigational hierarchy
Pagination
.breadcrumb-itemStyles list items or links inside the breadcrumb
Pagination
.btnCreates a basic button (gray background and rounded corners)
Buttons
.btn-blockCreates a block level button that spans the entire width of the parent element
Buttons
.btn-darkDark grey button
Buttons
.btn-dangerRed button. Indicates danger or a negative action
Buttons
.btn-groupGroups buttons together on a single line
Button Groups
.btn-group-lgLarge button group (makes all buttons in a button group larger – increased font-size and padding)
Button Groups
.btn-group-smSmall button group (makes all buttons in a button group smaller)
Button Groups
.btn-group-verticalMakes a button group appear vertically stacked
Button Groups
.btn-infoTeal button. Represents a neutral informative change or action
Buttons
.btn-lightLight grey button
Buttons
.btn-linkMakes a button look like a link (get button behavior)
Buttons
.btn-lgLarge button
Buttons
.btn-outline-darkDark grey bordered/outlined button
Buttons
.btn-outline-dangerRed bordered/outlined button. Indicates danger or a negative action
Buttons
.btn-outline-infoTeal bordered/outlined button. Represents a neutral informative change or action
Buttons
.btn-outline-lightLight grey bordered/outlined button
Buttons
.btn-outline-primaryBlue bordered/outlined button.
Buttons
.btn-outline-secondaryGrey bordered/outlined button. Indicates a “less” important action
Buttons
.btn-outline-successGreen bordered/outlined button. Indicates success or a positive action
Buttons
.btn-outline-warningOrange bordered/outlined button. Represents warning or a negative action
Buttons
.btn-primaryBlue button. Indicates a something important
Buttons
.btn-smSmall button
Buttons
.btn-secondaryGrey button. Indicates a “less” important action
Buttons
.btn-successGreen button. Indicates success or a positive action
Buttons
.btn-toolbarCombine sets of button groups into button toolbars for more complex components
Button Groups
.btn-warningOrange button. Represents warning or a negative action
Buttons
.cardCreates a card
Cards
.card-bodyContainer for card content
Cards
.card-columnsContainer to create a masonry-like grid of cards
Cards
.card-dangerAdds a red background color to the card. Represents danger or a negative action
Cards
.card-darkAdds a grey background color to the card
Cards
.card-deckContainer to create a grid of cards that are of equal height and width
Cards
.card-footerCard footer
Cards
.card-groupContainer to create a grid of cards that are of equal height and width, without side margins
Cards
.card-headerCard header
Cards
.card-header-tabsStyles navigation tabs inside the card header
Cards
.card-header-pillsStyles navigation pills inside the card header
Cards
.card-img-bottomPlace the image at the bottom inside a card
Cards
.card-img-overlayTurns an image into a card background. Often used to add text on top of the image
Cards
.card-img-topPlace the image at the top inside a card
Cards
.card-infoAdds a teal background color to the card. Represents some information
Cards
.card-lightAdds a light grey background color to the card
Cards
.card-linkAdds a blue color to any link and a hover effect inside the card
Cards
.card-primaryAdds a blue background color to the card. Represents something important
Cards
.card-secondaryAdds a grey background color to the card. Represents something “less” important
Cards
.card-subtitleThe .card-subtitle is used after a .card-title, and adds the following to an element: margin-top: -.375rem; margin-bottom: 0;
Cards
.card-successAdds a green background color to the card. Indicates success or a positive action
Cards
.card-textUsed to remove bottom margins for a p element if it is the last child (or the only one), inside .card-body
Cards
.card-titleAdds a title to any heading element inside the card
Cards
.card-warningAdds a yellow/orange background color to the card. Represents a warning or a negative action
Cards
.carouselCreates a carousel (slideshow)
Carousel
.carousel-captionCreates a caption text for each slide in the carousel
Carousel
.carousel-control-nextContainer for “next” carousel/item link
Carousel
.carousel-control-next-iconUsed together with .carousel-control-next to create a “next” icon/button (right-pointed arrow)
Carousel
.carousel-control-prevContainer for “previous” carousel/item link
Carousel
.carousel-control-prev-iconUsed together with .carousel-control-prev to create a “previous” icon/button (left-pointed arrow)
Carousel
.carousel-indicatorsAdds little dots/indicators at the bottom of each slide (which indicates how many slides there is in the carousel, and which slide the user are currently viewing)
Carousel
.carousel-innerContainer for slide items
Carousel
.carousel-itemSpecifies the content of each slide
Carousel
.clearfixClears floats
Utilities
.closeStyles a close icon. This is often used for alerts and modals. Often used together with the &times; symbol to create the actual icon (a better looking “x”). It floats right by default
Utilities
.col-autoMake form columns automatically size themselves based on their content
Forms
.col-*Creates a column layout for extra small devices (and up/all devices, if not combined with other column classes). The * can be a number between 1 and 12
Grid System
.col-sm-*Creates a column layout for small devices (and up, if not combined with other column classes). The * can be a number between 1 and 12
Grid System
.col-md-*Creates a column layout for medium devices (and up, if not combined with other column classes). The * can be a number between 1 and 12
Grid System
.col-lg-*Creates a column layout for large devices (and up, if not combined with other column classes). The * can be a number between 1 and 12
Grid System
.col-xl-*Creates a column layout for extra large devices. The * can be a number between 1 and 12
Grid System
.collapseIndicates collapsible content – which can be hidden or shown on demand
Collapse
.collapse showShow the collapsible content by default
Collapse
.containerFixed width container with widths determined by screen sites. Equal margin on the left and right.
Containers
.container-fluidA container that spans the full width of the screen
Containers
.container-*Responsive containers
Containers
.custom-checkboxA wrapper/container for custom checkboxes
Custom Forms
.custom-controlA wrapper/container for custom forms
Custom Forms
.custom-control-inputCustomized form control
Custom Forms
.custom-control-inlineInline (horizontally – side by side) customized form controls
Custom Forms
.custom-control-labelCustomized label, when used together with a custom form control
Custom Forms
.custom-fileCustomized file upload
Custom Forms
.custom-file-inputCustomized file upload
Custom Forms
.custom-file-labelCustomized file label
Custom Forms
.custom-radioA wrapper/container for custom radio buttons
Custom Forms
.custom-rangeCustomized range control
Custom Forms
.custom-selectCustomized select menu
Custom Forms
.custom-select-lgLarge customized select menu
Custom Forms
.custom-select-smSmall customized select menu
Custom Forms
.custom-switchCustomized toggle switch
Custom Forms
.disabledDisables a button (adds opacity and a “no-parking-sign” icon on hover)
Buttons
.disabledDisables a dropdown item (adds a grey text color and a “no-parking-sign” icon on hover)
Dropdowns
.disabledDisables a pagination link (cannot be clicked – adds a grey text color and a “no-parking-sign” icon on hover)
Pagination
.disabledDisables a list item in a list group (cannot be clicked – adds a light grey color and removes the hover effect on list item links)
List Groups
.dropdownCreates a toggleable menu that allows the user to choose one value from a predefined list
Dropdowns
.dropdown-dividerUsed to separate links in the dropdown menu with a thin horizontal border
Dropdowns
.dropdown-headerUsed to add headers inside the dropdown menu
Dropdowns
.dropdown-itemCreates a dropdown item (added to links or buttons inside .dropdown-menu)
Dropdowns
.dropdown-item-textUsed to add plain text to a dropdown item, or used on links for default link styling
Dropdowns
.dropdown-menuAdds the default styles for the dropdown menu container
Dropdowns
.dropdown-menu-rightRight-aligns a dropdown menu
Dropdowns
.dropdown-toggleUsed on the button that should hide and show (toggle) the dropdown menu
Dropdowns
.dropleftLeft-aligns the dropdown
Dropdowns
.droprightRight-aligns the dropdown
Dropdowns
.dropupIndicates a dropup menu (upwards instead of downwards)
Dropdowns
.d-blockCreates a block element (adds display:block)
Utilities
.d-*-blockCreates a block element on a specific screen width
Utilities
.d-inlineMakes an element inline
Utilities
.d-*-inlineMakes an element inline on a specific screen size
Utilities
.d-inline-blockMakes an element inline block
Utilities
.d-*-inline-blockMakes an element inline block on a specific screen size
Utilities
.d-flexCreates a flexbox container and transforms direct children into flex items
Flex
.d-*-flexCreates a flexbox container on a specific screen size
Flex
.d-inline-flexCreates an inline flexbox container
Flex
.d-*-inline-flexCreates an inline flexbox container on a specific screen size
Flex
.d-noneHides an element
Utilities
.d-*-noneHides an element on a specific screen size
Utilities
.d-tableMakes an element display as a table
Utilities
.d-*-tableMakes an element display as a table on a specific screen size
Utilities
.d-table-cellMakes an element display as a table cell
Utilities
.d-*-table-cellMakes an element display as a table cell on a specific screen size
Utilities
.d-table-rowMakes an element display as a table row
Utilities
.d-*-table-rowMakes an element display as a table row on a specific screen size
Utilities
.embed-responsiveContainer for embedded content. Makes videos or slideshows scale properly on any device
Images
.embed-responsive-16by9Container for embedded content. Creates an 16:9 aspect ratio embedded content
Images
.embed-responsive-3by4Container for embedded content. Creates an 3:4 aspect ratio embedded content
Images
.embed-responsive-itemUsed inside .embed-responsive. Scales the video nicely to the parent element
Images
.fadeAdds a fading effect when closing an alert box
Alerts
.fadeAdds a fading effect when showing tab/pill content
Navs
.fadeAdds a fading effect when opening a modal
Modal
.fixed-bottomMakes an element stay at the bottom of the screen (sticky/fixed)
Utilities
.fixed-topMakes an element stay at the top of the screen (sticky/fixed)
Utilities
.flex-columnDisplay flex items vertically
Flex
.flex-*-columnDisplay flex items vertically on different screen sizes:
Flex
.flex-column-reverseDisplay flex items vertically, reversed
Flex
.flex-*-column-reverseDisplay flex items vertically, reversed, on different screen sizes
Flex
.flex-fillUsed on flex items to force it/them into equal width columns
Flex
.flex-*-fillForce flex items into equal widths on different screens
Flex
.flex-grow-0|1Used on a single flex item to take up the rest of the available space
Flex
.flex-nowrapDon’t wrap flex items
Flex
.flex-*-nowrapDon’t wrap items on different screens
Flex
.flex-shrink-0|1Used on a single flex item to shrink it if necessary Flex
.flex-rowDisplay flex items horizontally (side by side)
Flex
.flex-*-rowDisplay flex items horizontally on a specific screen size
Flex
.flex-row-reverseDisplay flex items right-aligned and horizontally
Flex
.flex-*-row-reverseDisplay flex items right-aligned and horizontally on a specific screen size
Flex
.flex-wrapWrap flex items
Flex
.flex-*-wrapWrap items on different screens
Flex
.flex-wrap-reverseWrap flex items, in reversed order
Flex
.flex-*-wrap-reverseWrap flex items, in reversed order on different screens
Flex
.float-leftFloats an element to the left
Utilities
.float-*-leftFloats an element to the left on different screens
Utilities
.float-noneRemove floats from an element
Utilities
.float-rightFloats an element to the right
Utilities
.float-*-rightFloats an element to the left on different screens
Utilities
.font-italicItalic text
Typography
.font-weight-boldBold text
Typography
.font-weight-bolderBolder text (font-weight:bolder)
Typography
.font-weight-lightLight weight text (font-weight:300)
Typography
.font-weight-lighterLighter weight text (font-weight:lighter)
Typography
.font-weight-normalNormal text (font-weight:400)
Typography
.form-checkContainer for checkboxes. Adds proper padding
Forms
.form-check-inlineMakes checkboxes appear on the same line (horizontally)
Forms
.form-check-inputStyles checkboxes with proper margins
Forms
.form-check-labelEnsures proper margins for labels used together with checkboxes
Forms
.form-controlUsed on input, textarea, and select elements to span the entire width of the page and make them responsive
Forms
.form-control-fileAdds display:block and width:100% to input filed with type=”file”
Forms
.form-control-lgLarge form control
Forms
.form-control-plaintextStyles a form control as plain text
Forms
.form-control-rangeAdds display:block and width:100% to input filed with type=”range”
Forms
.form-control-smSmall form control
Forms
.form-groupContainer for form input and label
Forms
.form-inlineMakes a <form> left-aligned with inline-block controls (This only applies to forms within viewports that are at least 768px wide)
Forms
.form-rowContainer for responsive columns (less left and right margins than .row/overrides default column gutters)
Forms
.h1 - .h6Makes an element look like a heading of the chosen class (h1-h6)
Typography
.h-25Sets the height of an element to 25%
Utilities
.h-50Sets the height of an element to 50%
Utilities
.h-75Sets the height of an element to 75%
Utilities
.h-100Sets the height of an element to 100%
Utilities
.img-fluidResponsive image (adds max-width:100% and height:auto)
Images
.img-thumbnailShapes an image to a thumbnail (thin light grey borders)
Images
.initialismDisplays the text inside an <abbr> element in a slightly smaller font size
Typography
.input-groupContainer to enhance an input by adding an icon, text or a button in front or behind the input field as a “help text”
Input Group
.input-group-appendInput group container for adding help text behind an input field
Input Group
.input-group-lgLarge input group
Input Group
.input-group-prependInput group container for adding help text in front of an input field
Input Group
.input-group-smSmall input group
Input Group
.input-group-textStyles the specified help text in an input group
Input Group
.input-lgLarge input field
Input Sizing
.input-smSmall input field
Input Sizing
.invalid-feedbackCreates a custom validation message used in validated forms (red text color)
Forms
.invalid-tooltipCreates a custom validation message used in validated forms (red tooltip)
Forms
.invisibleMake an element invisible
Utilities
.is-invalidValidates a form element (adds a red border to input fields). Note: for server side
Forms
.is-validValidates a form element (adds a green border to input fields). Note: for server side
Forms
.jumbotronCreates a padded grey heading/box with rounded corners that enlarges the font sizes of the text inside it. Used for calling extra attention to some special content or information
Jumbotron
.jumbotron-fluidCreates a full-width jumbotron (grey padded heading) without rounded borders
Jumbotron
.justify-content-*Aligns flex items from the start, at the end, centered, in between and “around
Flex
.justify-content-*-aroundAligns flex items “around” on different screen sizes
Flex
.justify-content-*-betweenAligns flex items in “between” on different screen sizes
Flex
.justify-content-*-centerAligns flex items in the center on different screen sizes
Flex
.justify-content-*-endAligns flex items at the end on different screen sizes
Flex
.justify-content-*-startAligns flex items from the start on different screen sizes
Flex
.leadIncrease the font size and line height of a paragraph
Typography
.list-groupCreates a bordered list group for <li> elements
List Group
.list-group-flushRemoves some borders and rounded corners from list items in a list group
List Group
.list-group-horizontalDisplay list items horizontally instead of vertically (side-by-side instead of on top of each other)
List Group
.list-group-horizontal-*Display list items horizontally instead of vertically on different screen sizes
List Group
.list-group-itemAdded to each <li> element in the list group
List Group
.list-group-item-actionAdded to links inside the list group to make them stand out on hover (darker background)
List Group
.list-group-item-dangerRed background color for a list item in a list group
List Group
.list-group-item-darkDark grey background color for a list item in a list group
List Group
.list-group-item-infoLight-blue background color for a list item in a list group
List Group
.list-group-item-lightLight grey background color for a list item in a list group
List Group
.list-group-item-primaryBlue background color for a list item in a list group
List Group
.list-group-item-successGreen background color for a list item in a list group
List Group
.list-group-item-warningYellow background color for a list item in a list group
List Group
.list-inlinePlaces all list items on a single line (used together with .list-inline-item on each <li> elements)
Typography
.list-inline-itemPlaces all list items on a single line (used together with .list-inline on the parent <ul> element)
Typography
.list-unstyledRemoves all default list-style (bullets, left margin, etc.) styling from a <ul> or <ol> list
Typography
.markHighlights text: Highlighted text
Typography
.mediaAligns media objects together with content (like images or videos – often used for comments in a blog post etc)
Media Objects
.media-bodyContainer for media content
Media Objects
.modalIdentifies the content as a modal and brings focus to it
Modals
.modal-bodyDefines the style for the body of the modal. Add any HTML markup here (p, img, etc)
Modals
.modal-contentStyles the modal (border, background-color, etc). Inside this, add the modal’s header, body and footer, if needed
Modals
.modal-dialog-centeredCenters the modal vertically and horizontally within the page
Modals
.modal-dialog-scrollableAdds a scrollbar inside the modal
Modals
.modal-footerThe footer of the modal (often contains an action button and a close button)
Modals
.modal-headerThe header of the modal (often contains a title and a close button)
Modals
.modal-lgLarge modal (wider than default)
Modals
.modal-smSmall modal (less width)
Modals
.modal-xlExtra large modal
Modals
.m-# / m-*-#Responsive margin classes. * can be sm, md, lg or xl. # can be a number between 0 and 5
Utilities
.mt-# / mt-*-#Responsive top margin classes. * can be sm, md, lg or xl. # can be a number between 0 and 5
Utilities
.mb-# / mb-*-#Responsive bottom margin classes. * can be sm, md, lg or xl. # can be a number between 0 and 5
Utilities
.ml-# / ml-*-#Responsive left margin classes. * can be sm, md, lg or xl. # can be a number between 0 and 5
Utilities
.mr-# / mr-*-#Responsive right margin classes. * can be sm, md, lg or xl. # can be a number between 0 and 5
Utilities
.mx-# / mx-*-#Responsive left and right margin auto (horizontal) classes. * can be sm, md, lg or xl. # can be a number between 0 and 5
Utilities
.my-# / my-*-#Responsive top and bottom margin auto (vertical) classes. * can be sm, md, lg or xl. # can be a number between 0 and 5
Utilities
.mx-autoCenters an element horizontally
Utilities
.nav nav-tabsCreates a tabbed menu
Tabs
.nav nav-pillsCreates a pill menu
Tabs
.nav-justifiedJustifies tab/pill links with an equal width
Tabs
.navbarCreates a navigation bar
Navbar
.navbar-navContainer for navigation links inside the .navbar container
Navbar
.navbar-brandAdded to a link or a header element inside the navbar to represent a logo or a header
Navbar
.navbar-collapseCollapses the navbar (hidden and replaced with a menu/hamburger icon on mobile phones and small tablets)
Navbar
.navbar-expand-*Responsive collapsible class – stacks the navbar vertically on small (sm), medium (md), large (lg) or extra large (xl) screens
Navbar
.navbar-darkAdds a white text color to all links in the navbar
Navbar
.navbar-lightAdds a black text color to all links in the navbar
Navbar
.navbar-textVertically align any elements inside the navbar that are not links (ensures proper padding)
Navbar
.navbar-togglerStyles the button that should open the navbar on small screens. Automatically styled as a hamburger/three bars
Navbar
.nav-linkUsed to style links/anchors inside the navbar
Navbar
.nav-itemUsed to style list items inside the navbar
Navbar
.needs-validationAdds validation styles to a submitted form
Forms
.no-guttersRemove gutters/extra space from columns
Grid System
.page-itemStyles list items inside a pagination
Pagination
.page-linkStyles links inside a pagination
Pagination
.paginationCreates a pagination (Useful when you have a web site with lots of pages
Pagination
.pagination-lgLarge pagination (each pagination link gets a bigger font-size and more padding)
Pagination
.pagination-smSmall pagination (each pagination link gets a smaller font size and less padding)
Pagination
.pre-scrollableMakes a <pre> element scrollable (max-height of 350px and provide a y-axis scrollbar)
Helpers
.progressContainer for progress bars
Progress Bars
.progress-barCreates a progress bar
Progress Bars
.progress-bar-animatedAnimates the progress bar (used together with stripes)
Progress Bars
.progress-bar-stripedAdds stripes to the progress bar
Progress Bars
.p-# / p-*-#Responsive padding classes. * can be sm, md, lg or xl. # can be a number between 0 and 5
Utilities
.pt-# / pt-*-#Responsive top padding classes. * can be sm, md, lg or xl. # can be a number between 0 and 5
Utilities
.pb-# / pb-*-#Responsive bottom padding classes. * can be sm, md, lg or xl. # can be a number between 0 and 5
Utilities
.pl-# / pl-*-#Responsive left padding classes. * can be sm, md, lg or xl. # can be a number between 0 and 5
Utilities
.pr-# / pr-*-#Responsive right padding classes. * can be sm, md, lg or xl. # can be a number between 0 and 5
Utilities
.py-# / py-*-#Responsive top and bottom padding classes. * can be sm, md, lg or xl. # can be a number between 0 and 5
Utilities
.px-# / px-*-#Responsive left and right padding classes. * can be sm, md, lg or xl. # can be a number between 0 and 5
Utilities
.roundedAdds rounded corners to an element
Utilities
.rounded-bottomAdds bottom rounded corners to an element
Utilities
.rounded-circleShapes an element to a circle (not supported in IE8 and earlier)
Utilities
.rounded-leftAdds left rounded corners of an element
Utilities
.rounded-rightAdds right rounded corners to an element
Utilities
.rounded-topAdds top rounded corners to an element
Utilities
.rounded-0Removes rounded corners from an element
Utilities
.rowContainer for responsive columns
Grid System
.row-cols-*Set the number of columns that should appear next to each other
Grid System
.shadowAdds a shadow to an element
Utilities
.shadow-lgAdds a large shadow to an element
Utilities
.shadow-noneRemoves shadows from an element
Utilities
.shadow-smAdds a small shadow to an element
Utilities
.smallCreates a lighter, secondary text in any heading
Typography
.spinner-borderCreates a spinner/loader
Spinners
.spinner-border-smCreates a smaller spinner/loader
Spinners
.spinner-growCreates a spinner/loader that “grows”
Spinners
.spinner-grow-smCreates a smaller spinner/loader that “grows”
Spinners
.sr-onlyHides an element on all devices except for screen readers
Utilities
.sr-only-focusableHides an element on all devices except for screen readers
Utilities
.sticky-topMakes an element stay sticky/fixed at the top of the page when you scroll past it
Utilities
.stretched-linkAdded to a link to make its containing block (parent) clickable (works only for parent elements with position:relative)
Utilities
.tab-contentUsed together with .tab-pane to creates toggleable/dynamic tabs/pills
Tabs
.tab-paneUsed together with .tab-content to creates toggleable/dynamic tabs/pills
Tabs
.tableAdds basic styling to a table (padding, bottom borders, etc)
Tables
.table-activeAdds a grey background color to the table row (<tr> or table cell (<td>) (same color used on hover)
Tables
.table-borderedAdds borders on all sides of the table and cells
Tables
.table-borderlessRemove borders from a table
Tables
.table-condensedMakes a table more compact by cutting cell padding in half
Tables
.table-darkAdds a black background with white text to the table
Tables
.table-hoverCreates a hoverable table (adds a grey background color on table rows on hover)
Tables
.table-responsive-*Makes a table responsive (adds a horizontal scrollbar when needed). By default, the scrollbar is added to the table on screens that are less than 992px wide (if needed). There’s no difference when viewing anything lager than 992px wide. However, you can use sm|md|lg|xl to decide WHEN the table should get a scrollbar, depending on the screen width
Tables
.table-stripedAdds zebra-stripes to a table
Tables
.text-breakPrevents long text from breaking layout
Typography
.text-capitalizeIndicates capitalized text
Typography
.text-centerCenter-aligns text
Typography
.text-*-centerCenter-aligns text on different screens
Typography
.text-dangerRed text color. Indicates danger
Colors
.text-darkDark grey text color
Typography
.text-decoration-noneRemoves the underline from a link
Typography
.text-hideHides text (helps replace an element’s text content with a background image)
Typography
.text-infoLight-blue text color. Indicates information
Colors
.text-lightLight grey text color
Colors
.text-justifyIndicates justified text
Typography
.text-leftAligns the text to the left
Typography
.text-*-leftLeft-aligns text on different screens
Typography
.text-lowercaseChanges text to lowercase
Typography
.text-mutedGrey text color
Colors
.text-nowrapPrevents the text from wrapping
Typography
.text-primaryBlue text color. Indicates something important
Colors
.text-secondaryGrey text color. Indicates something “less” important
Colors
.text-resetResets the color of a text or a link (inherits the color from its parent)
Typography
.text-rightAligns text to the right
Typography
.text-*-rightRight-aligns text on different screens
Typography
.text-successGreen text color. Indicates success
Colors
.text-uppercaseMakes text uppercase
Typography
.text-warningYellow/orange text color. Indicates warning
Colors
.text-whiteWhite text color
Colors
.thead-darkAdds a black background color to table headers
Tables
.thead-lightAdds a grey background color to table headers
Tables
.toastCreates a toast (alert box that disappears after a few seconds)
Toast
.toast-bodyToast body
Toast
.toast-headerToast header
Toast
.valid-feedbackCreates a custom validation message used in validated forms (green text color)
Forms
.valid-tooltipCreates a custom validation message used in validated forms (green tooltip)
Forms
.visibleMake an element visible
Utilities
.was-validatedAdds validation styles to a form element
Forms
.w-25Sets the width of an element to 25%
Utilities
.w-50Sets the width of an element to 50%
Utilities
.w-75Sets the width of an element to 75%
Utilities
.w-100Sets the width of an element to 100%

Utilities

CSS3 Tutorial

An outline is a line that is drawn around elements, OUTSIDE the borders, to make the element “stand out”.

  • a:link – a normal, unvisited link
  • a:visited – a link the user has visited
  • a:hover – a link when the user mouses over it
  • a:active – a link the moment it is clicked
  • /* unvisited link */
    a:link {
      color: red;
    }

    /* visited link */
    a:visited {
      color: green;
    }

    /* mouse over link */
    a:hover {
      color: hotpink;
    }

    /* selected link */
    a:active {
      color: blue;
    }

ul.a {
  list-style-type: circle;
}

ul.b {
  list-style-type: square;
}

ol.c {
  list-style-type: upper-roman;
}

ol.d {
  list-style-type: lower-alpha;
}

ul {
  list-style-image: url(‘sqpurple.gif’);
}

th {
  text-align: left;
}

td {
  height: 50px;
  vertical-align: bottom;
}

display: none

h1.hidden {
  visibility: hidden;
}

The position property specifies the type of positioning method used for an element.

There are five different position values:

  • static
  • relative
  • fixed
  • absolute
  • sticky

HTML elements are positioned static by default.

Static positioned elements are not affected by the top, bottom, left, and right properties.

An element with position: static; is not positioned in any special way; it is always positioned according to the normal flow of the page:

position: relative;

An element with position: relative; is positioned relative to its normal position.

Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element.

position: fixed;

An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element.

A fixed element does not leave a gap in the page where it would normally have been located.

position: absolute;

An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).

However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

Note: A “positioned” element is one whose position is anything except static.

position: sticky;

An element with position: sticky; is positioned based on the user’s scroll position.

A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport – then it “sticks” in place (like position:fixed).

CSS Overflow

The overflow property specifies whether to clip the content or to add scrollbars when the content of an element is too big to fit in the specified area.

The overflow property has the following values:

  • visible – Default. The overflow is not clipped. The content renders outside the element’s box
  • hidden – The overflow is clipped, and the rest of the content will be invisible
  • scroll – The overflow is clipped, and a scrollbar is added to see the rest of the content
  • auto – Similar to scroll, but it adds scrollbars only when necessary

Note: The overflow property only works for block elements with a specified height.

div {
  overflow-x: hidden; /* Hide horizontal scrollbar */
  overflow-y: scroll; /* Add vertical scrollbar */
}

The CSS float property specifies how an element should float.

The CSS clear property specifies what elements can float beside the cleared element and on which side.

The float property is used for positioning and formatting content e.g. let an image float left to the text in a container.

The float property can have one of the following values:

  • left – The element floats to the left of its container
  • right – The element floats to the right of its container
  • none – The element does not float (will be displayed just where it occurs in the text). This is default
  • inherit – The element inherits the float value of its parent

In its simplest use, the float property can be used to wrap text around images.

The display: inline-block Value

Compared to display: inline, the major difference is that display: inline-block allows to set a width and height on the element.

Also, with display: inline-block, the top and bottom margins/paddings are respected, but with display: inline they are not.

Compared to display: block, the major difference is that display: inline-block does not add a line-break after the element, so the element can sit next to other elements.

CSS Combinators

A combinator is something that explains the relationship between the selectors.

A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator.

There are four different combinators in CSS:

Descendant Selector

The descendant selector matches all elements that are descendants of a specified element.

The following example selects all <p> elements inside <div> elements: 

Example

div p {
  background-color: yellow;
}

  • descendant selector (space)
  • child selector (>)
  • adjacent sibling selector (+)
  • general sibling selector (~)

Child Selector

The child selector selects all elements that are the children of a specified element.

The following example selects all <p> elements that are children of a <div> element:

Example

div > p {
  background-color: yellow;
}

Adjacent Sibling Selector

The adjacent sibling selector selects all elements that are the adjacent siblings of a specified element.

Sibling elements must have the same parent element, and “adjacent” means “immediately following”.

The following example selects all <p> elements that are placed immediately after <div> elements:

Example

div + p {
  background-color: yellow;
}

General Sibling Selector

The general sibling selector selects all elements that are siblings of a specified element.

The following example selects all <p> elements that are siblings of <div> elements: 

Example

div ~ p {
  background-color: yellow;
}

What are Pseudo-classes?

A pseudo-class is used to define a special state of an element.

For example, it can be used to:

  • Style an element when a user mouses over it
  • Style visited and unvisited links differently
  • Style an element when it gets focus

The syntax of pseudo-classes:

selector:pseudo-class {
  property:value;
}

Pseudo-classes and CSS Classes

Pseudo-classes can be combined with CSS classes:

When you hover over the link in the example, it will change color:

Example

a.highlight:hover {
  color: #ff0000;
}

Hover on <div>

An example of using the :hover pseudo-class on a <div> element:

Example

div:hover {
  background-color: blue;
}

Simple Tooltip Hover

Hover over a <div> element to show a <p> element (like a tooltip):

Hover over me to show the <p> element.

Example

p {
  display: none;
  background-color: yellow;
  padding: 20px;
}

div:hover p {
  display: block;
}

CSS – The :first-child Pseudo-class

The :first-child pseudo-class matches a specified element that is the first child of another element.

Match the first <p> element

In the following example, the selector matches any <p> element that is the first child of any element:

Example

p:first-child {
  color: blue;
}

Match the first <i> element in all <p> elements

In the following example, the selector matches the first <i> element in all <p> elements:

Example

p i:first-child {
  color: blue;
}

Match all <i> elements in all first child <p> elements

In the following example, the selector matches all <i> elements in <p> elements that are the first child of another element:

Example

p:first-child i {
  color: blue;
}

What are Pseudo-Elements?

A CSS pseudo-element is used to style specified parts of an element.

For example, it can be used to:

  • Style the first letter, or line, of an element
  • Insert content before, or after, the content of an element

The ::first-line Pseudo-element

The ::first-line pseudo-element is used to add a special style to the first line of a text.

The following example formats the first line of the text in all <p> elements:

Example 

p::first-line {
  color: #ff0000;
  font-variant: small-caps;
}

Note: The ::first-line pseudo-element can only be applied to block-level elements.

The following properties apply to the ::first-line pseudo-element:

  • font properties
  • color properties
  • background properties
  • word-spacing
  • letter-spacing
  • text-decoration
  • vertical-align
  • text-transform
  • line-height
  • clear

Notice the double colon notation – ::first-line versus :first-line

The double colon replaced the single-colon notation for pseudo-elements in CSS3. This was an attempt from W3C to distinguish between pseudo-classes and pseudo-elements.

The single-colon syntax was used for both pseudo-classes and pseudo-elements in CSS2 and CSS1.

For backward compatibility, the single-colon syntax is acceptable for CSS2 and CSS1 pseudo-elements.

The ::first-letter Pseudo-element

The ::first-letter pseudo-element is used to add a special style to the first letter of a text.

The following example formats the first letter of the text in all <p> elements: 

Example

p::first-letter {
  color: #ff0000;
  font-size: xx-large;
}

Note: The ::first-letter pseudo-element can only be applied to block-level elements.

The following properties apply to the ::first-letter pseudo- element: 

  • font properties
  • color properties 
  • background properties
  • margin properties
  • padding properties
  • border properties
  • text-decoration
  • vertical-align (only if “float” is “none”)
  • text-transform
  • line-height
  • float
  • clear

Pseudo-elements and CSS Classes

Pseudo-elements can be combined with CSS classes: 

Example

p.intro::first-letter {
  color: #ff0000;
  font-size:200%;
}

The example above will display the first letter of paragraphs with class=”intro”, in red and in a larger size.

Multiple Pseudo-elements

Several pseudo-elements can also be combined.

In the following example, the first letter of a paragraph will be red, in an xx-large font size. The rest of the first line will be blue, and in small-caps. The rest of the paragraph will be the default font size and color:

Example

p::first-letter {
  color: #ff0000;
  font-size: xx-large;
}

p::first-line {
  color: #0000ff;
  font-variant: small-caps;
}

CSS – The ::before Pseudo-element

The ::before pseudo-element can be used to insert some content before the content of an element.

The following example inserts an image before the content of each <h1> element:

Example

h1::before {
  content: url(smiley.gif);
}

CSS – The ::after Pseudo-element

The ::after pseudo-element can be used to insert some content after the content of an element.

The following example inserts an image after the content of each <h1> element:

Example

h1::after {
  content: url(smiley.gif);
}

CSS – The ::selection Pseudo-element

The ::selection pseudo-element matches the portion of an element that is selected by a user.

The following CSS properties can be applied to ::selection: color, background, cursor, and outline.

The following example makes the selected text red on a yellow background:

Example

::selection {
  color: red;
  background: yellow;
}

All CSS Pseudo Elements

SelectorExampleExample description
::afterp::afterInsert something after the content of each <p> element
::beforep::beforeInsert something before the content of each <p> element
::first-letterp::first-letterSelects the first letter of each <p> element
::first-linep::first-lineSelects the first line of each <p> element
::selectionp::selectionSelects the portion of an element that is selected by a user

All CSS Pseudo Classes

SelectorExampleExample description
:activea:activeSelects the active link
:checkedinput:checkedSelects every checked <input> element
:disabledinput:disabledSelects every disabled <input> element
:emptyp:emptySelects every <p> element that has no children
:enabledinput:enabledSelects every enabled <input> element
:first-childp:first-childSelects every <p> elements that is the first child of its parent
:first-of-typep:first-of-typeSelects every <p> element that is the first <p> element of its parent
:focusinput:focusSelects the <input> element that has focus
:hovera:hoverSelects links on mouse over
:in-rangeinput:in-rangeSelects <input> elements with a value within a specified range
:invalidinput:invalidSelects all <input> elements with an invalid value
:lang(language)p:lang(it)Selects every <p> element with a lang attribute value starting with “it”
:last-childp:last-childSelects every <p> elements that is the last child of its parent
:last-of-typep:last-of-typeSelects every <p> element that is the last <p> element of its parent
:linka:linkSelects all unvisited links
:not(selector):not(p)Selects every element that is not a <p> element
:nth-child(n)p:nth-child(2)Selects every <p> element that is the second child of its parent
:nth-last-child(n)p:nth-last-child(2)Selects every <p> element that is the second child of its parent, counting from the last child
:nth-last-of-type(n)p:nth-last-of-type(2)Selects every <p> element that is the second <p> element of its parent, counting from the last child
:nth-of-type(n)p:nth-of-type(2)Selects every <p> element that is the second <p> element of its parent
:only-of-typep:only-of-typeSelects every <p> element that is the only <p> element of its parent
:only-childp:only-childSelects every <p> element that is the only child of its parent
:optionalinput:optionalSelects <input> elements with no “required” attribute
:out-of-rangeinput:out-of-rangeSelects <input> elements with a value outside a specified range
:read-onlyinput:read-onlySelects <input> elements with a “readonly” attribute specified
:read-writeinput:read-writeSelects <input> elements with no “readonly” attribute
:requiredinput:requiredSelects <input> elements with a “required” attribute specified
:rootrootSelects the document’s root element
:target#news:targetSelects the current active #news element (clicked on a URL containing that anchor name)
:validinput:validSelects all <input> elements with a valid value
:visiteda:visitedSelects all visited links

Horizontal Navigation Bar Examples

Create a basic horizontal navigation bar with a dark background color and change the background color of the links when the user moves the mouse over them:

Example

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

/* Change the link color to #111 (black) on hover */
li a:hover {
  background-color: #111;
}

Active/Current Navigation Link

Add an “active” class to the current link to let the user know which page he/she is on:

Example

.active {
  background-color: #4CAF50;
}

This example is similar to the previous one, except that we add links inside the dropdown box and style them to fit a styled dropdown button:

Example

<style>
/* Style The Dropdown Button */
.dropbtn {
  background-color: #4CAF50;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}

/* The container <div> – needed to position the dropdown content */
.dropdown {
  position: relative;
  display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

/* Links inside the dropdown */
.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #f1f1f1}

/* Show the dropdown menu on hover */
.dropdown:hover .dropdown-content {
  display: block;
}

/* Change the background color of the dropdown button when the dropdown content is shown */
.dropdown:hover .dropbtn {
  background-color: #3e8e41;
}
</style>

<div class=”dropdown”>
  <button class=”dropbtn”>Dropdown</button>
  <div class=”dropdown-content”>
    <a href=”#”>Link 1</a>
    <a href=”#”>Link 2</a>
    <a href=”#”>Link 3</a>
  </div>
</div>

Image Gallery

The following image gallery is created with CSS:

Example

<html>
<head>
<style>
div.gallery {
  margin: 5px;
  border: 1px solid #ccc;
  float: left;
  width: 180px;
}

div.gallery:hover {
  border: 1px solid #777;
}

div.gallery img {
  width: 100%;
  height: auto;
}

div.desc {
  padding: 15px;
  text-align: center;
}
</style>
</head>
<body>

<div class=”gallery”>
  <a target=”_blank” href=”img_5terre.jpg”>
    <img src=”img_5terre.jpg” alt=”Cinque Terre” width=”600″ height=”400″>
  </a>
  <div class=”desc”>Add a description of the image here</div>
</div>

<div class=”gallery”>
  <a target=”_blank” href=”img_forest.jpg”>
    <img src=”img_forest.jpg” alt=”Forest” width=”600″ height=”400″>
  </a>
  <div class=”desc”>Add a description of the image here</div>
</div>

<div class=”gallery”>
  <a target=”_blank” href=”img_lights.jpg”>
    <img src=”img_lights.jpg” alt=”Northern Lights” width=”600″ height=”400″>
  </a>
  <div class=”desc”>Add a description of the image here</div>
</div>

<div class=”gallery”>
  <a target=”_blank” href=”img_mountains.jpg”>
    <img src=”img_mountains.jpg” alt=”Mountains” width=”600″ height=”400″>
  </a>
  <div class=”desc”>Add a description of the image here</div>
</div>

</body>
</html>

All CSS Attribute Selectors

SelectorExampleExample description
[attribute][target]Selects all elements with a target attribute
[attribute=value][target=_blank]Selects all elements with target=”_blank”
[attribute~=value][title~=flower]Selects all elements with a title attribute containing the word “flower”
[attribute|=value][lang|=en]Selects all elements with a lang attribute value starting with “en”
[attribute^=value]a[href^=”https”]Selects every <a> element whose href attribute value begins with “https”
[attribute$=value]a[href$=”.pdf”]Selects every <a> element whose href attribute value ends with “.pdf”
[attribute*=value]a[href*=”w3schools”]Selects every <a> element whose href attribute value contains the substring “w3schools”

CSS border-radius Property

The CSS border-radius property defines the radius of an element’s corners.

Example

#rcorners1 {
  border-radius: 25px;
  background: #73AD21;
  padding: 20px;
  width: 200px;
  height: 150px;
}

#rcorners2 {
  border-radius: 25px;
  border: 2px solid #73AD21;
  padding: 20px;
  width: 200px;
  height: 150px;
}

#rcorners3 {
  border-radius: 25px;
  background: url(paper.gif);
  background-position: left top;
  background-repeat: repeat;
  padding: 20px;
  width: 200px;
  height: 150px;
}

CSS border-image Property

#borderimg {
  border: 10px solid transparent;
  padding: 15px;
  border-image: url(border.png) 30 round;
}

CSS Multiple Backgrounds

#example1 {
  background-image: url(img_flwr.gif), url(paper.gif);
  background-position: right bottom, left top;
  background-repeat: no-repeat, repeat;
}

CSS Linear Gradients

To create a linear gradient you must define at least two color stops. Color stops are the colors you want to render smooth transitions among. You can also set a starting point and a direction (or an angle) along with the gradient effect.

background-image: linear-gradient(direction, color-stop1, color-stop2, …);

Linear Gradient – Top to Bottom (this is default)

The following example shows a linear gradient that starts at the top. It starts red, transitioning to yellow:

Example

#grad {
  background-image: linear-gradient(red, yellow);
}

CSS Shadow Effects

With CSS you can add shadow to text and to elements.

In this chapter you will learn about the following properties:

  • text-shadow
  • box-shadow

h1 {
  text-shadow: 2px 2px;
}

Multiple Shadows

To add more than one shadow to the text, you can add a comma-separated list of shadows.

The following example shows a red and blue neon glow shadow:

h1 {
  text-shadow: 0 0 3px #FF0000, 0 0 5px #0000FF;
}

CSS box-shadow Property

The CSS box-shadow property applies shadow to elements.

In its simplest use, you only specify the horizontal shadow and the vertical shadow:

div {
  box-shadow: 10px 10px;
}

div {
  box-shadow: 10px 10px grey;
}

CSS Transitions

Specify the Speed Curve of the Transition

The transition-timing-function property specifies the speed curve of the transition effect.

The transition-timing-function property can have the following values:

  • ease – specifies a transition effect with a slow start, then fast, then end slowly (this is default)
  • linear – specifies a transition effect with the same speed from start to end
  • ease-in – specifies a transition effect with a slow start
  • ease-out – specifies a transition effect with a slow end
  • ease-in-out – specifies a transition effect with a slow start and end
  • cubic-bezier(n,n,n,n) – lets you define your own values in a cubic-bezier function

The following example shows the some of the different speed curves that can be used:

Example

#div1 {transition-timing-function: linear;}
#div2 {transition-timing-function: ease;}
#div3 {transition-timing-function: ease-in;}
#div4 {transition-timing-function: ease-out;}
#div5 {transition-timing-function: ease-in-out;}

What are CSS Animations?

An animation lets an element gradually change from one style to another.

You can change as many CSS properties you want, as many times you want.

To use CSS animation, you must first specify some keyframes for the animation.

Keyframes hold what styles the element will have at certain times.


The @keyframes Rule

When you specify CSS styles inside the @keyframes rule, the animation will gradually change from the current style to the new style at certain times.

To get an animation to work, you must bind the animation to an element.

The following example binds the “example” animation to the <div> element. The animation will last for 4 seconds, and it will gradually change the background-color of the <div> element from “red” to “yellow”:

Example

/* The animation code */
@keyframes example {
  from {background-color: red;}
  to {background-color: yellow;}
}

/* The element to apply the animation to */
div {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
}

Tooltip

A tooltip is often used to specify extra information about something when the user moves the mouse pointer over an element:

Example

<style>
/* Tooltip container */
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black; /* If you want dots under the hoverable text */
}

/* Tooltip text */
.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: black;
  color: #fff;
  text-align: center;
  padding: 5px 0;
  border-radius: 6px;
 
  /* Position the tooltip text – see examples below! */
  position: absolute;
  z-index: 1;
}

/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
  visibility: visible;
}
</style>

<div class=”tooltip”>Hover over me
  <span class=”tooltiptext”>Tooltip text</span>
</div>

Example Explained

HTML: Use a container element (like <div>) and add the "tooltip" class to it. When the user mouse over this <div>, it will show the tooltip text.

The tooltip text is placed inside an inline element (like <span>) with class="tooltiptext".

CSS: The tooltip class use position:relative, which is needed to position the tooltip text (position:absolute). Note: See examples below on how to position the tooltip.

The tooltiptext class holds the actual tooltip text. It is hidden by default, and will be visible on hover (see below). We have also added some basic styles to it: 120px width, black background color, white text color, centered text, and 5px top and bottom padding.

The CSS border-radius property is used to add rounded corners to the tooltip text.

The :hover selector is used to show the tooltip text when the user moves the mouse over the <div> with class="tooltip".

CSS Multi-column Layout

The CSS multi-column layout allows easy definition of multiple columns of text – just like in newspapers

CSS Multi-columns Properties

The following table lists all the multi-columns properties: 

PropertyDescription
column-countSpecifies the number of columns an element should be divided into
column-fillSpecifies how to fill columns
column-gapSpecifies the gap between the columns
column-ruleA shorthand property for setting all the column-rule-* properties
column-rule-colorSpecifies the color of the rule between columns
column-rule-styleSpecifies the style of the rule between columns
column-rule-widthSpecifies the width of the rule between columns
column-spanSpecifies how many columns an element should span across
column-widthSpecifies a suggested, optimal width for the columns
columnsA shorthand property for setting column-width and column-count

CSS Box Sizing

The CSS box-sizing property allows us to include the padding and border in an element’s total width and height.


Without the CSS box-sizing Property

By default, the width and height of an element is calculated like this:

width + padding + border = actual width of an element
height + padding + border = actual height of an element

This means: When you set the width/height of an element, the element often appears bigger than you have set (because the element’s border and padding are added to the element’s specified width/height).

CSS Flexbox Layout Module

Before the Flexbox Layout module, there were four layout modes:

  • Block, for sections in a webpage
  • Inline, for text
  • Table, for two-dimensional table data
  • Positioned, for explicit position of an element

The Flexible Box Layout Module, makes it easier to design flexible responsive layout structure without using float or positioning.

The following table lists the CSS properties used with flexbox:

PropertyDescription
displaySpecifies the type of box used for an HTML element
flex-directionSpecifies the direction of the flexible items inside a flex container
justify-contentHorizontally aligns the flex items when the items do not use all available space on the main-axis
align-itemsVertically aligns the flex items when the items do not use all available space on the cross-axis
flex-wrapSpecifies whether the flex items should wrap or not, if there is not enough room for them on one flex line
align-contentModifies the behavior of the flex-wrap property. It is similar to align-items, but instead of aligning flex items, it aligns flex lines
flex-flowA shorthand property for flex-direction and flex-wrap
orderSpecifies the order of a flexible item relative to the rest of the flex items inside the same container
align-selfUsed on flex items. Overrides the container’s align-items property
flexA shorthand property for the flex-grow, flex-shrink, and the flex-basis properties

CSS2 Introduced Media Types

The @media rule, introduced in CSS2, made it possible to define different style rules for different media types.

Examples: You could have one set of style rules for computer screens, one for printers, one for handheld devices, one for television-type devices, and so on.

Unfortunately these media types never got a lot of support by devices, other than the print media type.


CSS Media Queries

CSS3 Introduced Media Queries

Media queries in CSS3 extended the CSS2 media types idea: Instead of looking for a type of device, they look at the capability of the device.

Media queries can be used to check many things, such as:

  • width and height of the viewport
  • width and height of the device
  • orientation (is the tablet/phone in landscape or portrait mode?)
  • resolution

Using media queries are a popular technique for delivering a tailored style sheet to desktops, laptops, tablets, and mobile phones (such as iPhone and Android phones).

CSS3 Media Types

ValueDescription
allUsed for all media type devices
printUsed for printers
screenUsed for computer screens, tablets, smart-phones etc.
speechUsed for screenreaders that “reads” the page out loud

Media Queries Simple Examples

One way to use media queries is to have an alternate CSS section right inside your style sheet.

The following example changes the background-color to lightgreen if the viewport is 480 pixels wide or wider (if the viewport is less than 480 pixels, the background-color will be pink):

Example

@media screen and (min-width: 480px) {
  body {
    background-color: lightgreen;
  }
}

What is Responsive Web Design?

Responsive web design makes your web page look good on all devices.

Responsive web design uses only HTML and CSS.

Responsive web design is not a program or a JavaScript.

What is The Viewport?

The viewport is the user’s visible area of a web page.

The viewport varies with the device, and will be smaller on a mobile phone than on a computer screen.

Before tablets and mobile phones, web pages were designed only for computer screens, and it was common for web pages to have a static design and a fixed size.

Then, when we started surfing the internet using tablets and mobile phones, fixed size web pages were too large to fit the viewport. To fix this, browsers on those devices scaled down the entire web page to fit the screen.

This was not perfect!! But a quick fix.


Setting The Viewport

HTML5 introduced a method to let web designers take control over the viewport, through the <meta> tag.

You should include the following <meta> viewport element in all your web pages:

<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

A <meta> viewport element gives the browser instructions on how to control the page’s dimensions and scaling.

The width=device-width part sets the width of the page to follow the screen-width of the device (which will vary depending on the device).

The initial-scale=1.0 part sets the initial zoom level when the page is first loaded by the browser.

Here is an example of a web page without the viewport meta tag, and the same web page with the viewport meta tag:

Tip: If you are browsing this page with a phone or a tablet, you can click on the two links below to see the difference.

Size Content to The Viewport

Users are used to scroll websites vertically on both desktop and mobile devices – but not horizontally!

So, if the user is forced to scroll horizontally, or zoom out, to see the whole web page it results in a poor user experience.

Some additional rules to follow:

1. Do NOT use large fixed width elements – For example, if an image is displayed at a width wider than the viewport it can cause the viewport to scroll horizontally. Remember to adjust this content to fit within the width of the viewport.

2. Do NOT let the content rely on a particular viewport width to render well – Since screen dimensions and width in CSS pixels vary widely between devices, content should not rely on a particular viewport width to render well.

3. Use CSS media queries to apply different styling for small and large screens – Setting large absolute CSS widths for page elements will cause the element to be too wide for the viewport on a smaller device. Instead, consider using relative width values, such as width: 100%. Also, be careful of using large absolute positioning values. It may cause the element to fall outside the viewport on small devices.

Always Design for Mobile First

Mobile First means designing for mobile before designing for desktop or any other device (This will make the page display faster on smaller devices).

This means that we must make some changes in our CSS.

Instead of changing styles when the width gets smaller than 768px, we should change the design when the width gets larger than 768px. This will make our design Mobile First:

Example

/* For mobile phones: */
[class*=”col-“] {
  width: 100%;
}

@media only screen and (min-width: 768px) {
  /* For desktop: */
  .col-1 {width: 8.33%;}
  .col-2 {width: 16.66%;}
  .col-3 {width: 25%;}
  .col-4 {width: 33.33%;}
  .col-5 {width: 41.66%;}
  .col-6 {width: 50%;}
  .col-7 {width: 58.33%;}
  .col-8 {width: 66.66%;}
  .col-9 {width: 75%;}
  .col-10 {width: 83.33%;}
  .col-11 {width: 91.66%;}
  .col-12 {width: 100%;}
}

HTML Tutorial

An HTML element usually consists of a start tag and an end tag, with the content inserted in between

Attributes provide additional information about HTML elements.

Headings are defined with the <h1> to <h6> tags. <h1> defines the most important heading. <h6> defines the least important heading.

CSS stands for Cascading Style Sheets. CSS describes how HTML elements are to be displayed on screen, paper, or in other media.

  • Inline – by using the style attribute in HTML elements
  • Internal – by using a <style> element in the <head> section
  • External – by using an external CSS file

Links are found in nearly all web pages. Links allow users to click their way from page to page.

An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.

discSets the list item marker to a bullet (default)
circleSets the list item marker to a circle
squareSets the list item marker to a square
noneThe list items will not be marked

A block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).

An inline element does not start on a new line and only takes up as much width as necessary.

The HTML class attribute is used to define equal styles for elements with the same class name. So, all HTML elements with the same class attribute will get the same style.

The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document). The id value can be used by CSS and JavaScript to perform certain tasks for the element with the specific id value. In CSS, to select an element with a specific id, write a hash (#) character, followed by the id of the element.

The <head> element is a container for metadata (data about data) and is placed between the <html> tag and the <body> tag.

HTML metadata is data about the HTML document. Metadata is not displayed.

Metadata typically define the document title, character set, styles, scripts, and other meta information.

The following tags describe metadata: <title>, <style>, <meta>, <link>, <script>, and <base>.

  • <header> – Defines a header for a document or a section
  • <nav> – Defines a container for navigation links
  • <section> – Defines a section in a document
  • <article> – Defines an independent self-contained article
  • <aside> – Defines content aside from the content (like a sidebar)
  • <footer> – Defines a footer for a document or a section
  • <details> – Defines additional details
  • <summary> – Defines a heading for the <details> element

When making responsive web pages, add the following <meta> element in all your web pages <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

The HTML <form> element defines a form that is used to collect user input

An HTML form contains form elements.

Form elements are different types of input elements, like: text fields, checkboxes, radio buttons, submit buttons, and more.

SVG stands for Scalable Vector Graphics. SVG is used to define graphics for the Web. SVG is a W3C recommendation

Multimedia comes in many different formats. It can be almost anything you can hear or see. Web pages often contain multimedia elements of different types and formats.

Before HTML5, a video could only be played in a browser with a plug-in (like flash).

The HTML5 <video> element specifies a standard way to embed a video in a web page.

<video width=”320″ height=”240″ controls>
  <source src=”movie.mp4″ type=”video/mp4″>
  <source src=”movie.ogg” type=”video/ogg”>
Your browser does not support the video tag.
</video>

Before HTML5, audio files could only be played in a browser with a plug-in (like flash).

The HTML5 <audio> element specifies a standard way to embed audio in a web page.

<audio controls>
  <source src=”horse.ogg” type=”audio/ogg”>
  <source src=”horse.mp3″ type=”audio/mpeg”>
Your browser does not support the audio element.
</audio>