Dynamic Website for Rs. 7777

Dynamic Website Design for Rs.7777* only

 

Free Domain name Registrationwebdesign2

Free Web Hosting

Free Unlimited Space

 Free Unlimited Photo Upload

Free Unlimited Video Upload

* One dynamic Page and lots of static pages

 

For details please contact

Tankadhar Training and Research Center,

Odisha – 765001. Ph.06856 224064. Mobile. 9439156664

My 4 secrets for creating a regular blog

Posted by on January 16th, 2013

My 4 secrets for creating a regular blog
Blogging seems to be one of those things that many people start, yet few manage to keep going. I think a lot of people have the desire to write about what they are passionate about and publish it online, but turning that passion into a regular form of content can be extremely difficult.

When I first started this website, I would go through phases of writing, and then long periods of neglect. I just couldn’t find it in myself to produce content on a regular basis, even though I had the desire to do so.

I think there is so much value in regularly writing your thoughts on a subject and publishing it online for anyone to read. Writing really cements your understanding of a topic when you are forced to explain it in your own words. I also think the ability to write clearly is a huge asset, no matter what industry you work in or what your job entails. Writing is all about clarity of thought and being able to communicate effectively. If you write regularly over a sustained period of time, you will eventually become a really good writer.

Also, don’t think you can’t do it just because you are not a “writer”. I am by no means a natural writer, and I actually struggled through English lessons throughout my education. Until just a couple of years ago, I hated writing, but I think it’s not until you are actually writing about something you care about that your passion starts to show.

So if you are looking to start a blog, or you have given up in the past and want to try again, here are my 4 secrets for writing regular content. These 4 things actually worked for me, so I hope they will work for you too. Take a look at the dates of my first 20 or so posts to see how I struggled to post regularly at the beginning!

1. Set a schedule

The first really important thing to do is to set yourself a schedule. Unless you have a set schedule to meet, you will never be able to post regularly.

A lot of people want to blog only when an idea strikes them. If that is the kind of blog you want to write it is unlikely that it will ever become “regular”. Writing whenever the mood strikes, or when you think of an idea that is worthy to be written about won’t happen very regularly. There’s nothing wrong with this kind of blog, but it will always be sporadic and it will never grow a following.

A schedule forces you to be more creative and think of topics to write about. When you know you have a schedule to meet, you start to get into the habit or producing more ideas on a regular basis.

I wanted Culttt to be a very active website and so I decided I would post 3 times a week. You might not want to make this kind of commitment to writing, but you need to make a commitment based upon the investment you want to make.

You also need to hold yourself accountable to meet the schedule. A schedule is pointless if you miss it. Start with a target that you can easily hit. Once you start getting traffic and your website starts to grow, it becomes much harder to miss your schedule.

2. Block out time to write

Once you have your schedule in place, you need to set a routine in order to produce the content. Setting a routine is important because if you don’t, you won’t hit your schedule.

Setting a routine to write is exactly the same as learning or improving anything. For example, if you were having piano lessons once a week, you would need to set yourself a routine to practice, or when the lessons comes round each week you would show no improvement. Think of your schedule dates as your piano lesson.

Blocking out time to write is important because it forces you to sit down and do the work. If you don’t set yourself a routine, you won’t end up writing.

3. Write no matter what

Like an type of art, writing can often be difficult. Either it is a struggle to convey an idea, or you live in fear that what you write is not good enough. This is made even worse when you have a schedule to meet, and you’ve blocked out time in order to write. It’s easy to find yourself sitting for a long time, staring at a blank document.

I’ve found the best way to solve this problem is just to write no matter what. My first draft of a post is often terrible as I quickly get everything I want to say out of my head and into a working document. The majority of the time I’m just writing out a list of bullet points of areas I want to cover, or I write down all the section headers without ever writing out a proper sentence. If you do this, you can very quickly get the structure of a post, without the struggle of writing the first paragraph.

Whenever I write a post, I write out the headings and then just write as much as I can under each section. Once I think I’ve written all my ideas down, I save the document and call it a night.

I don’t usually look at the post again until I want to put it into WordPress. When you come back to a post that you’ve written, it is much easier to edit it down to exactly what you want to say. Coming back with a fresh set of eyes enables you to critically evaluate what you have written so you can re-write or re-organise it so it reads more clearly.

Part of writing regularly is also about getting over the fear of your writing not being good enough. When you are shooting for a gruelling schedule, you don’t have time to painstakingly edit every word.

Real artists ships.

4. Always be formulating

The final problem with writing regular content is formulating enough ideas for content. It’s difficult to sit down and start writing in your allotted writing block if you have nothing to write about. It is much easier if you already have a list of ideas for potential posts as you can just start writing straight away.

In order to write regularly, you really have to surround yourself within your niche. Hopefully you have picked a topic that you are passionate about, and so you already have a lot to say.

I find one of the best ways to start formulating more ideas is to read a lot of content. I have over 150 RSS feed subscriptions in my Google Reader account that I clear down every day. Whenever I see something interesting I just star it so I can come back to it later. I also follow a lot of people on Twitter who regularly post links to interesting content. Again I just favourite it so I can come back to it and read it when I have time.

I read all different types of content from a wide range of different websites. From big media companies, to individual bloggers. I find having a wide range of different types of content enabled me to discover the type of content I want to write.

When you start reading a lot of content from a particular niche, you begin to synthesis the various ideas that you read and mix them with your own. This enables you to subconsciously spot patterns or come up with ideas for original content. You will probably also see posts in a particular format which would work well for a different idea that you have.

It’s difficult to come up with a regular stream of ideas, but you can make it a lot easier if you provide yourself with the right type of inspiration.

And finally, have some way of writing down notes or ideas for blog posts. I use Evernote all the time to store lists of post ideas and random thoughts that could potentially grow into a post. Sometimes someone will mention something to you that triggers an idea for a post. Personally, if I don’t write it down immediately, I will never think of it again. Keeping a centralised list of post ideas in Evernote makes it a lot easier to start writing as soon as I sit down in my allotted time.

Conclusion

I’m not going to lie to you, writing a regular blog is a lot of hard work, but the huge amount of opportunity it grants you in the long run is worth the effort. It enables you to make something really great over a long sustained period of time bit by bit.

Hopefully these four things will encourage or help you to start regularly blogging too. I really struggled to write regularly for a long time, but by finding what works for you, you too can start building something you really care about.

STEPS TO MAKE ONLINE PASSPORT

नई दि‍ल्‍ली। सरकार जल्‍द ही पासपोर्ट और बनाने की प्रक्रि‍या में आधार कार्ड को आवश्‍यक बनाए जाने की योजना बना रही है। सरकार इस प्रक्रिया से आवेदक की आपराधिक गति‍वि‍धि‍यों के सत्यापन की प्रणाली स्थापित करने की कोशिश भी की जा रही है। नई प्रक्रिया के तहत यदि कोई पासपोर्ट के लिए आवेदन करता है और आधार नहीं होने पर पहले उसे आधार कार्ड बनवाना पड़ सकता है।
यह कदम पीएम नरेंद्र मोदी के उन दिशा-निर्देशों के तहत उठाया जा रहा है, जिसमें उन्होंने देशवासियों को पारदर्शी और साधारण तरीकों से पासपोर्ट सेवा देने की बात की थी। मालूम हो कि सरकार के पास पासपोर्ट के लिए पुलिस सत्यापन के संबंध में लगातार शिकायतें आती हैं और इसके चलते पासपोर्ट जारी करने में देरी होती है।
आइए जानते हैं कैसे करते हैं पासपोर्ट के लिए ऑनलाइन आवेदन-
स्टेप-1- पासपोर्ट सेवा पोर्टल पर खुद को रजिस्टर करें
सबसे पहले पासपोर्ट सेवा पोर्टल की वेबसाइट http://passportindia.gov.in/AppOnlineProject/welcomeLink पर जाकर खुद को रजिस्टर करें। इसके register now लिंक पर क्लिक करें।
स्टेप-2- लॉगिन करें
खुद को रजिस्टर करने के बाद आपको एक लॉगिन आई मिल जाएगी, जिसकी मदद से आप खुद को पासपोर्स सेवा पोर्टल की वेबसाइट http://passportindia.gov.in/AppOnlineProject/welcomeLink पर लॉगिन कर सकते हैं।
आगे की स्लाइड्स में जानें अन्य स्टेप्स-
नोट- तस्वीरों का प्रयोग सिर्फ प्रस्तुतिकरण के लिए किया गया है। सारी जानकारी पासपोर्ट सेवा ऑनलाइन पोर्टल की वेबसाइट से ली गई है।
स्टेप-3- विकल्प चुनें
इसमें लॉगिन करने के बाद आपको अप्लाई फॉर फ्रेश पासपोर्स (Apply For Fresh Passport) या री इश्यू ऑफ पासपोर्ट (Re-issue of Passport) में से किसी लिंक को चुनना होगा। जैसा कि यहां हम पहली बार पासपोर्ट के आवेदन की प्रक्रिया की बात कर रहे हैं तो इसके लिए अप्लाई फॉर फ्रेश पासपोर्ट (Apply For Fresh Passport) पर क्लिक करना होगा।
स्टेप-4- फॉर्म भरें
अप्लाई फॉर फ्रेश पासपोर्ट पर क्लिक करने के आपके सामने कई सारे फॉर्म आएंगे, जिनमें आपकी जानकारी मांगी जाएगी। इन सभी फॉर्म को सही से भरें। ध्यान रहे कि फॉर्म भरने में गलती न हो, क्योंकि एक बार पासपोर्ट की प्रक्रिया रिजेक्ट होने पर दोबारा पासपोर्ट के लिए आवेदन करने में समय लग जाता है, जिससे समय की बर्बादी होती है।
स्टेप-5- भुगतान और मिलने का समय निर्धारण
‘व्यू सेव्ड/सबमिटेड एप्लिकेशन्स’ (View Saved/Submitted Applications) स्क्रीन पर ‘पे एंड शेड्यूल अप्वाइंटमेंट’ (Pay and Schedule Appointment) लिंक पर क्लिक करें और अपना अप्वाइंटमेंट, यानी मिलने का समय बुक करें।
फॉर्म सबमिट करने के बाद आपके सामने एक विंडो खुलेगी जहां पर आपको पासपोर्ट बनवाने की राशि का भुगतान करना होता है। यह भुगतान आप क्रेडिट कार्ड, डेबिट कार्ड, इंटरनेट बैंकिंग या फिर एसबीआई बैंक के चालान से कर सकते हैं।
स्टेप-6- सारी प्रक्रिया पूरी होने के बाद प्रिंट एप्लिकेशन रिसीप्ट लिंक पर क्लिक करके एप्लिकेशन को प्रिंट करें। इसमें आपका एप्लिकेशन रेफेरेंस नंबर और अप्वाइंटमेंट नंबर होता है।
स्टेप-7- जहां पर भी आपका अप्वाइंटमेंट बुक किया गया है वहां के पासपोर्ट सेवा केन्द्र में अपने असली डॉक्युमेंट्स के साथ जाएं।

Make passport in 10 days

नई दि‍ल्‍ली. पासपोर्ट बनवाने के लिए ऑनलाइन आवेदन करने वालों के लिए अच्छी खबर है। अब सिर्फ 10 दिन में पासपोर्ट बन सकता है। इसके लिए ऑनलाइन आवेदन करना होगा और इसके लिए डॉक्युमेंट्स की लिस्टिंग करना भी जरूरी नहीं है। अपने डॉक्युमेंट्स आवदेक ऑनलाइन समिट कर सकता है। साथ ही, आइडेंटिटी प्रूफ और ऐड्रेस प्रूफ जैसे तमाम डॉक्युमेंट की जगह सिर्फ एक आधार कार्ड से भी काम हो सकता है। आवेदन करते ही आपको अगले 3 दिनों में अप्वॉइंटमेंट मिल जाएगा। पूरी प्रक्रिया होने के ठीक 7 दिन बाद आपका पासपोर्ट आपके हाथ में होगा। यानी कुल मिलाकर सिर्फ 10 दिनों में आपका पासपोर्ट आपके पास आ सकता है।
गाजियाबाद के पासपोर्ट अधिकारी सीताराम यादव का कहना है कि पहले प्रॉसेस में समय लगता था। इसलिए डॉक्युमेंटेशन के जरिए समय को बचाने की कोशिश की जा रही है। हालांकि, कभी-कभी डाक सेवा में देरी या छुट्टियों के चलते पासपोर्ट पहुंचने में ज्यादा समय लग जाता है।
आधार कार्ड का फायदा
सरकार ने आधार कार्ड की प्रक्रिया से आवेदक की आपराधिक गति‍वि‍धि‍यों के सत्यापन की प्रणाली बनाने की कोशिश की है। नई प्रक्रिया के तहत यदि कोई पासपोर्ट के लिए आवेदन करता है और उसके पास आधार कार्ड नहीं है, तो पहले उसे आधार कार्ड बनवाना पड़ सकता है।
क्यों होती थी देरी
दरअसल, सरकार के पास पासपोर्ट के लिए पुलिस सत्यापन के संबंध में लगातार शिकायतें आती हैं और इसके चलते पासपोर्ट जारी करने में देरी होती है। आवेदक को सुविधा देने के लिए मिनिस्ट्री ऑफ होम अफेयर्स ने यह निर्णय लिया है। हम आपको बता रहे हैं कि आवेदक किस तरह अपने पासपोर्ट के लिए ऑनलाइन आवेदन कर सकता है और सिर्फ 10 दिन में अपना पासपोर्ट हासिल कर सकता है।
आइये, जानते हैं क्या है पासपोर्ट के लिए ऑनलाइन आवेदन का प्रॉसेस…
स्टेप-1- पासपोर्ट सेवा पोर्टल पर खुद को रजिस्टर करें

सबसे पहले पासपोर्ट सेवा पोर्टल की वेबसाइट http://www.passportindia.gov.in/AppOnlineProject/welcomeLink पर जाएं। पेज पर register now के लिंक पर क्लिक करें। रजिस्टर करें। इसमें अपनी डिटेल्स भरें। इसके बाद आपको ई-मेल आईडी पर लॉगिन आईडी मिल जाएगी। वापस होम पेज पर जाएं।

स्टेप-2- लॉगिन करें
ई-मेल पर आए लिंक पर क्लिक करके अपने अकाउंट को एक्टिवेट करें। यूजर आईडी भरें और फिर पासवर्ड डालें। अप्लाई फॉर फ्रेश पासपोर्स (Apply For Fresh Passport) या री-इश्यू ऑफ पासपोर्ट लिंक पर क्लिक करें। इसके बाद दो पार्ट हैं। ऑनलाइन पासपोर्ट आवेदन करने के लिए दूसरे ऑप्शन पर क्लिक करें।

Learn HTML: Learn the Foundations of HTML

What Is HTML5?

HTML is a markup language that provides the structure that lies underneath every website—and many mobile apps. You can easily think of HTML as the framing that gives structure to content, but is nearly invisible to the naked eye. HTML stands for HyperText Markup Language. If the term HyperText is unfamiliar—as it is to many—it simply means interactive text. Hypertext is generally made interactive with hyperlinks, which we’ll discuss later on in the tutorial.

For many, learning HTML is a first step towards learning web design and development—or even more advanced programming languages. Most think HTML is clear and easy to learn. Perhaps many think HTML is easy to learn due to the fact that it’s a markup language, which is distinct from a programming language. A markup language is designed to describe the purpose of content pieces in a document.

A common misconception about HTML is that it is used to design a web page or web site. This simply isn’t true. While the HTML language provides structure, that structure is divorced from the actual appearance. The HTML structure can be applied to large-screen monitors, mobile devices and even the printed version of documents.image06

Figure 1: Some of the HTML that structures Udemy.com as viewed in the web browser. You can view the HTML from any site in your web browser by clicking View —> Source in the browser menu.

The actual graphic design of a web site is defined using a separate language called CSS, which stands for Cascading Style Sheet language. In this tutorial we’re going to use mostly HTML5 markup, but will also introduce some CSS so we can make our HTML5 content look better. Even if you don’t have any CSS defined in your document, the browser has default CSS for each HTML5 element. This is known as the default style sheet. The default style sheet styles each HTML element if no CSS is provided. The default styles tend to be very boring, but they do make plain HTML content appear readable in the browser.

Versions of HTML

There are a number of versions of HTML that are in use today. The most current version of HTML is HTML5. It was recently made the current recommendation of the World Wide Web Consortium (W3C), the standards body that governs HTML. (Without standardization and the W3C, every browser might interpret HTML differently, causing a different result in Chrome, Firefox and Safari.)

HTML5 has brought some much-needed standardization to the world of HTML. With HTML5 we can now play audio and video directly in the web browser. This latest version of HTML has brought us many new tags which have allowed us to better describe (or mark up) the content in our documents. For example, before HTML5 we only had (primarily) <p> (paragraph) tags and <h> (heading) tags to describe our content. HTML5 has brought a plethora of new tags to allow us to structure documents. These new tags include header, footer, article, section, aside and nav (for navigation elements).

Prior to HTML5, most developers were using HTML 4.03 or XHTML. HTML 4.03 was an important update over older previous versions of HTML. There are still a great many web sites running on the HTML 4.03 standard today. HTML 4.03 required a bit more verbiage in some places, and was more limited than the current HTML5 version. XHTML was a stricter version of the HTML standard that required code to be compliant with both the HTML and XML development standards.

The good news is there is no real reason to get too hung up on the different versions of HTML. They are all very similar, and the differences are really nuanced. If you are familiar with HTML5 and need to work with older HTML 4.03 code, you should be able to do so without issue.

image08

Figure 2: HTML5 has included many new tags to allow us to describe content well, including: header, footer, article, section and aside.

The Lingo: Tags, Elements, Content, Attributes and Values

HTML5 code can appear confusing at first. It’s important to understand the vocabulary behind HTML5 code, as it makes the code easier to understand and allows you to better communicate about HTML code with others. If you understand and can identify tags, content, attributes and values in HTML5 code, you’ll be well on your way to a better understanding of the code.

Tags and Elements

Tags are the essential building blocks of HTML. Tags are the individual content units that make up the HTML markup language. If you are following best practices, HTML tags are paired into an opening tag and a closing tag. Together an opening tag, closing tag and whatever appears in between are known as an element. Consider the HTML element below:

<p>Until the end of time</p>

In this element there are two tags: the opening and closing “p” tags, which is an abbreviation for paragraph tag. Collectively, the opening tag, the text “Until the end of time” and the closing tag are known as an element.

Opening tags are always placed in brackets like this:
<p>

Closing tags are always placed in brackets with a forward slash like this:
</p>

Elements can be considered the building blocks of HTML code, and tags are the building blocks of elements.

Content

In our element example above, the content of the element is the text “Until the end of time.” The content is most often what is actually being delivered for the user to read, listen to or view. All of the text you view in a browser is content that exists in some element of the HTML code. Element content can be broken down into three categories:

Text Content: Text content inside an element is often directly displayed to the user. Text can be a single sentence, an entire paragraph, or even an entire article. The following HTML element contains only text content:

<p>If you are strong enough, there are no precedents</p>

Element Content: Some elements contain one or more additional elements of content. Later in this tutorial, we’ll examine basic document structure, which uses a number of elements contained in other elements. For example, the <head> element below contains element content:


<head>
    <title>You rock the world</title>
    <meta type="author" description="Mark Lassoff" />
</head>

Empty Content: A few elements can be empty and contain no content at all. These elements are usually abbreviated and not closed with a formal closing tag. The break element, <br/>, is used with frequency and is empty. The “/” in the tag indicates that the tag is both an opening and closing tag.

Attributes and Values

Often tags need to be modified in some way or additional information is needed about how the tag should perform. Frequently, tags need to be linked to CSS or Javascript code in order to make them dynamic. In either of these cases, attributes and values are used. You might see some HTML code that is similar to this:


<p id="first">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas purus felis, finibus sed nunc et, dignissim placerat elit. Curabitur nec leo rhoncus, condimentum urna quis, dapibus sapien. Maecenas condimentum turpis id arcu rhoncus sodales. Vestibulum mattis varius ligula, sed venenatis lorem gravida ut. Donec interdum consectetur congue. Pellentesque tincidunt lobortis pretium. Donec urna urna, cursus eget nunc sit amet, vehicula mattis odio. Nam et venenatis tellus. Etiam at ligula lacinia, mattis nunc eget, condimentum nibh.</p>

If you examine the opening paragraph tag, you’ll notice the addition of an attribute and value. The attribute “id” allows us to assign an identifier to the element. (This is used if we want to address the element through Javascript or CSS code). The value is “first” which is the arbitrary value value I gave this element. There are no specific rules for providing values for id attributes; just be systematic and do what makes sense to you.

In older HTML you may see attributes and values designed to affect the appearance of the content in the browser. For example, you might see code similar to the following:

<p align="center">Tricks of the trade</p>

Be aware that while this is valid code, attributes that change the appearance of the content are no longer recommended for use in HTML5. Appearance is now within the purview of CSS, and this is code that should be updated.

Tools of the Trade

Every profession has “tools of the trade.” In the case of HTML, these are programs that you will use to write and display code. Note that the programs suggested here are merely the author’s recommendations; there are dozens of good tools out there. Most HTML coders discover their favorite tools through a process of trial and error. Try several tools and see which you like best.

The Text Editor

The text editor is the program where you will author your HTML5 code. Text editors are akin to stripped-down word processors. Most importantly, in contrast to word processors, they keep the text “pure” and don’t inject formatting codes that might confuse browsers trying to interpret HTML.

Asking a developer, “What’s the best text editor?” might be akin to starting a heated argument. Many developers are super passionate about their text editors.

A good free text editor is Brackets from Adobe. Brackets is available for PC and Mac, and you can download it for free.

image07

Figure 3: Brackets from Adobe is a free, popular text editor. Examples in this article were created using Brackets.

Your Browser

The browser landscape is always changing. Most developers have several browsers installed on their machine. The goal is often to make sure HTML and CSS code performs the same across that gamut of browsers. Google Chrome remains a favorite of many developers because of its extensive developer tools. Developers’ tools within Chrome provide a means of testing HTML and Javascript code and tracking down problems.

image10

Figure 4: Chrome Developer tools ready for action. These tools can be very helpful in debugging complex web sites.

In addition to Chrome, most web developers have Firefox, Safari and even Opera to test their HTML code. With many Windows users currently upgrading to Windows 10, users should consider testing in the Windows Edge browser, as well.

Your First HTML Document

Now’s the time to fire up your text editor and web browser and write some code. Commonly the first program that developers write when learning a new language is the “Hello World” program. This code displays the text “Hello World” in the browser. To honor the tradition, we’ll do the same here.

Writing the Code

Open your text editor and type the following code:


<!DOCTYPE html>
<html>
    <head>
        <title>First HTML document</title>
    </head>
    <body>
        <h1>Hello World</h1>
    </body>
</html>

Be careful as you key in the code, as a single error might cause the code to display improperly in the browser. Don’t worry much about the meaning of the elements; we’ll discuss those later. For now, just type in the code and get used to the process of writing code in a text editor and displaying it in a browser (which we’ll discuss next).

You’ll notice as you type the code that some lines are indented. This is done in an effort to make the code itself more readable and does not have any effect on how the code is displayed in the web browser. In fact, the browser completely ignores the indentation. The indentation does, however, make it easier for your human colleagues to read your code.

Using the save feature in your text editor saves the document as helloWorld.html. HTML documents you create should always use the .html extension.

Displaying the Result in a Web Browser

Loading the code into your web browser for testing should be as easy as double-clicking the icon for helloWorld.html. Hopefully you should get a result similar to the screenshot below:

image09

Figure 5: The Hello World displayed in Google’s Chrome browser.

If you aren’t greeted with “Hello World” in your browser window, open your text editor again and check your code carefully against the code provided for you.

HTML Document Structure

HTML documents all share a common structure. The structure provides a skeleton for all HTML documents. The structure looks like this:


<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        
    </body>
</html>  

You should note that the first line of code is not actually HTML code. The first line is known as a doc-type definition. Its purpose is to define the document as an HTML document. The doc-type definition shown is for HTML5 documents. The doc-type definition has been greatly simplified for HTML5. The doc-type definition for the older XHTML standard was much longer:


 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

The doc-type definition also has no effect on the way a page is displayed; It is simply declarative, though it might be used by a validator to ensure that the code meets the HTML standard you have declared in the DOCTYPE element.

The basic document structure is generally broken into two parts: the head and the body.

The Document <head>

The document head generally contains three specific types of elements. First, the document <title> element defines a general title for the document. The title is used by search engines, like Google, to index the page. The title is also displayed in the document tab of the browser. Finally, the title is used if the user saves the page as a bookmark.

The second type of element is a “meta” tag. Meta tags provide further information about the document itself. For example, the meta tags may contain a description of the web site that is used by search engines.

image01

Figure 6: Some of the information in Google’s listing on Udemy was supplied by meta tags. Note the descriptions under each page header.

Finally, the third type of element contained in the document head are link elements that tie Javascript code and CSS code to the HTML document. Some complex HTML documents have ten or more link elements that include external scripts and libraries.

The Document <body>

Just about everything the user sees in the document window of the browser is contained in the <body> element of the HTML code. The body is, essentially, a container for the visible content on a page. The body is usually the longer section of the document and can contain an unlimited number of HTML elements.

The document body is where you will spend most of your time as a web developer. Most of the code that we’ll be working on in the rest of this tutorial will appear in the body element of the HTML script.

Displaying Text

The most basic task accomplished with HTML code is displaying text in the browser window. Our initial “Hello World” script displayed text in the browser window. As HTML coders, we actually have quite a bit of control over the text and how it appears in the browser. Let’s take a look at some of the HTML elements that are used to display text.

Headings

Most documents (including this one) have some kind of structure that includes various levels of headings and subheadings. HTML5 documents represent headings in six different levels of importance. The most important headings are marked with the <h1> tag. The secondary headings are marked with <h2>. The least important headings are marked with <h6> (though few documents have a structure that includes six levels of headings).

Consider the following code:


<!DOCTYPE html>
<html>
    <head>
        <title>Headings</title>
    </head>
    <body>
        <h1>This is heading one.</h1>
        <h2>This is heading two.</h2>
        <h3>This is heading three.</h3>
        <h4>This is heading four.</h4>
        <h5>This is heading five.</h5>
        <h6>This is heading six.</h6>
    </body>
</html>

This document displays all six levels of HTML headings. Displayed in a browser, the result should look something like this:

image00

Figure 7: Heading tags rendered in the browser.

Note that by default, the browser displays more important headings as bigger and bolder. However, don’t think of the heading tags as a way to make text bigger; appearance is within the purview of CSS code. It is best to think of heading tags as simply denoting the importance of an individual heading.

<p>aragraph Text

Arguably, the <p>aragraph tag is the most commonly used HTML tag. It is designed to hold a paragraph of text, though it is used by most developers as a generic element that can hold just about anything. Before HTML5 there weren’t too many other options to hold content, so the <p>aragraph tag became a de facto default. In contemporary HTML5 code, however, there exists a plethora of more specific tags that can be used to mark up content. The <p>aragraph tag is still frequently used, but should more or less only be used to demarcate paragraphs within a larger passage of text.

Articles, Details and More

As alluded too earlier, HTML5 introduced a number of new tags used to mark up text. The most popular of these appear below:

Tag Purpose
<article> Defines an article within a document
<aside> A content aside—secondary from the main content
<details> Used to provide additional details that the user can view or hide in most browsers
<figcaption> Defines the caption for a <figure> element
<figure> Self-contained elements like code listings, images, diagrams, animations, etc.
<footer> Defines the footer for the document
<header> Defines a header for the document
<main> Defines the primary content of a document
<nav> Defines the navigation components of an HTML document
<section> Creates a section in a document
<summary> Creates a summary of a document, article or other entity

These tags are meant to allow a document to be more accurately structured. Simply speaking, you should surround your content with whatever tag most accurately denotes the purpose of the content. Some of this can be open to interpretation; however, as long as elements within the document are consistently named, it shouldn’t be difficult to derive meaning from your HTML5 markup.

Typography with CSS

As mentioned earlier, HTML5 is a structural language. It is designed to structure a document and define content elements. HTML5 is not a design language; CSS (Cascading Style Sheets) is the language of design. CSS has a different syntax than HTML, but it is easily deciphered. Below is a typical CSS “rule”.


p {
    font-family: arial, sans-serif;
    font-size: 1.1em;
    color:  red;
}

The “p” in the CSS code above is known as the selector. It allows you to choose which elements the CSS will be applied to. In this case, the CSS styles will be applied to all paragraph elements within the document.

We’ve included three styles to be applied. The first “font-family” style sets the typeface to Arial, or if Arial is not available, any sans-serif font. The next style sets the font size to 110% of the default. The “em” measurement allows the designer to set the font size based on the user’s choice for default size. Multiple the value by 100 to get the percentage of default size. Values greater than one will increase font size. Values less than one will decrease font size. The final CSS style will simply turn the text red.

CSS must be expressed within a style element. Examine the code below:


<!DOCTYPE html>
<html>
    <head>
        <title>First CSS</title>
        <style>
            h1  {
                font-family: Arial, sans-serif;
                font-size: 4em;
                color: red;
            }
        </style>
    </head>
    <body>
       <h1>Hello World</h1>
    </body>
</html>

The result in the browser should appear similar to the screenshot below:

image03

Figure 8: With CSS applied. Note that the text is three times larger than normal, red and rendered in the Arial font.

There are dozens of style rules that can be applied with CSS. Everything from element spacing, to color, to appearance can be controlled with CSS.

This table contains a list of common CSS styles:

Style Possible Values Used with Elements
color #RRGGBB (Red, Green, Blue hex values) any element that contains text
text-align left | right | center | justify block elements h1- h6, p, li, etc.
text-decoration none | underline | overline | line-through | blink | inherit mostly with a (anchor) elements
text-transformation none | capitalize | uppercase | lowercase any element that contains text
line-height % or px block elements h1- h6, p, li, etc.
letter-spacing normal or px value any element that contains text
font-family font or font-family [, font or font-family …] any element that contains text
font-size px or em value any element that contains text
font-style normal | italic | oblique any element that contains text
font-weight normal | bold any element that contains text
background-color #RRGGBB (Red, Green, Blue hex values) any element with a background
background-image url(“[image url]”) mostly with body
background-repeat repeat | repeat-x | repeat-y | no-repeat mostly with body
background-position left | center | right | top | center | bottom mostly with body
list-style-type disc | square | circle ul
list-style-type decimal | lower-roman | upper-roman | lower-alpha | upper-alpha ol

Displaying Media

One of the major advances in HTML5 is the way media is handled. Audio and video media, for example, are now played directly by the browser instead of via a plugin like Flash. This, in part, has led to a proliferation of audio and video content on the web. The inclusion of images, audio and video is fairly easy with HTML5, as you’ll see in the code samples below.

Displaying Images

The way we display static images in a web browser hasn’t changed much in 20 years. There are three file formats that the browser can display: jpg, gif and png. It is preferable to use correctly optimized images that have a minimal file size. Images can be optimized in any graphics editing program like Photoshop. Even though Internet users enjoy more bandwidth than ever before, it is still preferable to optimize images for a minimal file size. This is especially helpful for users who may be trying to access content from a tenuous cellular connection.

The HTML code to display an image looks like this:

<img src="mark.jpg" />

The value of the src attribute is the path and file name of the image. In the example above, the image “mark.jpg” is in the same folder at the HTML file itself, so no path is necessary. Many developers recommend that you include an alt attribute in your image tag. This attribute lets you write a text description of the image, which is helpful to users who might be using a screen reader due to visual impairment.

Audio and Video

Adding audio and video to an HTML document has become much easier over the past few years. Now, all browsers tend to support major audio and video file formats. Just a few years ago, support was more fractured and you couldn’t depend on a specific audio or video file type to work across the gamut of browsers.

The following HTML script plays an audio file called music.mp3.


<!DOCTYPE html>
<html>
    <head>
        <title>Audio</title>
    </head>
    <body>
        <h1>Listen to the Music!</h1>
        <audio controls="controls">
            <source src="music.mp3" />
        </audio>
    </body>
</html>

Every browser has a built-in audio player. While functionally identical, they appear a bit different from browser to browser. The audio tag loads that player. By using the controls attribute, we make controls like play and volume visible to, and adjustable by, the user.

Loaded into the Chrome browser, the audio tag would render a player similar to the screenshot below:

image02

Figure 9: The audio player in Google’s Chrome browser.

To play video with HTML, the code is almost identical. If you have a video file, you can substitute the file name and the video tag for the audio tag.

The following code would play a video with the file name “video.mp4”:


<!DOCTYPE html>
<html>
    <head>
        <title>video</title>
    </head>
    <body>
        <h1>Watch the movie!</h1>
        <video controls="controls">
            <source src="video.mp4" />
        </video>
    </body>
</html>

Browsers have a built-in video player, as well. The following screenshot shows a video being rendered in the Chrome browser:

image05

Figure 10: A sample .mp4 video rendered in the Chrome Browser. Note the video controls superimposed at the bottom of the video.

Hyperlinks

If there is a single advancement that caused the web to explode twenty years ago, it just might be hyperlinks. Hyperlinks give us the ability to jump from one document to another at the click of a mouse. Hyperlinks allowed us to create complex, hierarchical documents that were navigable and dynamic.

Hyperlinks are so common that most developers take them for granted. Hyperlinks—commonly abbreviated as links—fall into two broad categories. External links go from your page to a totally different web site. The second category of links, internal links, select a different page on the current site.

Links can be produced from text or image elements on a page. If you’ve worked with a web interface that included “buttons”, these were likely links. We’ll produce links with the <a>nchor tag.
External Links
External links go from your site to another site on a different domain. For example, if you were linking your site to Udemy.com or CNN.com, these would be external links. For example, my HTML course on Udemy is located at https://www.udemy.com/learn-html5/learn. If I wanted to link to that site, I’d write the following HTML:

<a href="https://www.udemy.com/learn-html5/learn">Learn HTML on Udemy!</a>

There are two components for us to look at in the hyperlink. The first is the text the user will click on in order to activate the link. This text is placed between the opening <a>nchor tag and the closing <a>nchor tag. In the preceding example, “Learn HTML on Udemy!” would be displayed for the user to click.

The second component to examine in a link is the address where you want the user to go on the web when the link is clicked. In the preceding example, we are using the Udemy address that takes the user to the HTML course.

Internal Links

Internal links are not much different from external links, except for the fact that they take the user to another page within the same domain. Imagine moving from the stock listings to the weather on a news site or one course to another on Udemy. These types of moves are accomplished via internal links. Internal links are structurally the same as external links. Let’s say, for example, you had the following two files:


<!DOCTYPE html>
<html>
    <head>
        <title>Links</title>
    </head>
    <body>
        <p>This is page one.</p>
        <p>Would you like to see <a href="page2.html">page two</a>?</p>
    </body>
</html>

page1.html


<!DOCTYPE html>
<html>
    <head>
        <title>Links</title>
    </head>
    <body>
        <p>This is page two.</p>
        <p>Would you like to see <a href="page1.html">page one</a>?</p>
    </body>
</html>

page2.html

You’ll note that the value of the href attribute here does not include the http:// section. Both page1.html and page2.html are on the same domain, and therefore the http:// is not necessary. Again, the words the user will click to activate the link are between the opening and closing <a>nchor tags, and the links work when clicked in the web browser.

image04

Figure 11: The link to page two is displayed in the web browser.

Conclusion

This primer on HTML was designed to give you a quick start in HTML coding. There is much more to learn and to know before you have HTML coding mastered. I hope this tutorial gave you a good introduction to the art of HTML code. Good luck with your future scripts!

Happy Independence Day

india-independence-day-2015-5144578369781760.2-hp

Angry Birds Open GL Error Fix for Windows 7 and XP

Angry Birds Open GL Error Fix for Windows 7 and XP

Image used under Creative Commons from thethreesisters.

You have played Angry Birds in your mobile, now you want to play the game in PC. So you have downloaded the PC version of the game and installed it. Even though installation is successful you may get some OpenGL or DirectX errors. So here is a working fix for all the errors.

You may get one or more of the following errors while running Angry Birds in your computer.

OpenGL 2.0 renderer not supported!

OpenGL 1.4 renderer not supported!

DirectX 11 renderer not supported!

If you get one or more of the above errors here is the fix for this.

We have Two Methods for fixing this. Either of them will surely work for you.

Method 1:

1. In your windows system, go to Start -> Control panel.

2. Go to Device Manager (If you can’t find the option, use the search box).

3. Go to Display Adapters


4. Double Click the Driver which is displayed.

5. In the window that pops up, go to the Driver tab and click Update Driver.

6. Click Search automatically for updated driver software option in the window that pops up.

7. Update the software and Restart your computer.

Go to Angry Birds and your problem should be fixed and you should be able to play the game. If not try Method 2.

Method 2:

Step 1: Updating all your drivers (Recommended)

Even though this step is not totally necessary, I recommend you to do this because it will also tackle the future problems while running games of any kind and it takes only a few minutes and it is fully automatic.

Go to the following link:
http://goo.gl/g1pCO

It is the Intel Automatic Driver Update Utility. It checks for the drivers in your computer and updates them if needed.

Step 2: Installing the latest DirectX (Recommended)

Some of you may get the DirectX error along with the Open GL error. If so this step is a must and for others I strongly recommend in installing the latest DirectX from the following link.

http://goo.gl/vhZhI

Alternately, you can download the latest DirectX from here: DirectX 11
The above link gives you the direct executable file rather than a web installer.

Step 3: Installing the Intel Graphics Media Accelerator Driver (Must)

This is the final and most important step in tackling the Open GL error. Just download the Intel Graphics Media Accelerator Driver for your operating system either windows 7 or windows xp from the following link and install it.

Intel Graphics Media Accelerator Driver for Windows 7:

http://goo.gl/BmtRn

Intel Graphics Media Accelerator Driver for Windows XP:

http://goo.gl/AxjAk

If the above two links didn’t work for you, go to the below link and select the Driver according to your System Configurations:

http://goo.gl/PwGw8

Now Restart your computer.

Try running the game and you should be able to play now!

All the above steps are explained in the following YouTube video:

If you have any problems just leave a comment stating your problem.

If this worked for you, give this page a +1 and Recommend it to google.

If you have found other solutions, do share it in the comment section below.

Thanks.

65 comments:

  1. deu certo mesmo valeu pela dica fico te devendo esssa..

    Reply

  2. not working in Windows 8
    Error: OpenGL 1.3 is not supported

    Reply

  3. Dude try the first method correctly.
    It will work for sure!

  4. when i completed the first method , after some some time a message appeared that you have the latest version of intel drivers. but still not able to play game

    Reply

  5. Update your DirectX and try again.

  6. You’re welcome dude!

  7. i attempted method 2
    while installing the graphic media accelator
    it prompt that system didnot meet the minimum requirements
    what should i do?

    Reply

  8. You must have downloaded the wrong driver.
    Have you tried method 1??
    If not try it. It is easy.

  9. hey buddy when i did the first method it showed that the best driver software for your computer is already been installed.what would i do now. please help me. my all pc games are not working dude.

  10. i can’t find device manger

    Reply

  11. If you are in Windows7 go to -> Start and in the search box type “Device Manager”.
    You will find it for sure.

  12. thanks buddy..it worked correctly..thanks from heart…

    Reply

  13. thanks dude…… you are really a god

    Reply

  14. Dude, I’m not a God. Just consider me as your friend.

  15. hi ! i have a problem with my graphic card driver when i try to update it it doesn’t work it downloaded the driver with no problems but when it try to install it says : (there was a problem during the installation )
    pleaseee help :/ !!
    thanx !

    Reply

  16. Did you try the first method ??

    If not try it.

    Still the error appears ???

    Give me the details of the error.

  17. first method worked for me
    thank u.

    Reply

  18. when i update the driver, it says that the best driver software for your device s already installed…….

    Reply

  19. Ok. Try the second method.

  20. hey buddy!! i have downloaded the setup of BLUSTACKS APP PLAYER but on installing it ,it shows YOUR GRAPHIC CARD DOESN’T RECOGNIZED YOU MAY NEED TO UPDATE IT .and when i go to DISPAY ADAPTERS it shows your graphic card is already updated ..so plz plz plz HeLp mE oUt…

    Reply

  21. Try the second method and let me know the result.

  22. i’ve tried but on installing the graphic media accelerator from your given link it shows that YOU HAVE LATEST VERSION WORKING ON YOUR DEVICE THAT THIS VERSION..and i’ve windows 8 so it has already installed the laest version of directx (directx 11) ..moreover my all drivers are updated ..that means i’ve tried both the methods ..so if you have another solution of this complexxx ..then plz tell me ..

  23. Exactly what error are you getting ??

    Is it ‘OpenGL’ error or anything else ??

  24. in angry birds i’m getting ..opengl 2.0 renderer not supported!reason:
    opengl 2.0 is not supported

    opengl 1.4 renderer not supported!reason:
    openhl 1.3 is not supported

    and on installing BLUSTACK i’m getting ..bluestack currently doesn’t recognize your graphic card. it is possible that your graphic drivers may need to be updated .please update them and try installing again.

  25. method 2 step one worked perfect for me ! thank you very much !!

    Reply

  26. texture problem too large!! solve this!!

    Reply

  27. n i have standard vga graphics adapter which is up to date!!

  28. Texture problem is also caused due to graphic drivers.

    You claim that you have your driver up to date.

    But I recommend you to go for the second method mentioned in the article.

  29. I method 1 The dialog box is saying that my driver is up to date
    And in the 2nd method diagnostics report is that my driver is updated.But still Angry Birds is not running in my computer.What should I do? Please help.

    Reply

  30. I have a link for updating your drivers manually in ‘Method 2′

    Pleas refer to that.

  31. hallo frnd I have acer D270 notebook,atom processor,I hve instld AB but it shows open gl render 2.0 error. Also I hav downloaded display drivers but I think its wrong.Hw can i find right matched audio, video drives from net.plz help me.

    Reply

  32. You can follow the steps in ‘Method 2′

  33. Nothing has worked at all. I have done everything you stated and restarted the computer. I am running windows 7. I keep getting an error window:

    OpenGL 1.4 renderer not supported!
    OpenGL ES 1.1 renderer not supported!
    OpenGL ES 2.0 renderer not supported!

    Any ideas?

    Thank you.

    Reply

  34. What about DirectX ???

    Is it up to date ??

  35. Dear Sir,
    I have the same problem. My driver is up to date. In method two the files downloaded do not install saying that system does not meet minimum requirements even when manually selecting file. Directx also not installed and failed. Pl help

  36. method 1 not working. i tried 2 method but the media graphic acclrator dosen’t install properly

    Reply

  37. method 2 ,step 2 and step3 dosen’t instaal. nw what can i do to play the game

    Reply

  38. my nopreating system is windos ultimate 64bit..media acclerator dosen’t suppot it

    Reply

  39. hi man the accelerator while em installing it it told me tat m minimum system requirements aren’t the minimum requirements

    my ram is 4 g byte and 1 g for my videos card

    Reply

  40. thanks man, your both the methods worked for me. :-)

    Reply

  41. i have latest graphic driver and latest directx… windows 8 pro x86 system (original with all updates) and still not work for me… playing any new games without problems…

    Reply

  42. very nice suggestions !!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    Reply

  43. Yea…it worked..lol I tried method #2 i updated my driver with no problems…media graphiocs card would not update though…said my system didn’t support ?? idk but anyway I tried Angry birds again with the new driver unstalled and it worked :) thank you so much for your help and your links..lol I think I better bookmark your page for future use..lol thanks buds :)

    Reply

  44. hey..
    i want to download opengl1.3 because..
    my 2nd PC doesnt have any net connection ..
    so any other option plz tell me @ dharmingheewala@yahoo.in
    p;zzzz dear… help me..

    Reply

  45. very useful info.Thank u dear Friend

    Reply

  46. I faced problem in Windows 7 that openGL 2.0 and 1.4 not supported.
    I applied your above stated solution Step 3 : Install Intel Graphics Media Accelerator Driver for Windows 7
    I have succeeded and Angry Birds is now running.
    Many thanks.

    Reply

  47. my driver is via chrome 9 family and i use windows xp .even my ram is 512mb and i dont have graphics card in my pc.can i run the game on my pc.even i am getting the opengl problem

    Reply

  48. hi! tried everything from method 1 to 2. restart my computer then tried opening the angry bird, the same problem pop up again. downloaded the directx 11 then it said the update is not applicable on your computer. what i will do? pls help thanks…

    Reply

  49. This comment has been removed by the author.

    Reply

  50. running on windows 7 and my display adapter is NVIDIA GeForce 8500 GT. hope that could help. thank you

    Reply

  51. This comment has been removed by a blog administrator.

    Reply

  52. what if my video card is nvidia would it still work?

    Reply

  53. thanku! it really worked

    Reply

  54. thanxxxxx man …u r awesome

    Reply

  55. plz someone tell me where to find intel graphics media accelerator drives
    i m not able to find them for windows 8.1
    and i need them to play games
    i get all of the above mentioned errors+directx 11 renderer not supported

    Reply

  56. my OS windows 7 home premium 64bit and display adaptor intel(R) G41 express chipset (microsoft corporation-WDDM 1.1) , processor Pentium(R) Dual Core CPU E5400@ 2.70 GHz. when i tried to update driver it says it is ok then i tried to installIntel(R) Grapphics media acceletor driver , it says with this configuration can’t install.What can i do now? I tried your method 1 in another computer and it worked

    Reply

National Digital Literacy Mission Govt Of India

NDLM

How to answer “tell me about yourself”

“So, Tell Me About Yourself….”

I recall, early in my career, when I responded to that interview question with a not so brief biography, starting with where I was born, where I went to school, my family members and do I need to go on?

Learn from my mistake……..

The recruiter stifled a few yawns but did not interrupt me. I was well into my 10 minute life story when I suddenly saw the look on his face and knew I was doomed; it was no surprise that I was not hired. I couldn’t even chalk this faux pas to a case of the nerves; I was just not aware how to interview. Interesting that I later found a career in human resources management and was responsible for selecting candidates.

No one teaches you how to interview.

Guidance counselors and career services offer overviews and there is information on the internet but you probably haven’t had someone guide youthrough the process, role playing the interview and providing you with feedback based on your responses. I learned by being on the other side of the table and as a recruiter. I spent many hours shadowing other human resources professionals and completing formal training which culminated in certifications.

As a job seeker, the question, “Tell me about yourself” can be intimidating because you don’t know how much detail the recruiter wants to hear. I assure you – not much. This is an icebreaker type of question and used for assessing your ability to present yourself and your qualifications for the job. So here are my recommendations for how to respond:

  1. WHY: Explain why you applied for the position
  2. WHAT: Briefly summarize your current role and share a bit of information about previous positions with the emphasis on your achievements in those roles. Think of this as a two minute advertisement airing on prime time. What do you want the recruiter to know about you?
  3. STRENGTHS: Share your strengths and expertise by referencing what others have pointed out as your strengths
  4. BRIDGE: Now share how what you have accomplished will benefit the prospective company. Shift the focus from YOU to the COMPANY – very important.
  5. CLOSE: Having assumed you did your research of the company, reference something you find relatable to the position and what you can do for the company. Here’s where you can really shine because many candidates simply don’t do their homework. Let’s say that you are in customer service management and the prospective company is expanding with a new call center. Ask the recruiter what is considered the biggest challenge of the growth and be prepared to respond with an example of how you may have handled that specific obstacle or issue.

You may ask, “Why not ask the recruiter for more clarification?” The short answer: Timing. That type of response, especially for the first question of the interview, may lead the recruiter to think that you may need constant clarification if hired and you won’t be able to work effectively in ambiguous situations. Wait to ask type of questions of the recruiter later in the interview.

Practice makes Perfect:

Be prepared by knowing what strengths and experience you want to share the most. Write down your response and say it aloud a few times until you gain confidence. Your prep work will keep you focused, provide the company they are seeking and you will be confidently in control of your response.

Want more career advice or assistance preparing for an interview? Contact : Patricia@CareerWisdomCoach.com. Based on a career of selecting top talent for Fortune 500 companies, He can help you succeed at showcasing your experience. He specialize in developing compelling resumes, linked in profiles and helping you design a laser-focused job search strategy. Contact me for a free consult.

Photo credits: primermagazine.com,

Tankadhar Training Center

Tankadhar Training Center – The only open source web developer training institute at rayagada. Golden Opportunity for BTECH and MCA students. Don’t need to wait for completion of course to go to banglore and learn the course to boost your chance of getting a job. Just do the course while studing and boost your carrier.Tankadhar Training Center

https://www.youtube.com/watch?v=I9KAoTQlEWs

Viacom18 Motion Pictures presents in association with NFDC and Maya Movies: Manjhi -The Mountain Man, releasing on August 21st, 2015. A film by Ketan Mehta starring versatile actor Nawazuddin Siddiqui in and as Manjhi along with Radhika Apte playing his beloved wife, this biopic is the story of an ordinary man who performed the extraordinary.

Lesson 6 : Working with Typography

Working with Typography

The field of web typography has grown substantially over time. There are a couple of different reasons for its rise in popularity; one widely acknowledged reason is the development of a system for embedding our own web fonts on a website.

In the past we were limited to a small number of typefaces that we could use on a website. These typefaces were the most commonly installed fonts on computers, so they were the most likely to render properly on-screen. If a font wasn’t installed on a computer, it wouldn’t render on the website either. Now, with the ability to embed fonts, we have a much larger palette of typefaces to choose from, including those that we add to a website.

While the ability to embed fonts gives us access to countless new typefaces, it’s also important for us to know the basic principles of typography. In this lesson we’re going to take a look at some of these basic principles and how to apply them to our web pages using HTML and CSS.

Typeface vs. Font

The terms “typeface” and “font” are often interchanged, causing confusion. Here is a breakdown of exactly what each term means.

A typeface is what we see. It is the artistic impression of how text looks, feels, and reads.

A font is a file that contains a typeface. Using a font on a computer allows the computer to access the typeface.

One way to help clarify the difference between a typeface and a font is to compare them to a song and an MP3. A typeface is very similar to a song in that it is a work of art. It is created by an artist or artists and is open to public interpretation. A font, on the other hand, is very similar to an MP3 in that it is not the artistic impression itself, but only a method of delivering the artistic value.

Adding Color to Text

Typically one of the first decisions we’ll make when building a website is choosing the primary typeface and text color to be used. While there are a number of other properties that can be changed—size, weight, and so on—the typeface and text color generally have the largest impact on the look and legibility of a page. Getting rid of the browser defaults and using our own typeface and text color immediately begins setting the tone of our page.

The only property we need to set the color of text is the color property. The color property accepts one color value, but in many different formats. These formats, as we discussed in Lesson 3, “Getting to Know CSS,” include keywords, hexadecimal values, and RGB, RGBa, HSL, and HSLa values. Hexadecimal values are the most prevalent, as they provide the most control with the least amount of effort.

Let’s take a look at the CSS required to change the color of all the text within the <html> element on a page:

1
2
3
4
html {
  color: #555;
}

Changing Font Properties

CSS offers a lot of different properties for editing the look and feel of text on a page. These properties fit into two categories: font-based properties and text-based properties. Most of these properties will be prefaced with either font-* or text-*. To begin we’ll discuss the font-based properties.

Font Family

The font-family property is used to declare which font—as well as which fallback or substitute fonts—should be used to display text. The value of the font-family property contains multiple font names, all comma separated.

The first declared font, starting from the left, is the primary font choice. Should the first font be unavailable, alternative fonts are declared after it in order of preference from left to right.

Font names consisting of two or more words need to be wrapped in quotation marks. Additionally, the last font should be a keyword value, which will use the system default font for the specified type, most commonly either sans-serif or serif.

The font-family property in action looks like this:

1
2
3
4
body {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

In this case, Helvetica Neue is the preferred font to display. If this font is unavailable or not installed on a given device, the next font in the list—Helvetica—will be used, and so on.

Font Size

The font-size property provides the ability to set the size of text using common length values, including pixels, em units, percentages, points, or font-size keywords.

Here the CSS is setting a font-size of 14 pixels on the <body> element:

1
2
3
4
body {
  font-size: 14px;
}

Font Style

To change text to italics, or to prevent text from being italicized, we’ll use the font-style property. The font-style property accepts four keyword values: normal, italic, oblique, and inherit. Of these four, the most commonly used are italic (sets text to italic) and normal (returns text to its normal style).

The following CSS sets all elements with a class of special to include a font-style of italic:

1
2
3
4
.special {
  font-style: italic;
}

Font Variant

It doesn’t happen often, but occasionally text will need to be set in small capitals, also known as small caps. For this specific case we’ll use the font-variant property. The font-variant property accepts three values: normal, small-caps, and inherit. The most typically seen values are normal and small-caps, which are used to switch typefaces between normal and small caps variants.

To switch all elements with a class of firm, we’ll use a font-variant of small-caps:

1
2
3
4
.firm {
  font-variant: small-caps;
}

Font Weight

Occasionally, we’ll want to style text as bold or to change the specific weight of a typeface. For these cases we’ll use the font-weight property. The font-weight property accepts either keyword or numeric values.

Keyword values include normal, bold, bolder, lighter, and inherit. Of these keyword values, it is recommended to primarily use normal and bold to change text from normal to bold and vice versa. Rather than using the keyword values bolder or lighter, it’s better to use a numeric value for more specific control.

In practice, here’s the CSS to set the font-weight to bold for any element with the class of daring:

1
2
3
4
.daring {
  font-weight: bold;
}

The numeric values 100, 200, 300, 400, 500, 600, 700, 800, and 900 pertain specifically to typefaces that have multiple weights. The order of these weights starts with the thinnest weight, 100, and scales up to the thickest weight, 900. For reference, the keyword value of normal maps to 400 and the keyword bold maps to 700; thus, any numeric value below 400 will be fairly thin, and any value above 700 will be fairly thick.

Changing the font-weight to 600 for any element with the class of daring now renders that text as semibold—not quite as thick as the bold keyword value from before:

1
2
3
4
.daring {
  font-weight: 600;
}

Typeface Weights

Before using a numeric value, we need to check and see whether the typeface we are using comes in the weight we’d like to use. Attempting to use a weight that’s not available for a given typeface will cause those styles to default to the closest value.

For example, the Times New Roman typeface comes in two weights: normal, or 400, and bold, or 700. Attempting to use a weight of 900 will default the typeface to the closest related weight, 700 in this case.

Line Height

Line height, the distance between two lines of text (often referred to as leading) is declared using the line-height property. The line-height property accepts all general length values, which we covered in Lesson 3, “Getting to Know CSS.”

The best practice for legibility is to set the line-height to around one and a half times our font-size property value. This could be quickly accomplished by setting the line-height to 150%, or just 1.5. However, if we’re working with a baseline grid, having a little more control over our line-height using pixels may be preferable.

Looking at the CSS, we’re setting a line-height of 22 pixels within the element, thus placing 22 pixels between each line of text:

1
2
3
4
body {
  line-height: 22px;
}

Line height may also be used to vertically center a single line of text within an element. Using the same property value for the line-height and height properties will vertically center the text:

1
2
3
4
5
.btn {
  height: 22px;
  line-height: 22px;
}

This technique may be seen with buttons, alert messages, and other single-line text blocks.

Shorthand Font Properties

All of the font-based properties listed earlier may be combined and rolled into one font property and shorthand value. The font property can accept multiple font-based property values. The order of these property values should be as follows, from left to right: font-style, font-variant, font-weight, font-size, line-height, and font-family.

As a shorthand value, these property values are listed from left to right without the use of commas (except for font names, as the font-family property value uses commas). A forward slash, /, separator is needed between the font-size and line-height property values.

When using this shorthand value, every property value is optional except the font-size and font-family property values. That said, we can include only the font-size and font-family property values in the shorthand value if we wish.

1
2
3
4
html {
  font: italic small-caps bold 14px/22px "Helvetica Neue", Helvetica, Arial, sans-serif;
}

Font Properties All Together

Let’s take a look at an example that uses all these font-based properties together. The following HTML and CSS demonstrates the different possibilities when styling text.

HTML
1
2
3
4
5
6
<h2><a href="#">I Am a Builder</a></h2>

<p class="byline">Posted by Shay Howe</p>

<p>Every day I see designers and developers working alongside one another. They work intelligently in pursuit of business objectives. They work diligently making exceptional products. They solve real problems and take pride in their work. They are builders. <a href="#">Continue&#8230;</a></p>
CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
h2,
p {
  color: #555;
  font: 13px/20px "Helvetica Neue", Helvetica, Arial, sans-serif;
}
a {
  color: #0087cc;
}
a:hover {
  color: #ff7b29;
}
h2 {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 6px;
}
.byline {
  color: #9799a7;
  font-family: Georgia, Times, "Times New Roman", serif;
  font-style: italic;
  margin-bottom: 18px;
}

CSS Pseudo-Classes

The demonstration here uses the :hover CSS pseudo-class, something we’ve never seen before. For reference, pseudo-classes are keywords that may be added to the end of a selector to style an element when it’s in a unique state.

The :hover pseudo-class styles an element when a user hovers over that element. When used with the <a> element, as shown here, all <a> elements will receive unique styles when they are hovered over. Now our <a> elements will change color upon being hovered over.

In Practice

Diving back into our Styles Conference website, let’s start adding some font-based properties.

  1. We’ll begin by updating the font on all of our text. To do this, we’ll apply styles to our <body> element. We’ll start with a color, and we’ll also add in font-weight, font-size, line-height, and font-family values by way of the font property and shorthand values.

    In an attempt to keep our main.css file as organized as possible, let’s create a new section for these custom styles, placing it just below our reset and above our grid styles.

    We need to add the following:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    /*
      ========================================
      Custom styles
      ========================================
    */
    body {
      color: #888;
      font: 300 16px/22px "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
    }
    
  2. In Lesson 4, “Opening the Box Model,” we began adding some typographic styles, specifically adding a bottom margin to a few different levels of headings and paragraphs. Within the same section of the main.css file, let’s add a color to the level-one through level-four headings.
    1
    2
    3
    4
    h1, h2, h3, h4 {
      color: #648880;
    }
    

    While we’re at it, let’s also add in font sizes for these different heading levels. Our <h1> and <h2> elements will use fairly large font-size values; consequently, we’ll also want to increase their line-height values to keep the text within these elements legible. For reference, we’ll make their line-height values 44 pixels, double the value of the base line-height set within the <body> element rule set.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    h1 {
      font-size: 36px;
      line-height: 44px;
    }
    h2 {
      font-size: 24px;
      line-height: 44px;
    }
    h3 {
      font-size: 21px;
    }
    h4 {
      font-size: 18px;
    }
    
  3. Our <h5> elements are going to be a little more unique than the rest of our headings. Accordingly, we’re going to change their styles a bit.

    We’ll use a different color property value and a slightly smaller font-size for these elements, and we’re going to change the font-weight to 400, or normal.

    By default, browsers render headings with a font-weight of bold. Our headings, however, are currently all set to a font-weight of 300. Our reset at the top of our main.css file changed the font-weight to normal, and then our font-weight of 300 within the <body> element rule set changed all headings to a font-weight of 300.

    The font-weight of 400 on the <h5> element will actually make it slightly thicker than the rest of our other headings and text.

    1
    2
    3
    4
    5
    6
    h5 {
      color: #a9b2b9;
      font-size: 14px;
      font-weight: 400;
    }
    
  4. Our reset at the beginning of our style sheet also reset the browser default styles for the <strong>, <cite>, and <em> elements, which we’ll want to add back in. For our <strong> elements we’ll want to set a font-weight of 400, which actually equates to normal, not bold, as the typeface we’re using is thicker than most typefaces. Then, for our <cite> and <em> elements we’ll want to set a font-style of italic.
    1
    2
    3
    4
    5
    6
    7
    strong {
      font-weight: 400;
    }
    cite, em {
      font-style: italic;
    }
    
  5. We’re on a roll, so let’s keep going by adding some styles to our anchor elements. Currently they are the browser default blue. Let’s make them the same color as our <h1> through <h4> heading elements. Additionally, let’s use the :hover pseudo-class to change the color to a light gray when a user hovers over an anchor.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    /*
      ========================================
      Links
      ========================================
    */
    
    a:hover {
      color: #a9b2b9;
    }
    a {
      color: #648880;
    }
    
  6. Now let’s take a look at our <header> element and update our styles there. We’ll begin updating our logo by adding the font-size and line-height properties within the logo rule set. Adding to the existing border-top, float, and padding properties, the new rule set should look like this:
    1
    2
    3
    4
    5
    6
    7
    8
    .logo {
      border-top: 4px solid #648880;
      float: left;
      font-size: 48px;
      line-height: 44px;
      padding: 40px 0 22px 0;
    }
    
  7. Because we’ve bumped up the size of the logo quite a bit, let’s add a margin to the <h3> element within the <header> element to balance it. We’ll do so by placing a class attribute value of tagline on the <h3> element and then using that class within our CSS to apply the proper margins.

    Let’s not forget that the changes to the <h3> element need to happen on every page.

    HTML
    1
    2
    <h3 class="tagline">August 24&ndash;26th &mdash; Chicago, IL</h3>
    
    CSS
    1
    2
    3
    4
    .tagline {
      margin: 66px 0 22px 0;
    }
    
  8. After the <h3> element with the class attribute value of tagline comes the <nav> element. Let’s add a class attribute value of primary-nav to the <nav> element and add font-size and font-weight properties to make the navigation stand out against the rest of the header.
    HTML
    1
    2
    3
    4
    <nav class="primary-nav">
      ...
    </nav>
    
    CSS
    1
    2
    3
    4
    5
    .primary-nav {
      font-size: 14px;
      font-weight: 400;
    }
    
  9. With the <header> element in slightly better shape, let’s also take a look at our <footer> element. Using the primary-footer class, let’s change the color and font-size for all the text within the <footer> element. Additionally, let’s bump up the font-weight of the <small> element to 400.

    Including the existing styles, the styles for our primary footer section should look like this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    .primary-footer {
      color: #648880;
      font-size: 14px;
      padding-bottom: 44px;
      padding-top: 44px;
    }
    .primary-footer small {
      float: left;
      font-weight: 400;
    }
    
  10. Let’s update our home page a bit, too. We’ll start with the hero section, increasing the overall line-height of the section to 44 pixels. We’ll also make the text within this section larger, increasing the <h2> element’s font-size to 36 pixels and the <p> element’s font-size to 24 pixels.

    We can make all of these changes by using the existing hero class selector and creating new selectors for the <h2> and <p> elements. Our styles for the hero section will now break down in this way:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    .hero {
      line-height: 44px;
      padding: 22px 80px 66px 80px;
    }
    .hero h2 {
      font-size: 36px;
    }
    .hero p {
      font-size: 24px;
    }
    
  11. Lastly, we have one small issue to fix on our home page. Previously we gave all of our anchor elements a light gray color value when a user hovers over them. This works great, except for within the three teasers on our home page where the anchor element wraps both <h3> and <h5> elements. Because the <h3> and <h5> elements have their own color definition, they are not affected by the :hover pseudo-class styles from before.

    Fortunately we can fix this, although it’s going to require a fairly complicated selector. We’ll begin by adding a class attribute value of teaser to all three columns on the home page. We’ll use this class as a qualifying selector shortly.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    <section class="grid">
    
      <!-- Speakers -->
      
      <section class="teaser col-1-3">
        <a href="speakers.html">
          <h5>Speakers</h5>
          <h3>World-Class Speakers</h3>
        </a>
        <p>Joining us from all around the world are over twenty fantastic speakers, here to share their stories.</p>
      </section>
    
      ...
    
    </section>
    

    With a qualifying class in place, we’re ready to do some CSS heavy lifting and create a fairly complex selector. We’ll begin our selector with the teaser class, as we only want to target elements within an element with the class of teaser. From there we want to apply styles to elements that reside within anchor elements that are being hovered over; thus we’ll add the a type selector along with the :hover pseudo-class. Lastly, we’ll add the h3 type selector to select the actual <h3> elements we wish to apply styles to.

    Altogether, our selector and styles for these <h3> elements will look like this:

    1
    2
    3
    4
    .teaser a:hover h3 {
      color: #a9b2b9;
    }
    

Whew, that was quite a bit. The good news is that our Styles Conference home page is starting to look really nice and is showing a bit of personality.

Styles Conference website
Fig 6Our Styles Conference website has received quite a bit of love from a handful of font-based properties

Applying Text Properties

Knowing how to set the family, size, style, variant, weight, and line height of a font is only half the battle. Additionally we can decide how to align, decorate, indent, transform, and space text. Let’s start with text alignment.

Text Align

Aligning text is an important part of building a rhythm and flow on a page; we do this using the text-align property. The text-align property has five values: left, right, center, justify, and inherit. All of these values are fairly straightforward; as expected, they align text to the left, right, or center, or they justify text.

The following CSS sets all paragraph text to be center aligned:

1
2
3
4
p {
  text-align: center;
}

The text-align property, however, should not be confused with the float property. The text-align values left and right will align text within an element to the left or right, whereas the float values left and right will move the entire element. Sometimes the text-align property will give us the desired outcome, and other times we may need to use the float property.

Text Decoration

The text-decoration property provides a handful of ways to spruce up text. It accepts the keyword values of none, underline, overline, line-through, and inherit. Use of the text-decoration property varies, but the most popular use is to underline links, which is a default browser style.

Here the CSS styles any element with the class of note with a text-decoration of underline:

1
2
3
4
.note {
  text-decoration: underline;
}

Multiple text-decoration values may be applied to an element at once by space-separating each keyword within the value.

Text Indent

The text-indent property can be used to indent the first line of text within an element, as is commonly seen in printed publications. All common length values are available for this property, including pixels, points, percentages, and so on. Positive values will indent text inward, while negative values will indent text outward.

Here, the CSS indents the text for all <p> elements inward by 20 pixels:

1
2
3
4
p {
  text-indent: 20px;
}

Text Shadow

The text-shadow property allows us to add a shadow or multiple shadows to text. The property generally takes four values, all listed one after the other from left to right. The first three values are lengths, and the last value is a color.

Within the three length values, the first value determines the shadow’s horizontal offset, the second value determines the shadow’s vertical offset, and the third value determines the shadow’s blur radius. The fourth, and last, value is the shadow’s color, which can be any of the color values used within the color property.

The text-shadow property here is casting a 30% opaque black shadow 3 pixels towards the right, 6 pixels down, and blurred 2 pixels off all <p> element text:

1
2
3
4
p {
  text-shadow: 3px 6px 2px rgba(0, 0, 0, .3);
}

Using negative length values for the horizontal and vertical offsets allows us to move shadows toward the left and the top.

Multiple text shadows can also be chained together using comma-separated values, adding more than one shadow to the text. Using numerous shadows allows us to place them above and below the text, or in any variation we desire.

Box Shadow

The text-shadow property places a shadow specifically on the text of an element. If we’d like to place a shadow on the element as a whole, we can use the box-shadow property.

The box-shadow property works just like the text-shadow property, accepting values for horizontal and vertical offsets, a blur, and a color.

The box-shadow property also accepts an optional fourth length value, before the color value, for the spread of a shadow. As a positive length value, the spread will expand the shadow larger than the size of the element it’s applied to, and as a negative length value the spread will shrink the shadow to be smaller than the size of the element it’s applied to.

Lastly, the box-shadow property may include an optional inset value at the beginning of the value to place the shadow inside an element as opposed to outside the element.

Text Transform

Similar to the font-variant property, there is the text-transform property. While the font-variant property looks for an alternate variant of a typeface, the text-transform property will change the text inline without the need for an alternate typeface. The text-transform property accepts five values: none, capitalize, uppercase, lowercase, and inherit.

The capitalize value will capitalize the first letter of each word, the uppercase value will capitalize every letter, and the lowercase value will make every letter lowercase. Using none will return any of these inherited values back to the original text style.

The following CSS sets all <p> element text to appear in all uppercase letters:

1
2
3
4
p {
  text-transform: uppercase;
}

Letter Spacing

Using the letter-spacing property, we can adjust the space (or tracking) between the letters on a page. A positive length value will push letters farther apart from one another, while a negative length value will pull letters closer together. The keyword value none will return the space between letters back to its normal size.

Using a relative length value with the letter-spacing property will help ensure that we maintain the correct spacing between letters as the font-size of the text is changed. It is, however, always a good idea to double-check our work.

With the CSS here, all of the letters within our <p> elements will appear .5 em closer together:

1
2
3
4
p {
  letter-spacing: -.5em;
}

Word Spacing

Much like the letter-spacing property, we can also adjust the space between words within an element using the word-spacing property. The word-spacing property accepts the same length values and keywords as the letter-spacing property. Instead of spacing letters apart, though, the word-spacing property applies those values between words.

Here every word within a <p> element will be spaced .25 em apart.

1
2
3
4
p {
  word-spacing: .25em;
}

Text Properties All Together

Let’s revisit our blog teaser demonstration from before, this time adding in a few text-based properties on top of our font-based properties.

HTML
1
2
3
4
5
6
<h2><a href="#">I Am a Builder</a></h2>

<p class="byline">Posted by Shay Howe</p>

<p class="intro">Every day I see designers and developers working alongside one another. They work intelligently in pursuit of business objectives. They work diligently making exceptional products. They solve real problems and take pride in their work. They are builders. <a href="#">Continue&#8230;</a></p>
CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
h2,
p {
  color: #555;
  font: 13px/20px "Helvetica Neue", Helvetica, Arial, sans-serif;
}
a {
  color: #0087cc;
}
a:hover {
  color: #ff7b29;
}
h2 {
  font-size: 22px;
  font-weight: bold;
  letter-spacing: -.02em;
  margin-bottom: 6px;
}
h2 a {
  text-decoration: none;
  text-shadow: 2px 2px 1px rgba(0, 0, 0, .2);
}
.byline {
  color: #9799a7;
  font-family: Georgia, Times, "Times New Roman", serif;
  font-style: italic;
  margin-bottom: 18px;
}
.intro {
  text-indent: 15px;
}
.intro a {
  font-size: 11px;
  font-weight: bold;
  text-decoration: underline;
  text-transform: uppercase;
}

In Practice

With text-based properties under our belts, let’s jump back into our Styles Conference website and put them to work.

  1. Currently every link on the page is underlined, which is the default style for anchor elements. This style is a little overbearing at times, though, so we’re going to change it up a bit.

    Adding to our links section within our main.css file, we’ll begin by removing the underline from all anchor elements by way of the text-decoration property. Next, we’ll select all anchor elements that appear within a paragraph element and give them a bottom border.

    We could use the text-decoration property instead of the border-bottom property to underline all the links within each paragraph; however, by using the border-bottom property we have more control over the underline’s appearance. Here, for example, the underline will be a different color than the text itself.

    Our links section, which includes our previous hover styles, should look like this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    a {
      color: #648880;
      text-decoration: none;
    }
    a:hover {
      color: #a9b2b9;
    }
    p a {
      border-bottom: 1px solid #dfe2e5;
    }
    
  2. Going back to our <h5> elements from before, which have slightly different styles than the rest of the headings, let’s make them all uppercase using the text-transform property. Our new <h5> element styles should look like this:
    1
    2
    3
    4
    5
    6
    7
    h5 {
      color: #a9b2b9;
      font-size: 14px;
      font-weight: 400;
      text-transform: uppercase;
    }
    
  3. Let’s revisit our <header> element to apply additional styles to our navigation menu (to which we previously added the primary-nav class attribute value). After the existing font-size and font-weight properties, let’s add some slight letter-spacing and change our text to all uppercase via the text-transform property.

    Our styles for the <nav> element with the primary-nav class attribute value should now look like this:

    1
    2
    3
    4
    5
    6
    7
    .primary-nav {
      font-size: 14px;
      font-weight: 400;
      letter-spacing: .5px;
      text-transform: uppercase;
    }
    
  4. Previously, we floated our logo to the left within the <header> element. Now our tagline sits directly to the right of the logo; however, we’d like it to appear all the way to the right of the <header> element, flush right.

    We need to add the text-align property with a value of right to the <h3> element with the class attribute value of tagline to get the tagline to sit all the way to the right.

    When added to the existing margin property, our new styles for the <h3> element with the class attribute value of tagline will look like this:

    1
    2
    3
    4
    5
    .tagline {
      margin: 66px 0 22px 0;
      text-align: right;
    }
    
  5. We’d also like our navigation menus, both in the <header> and <footer> elements, to sit flush right. Because both the <header> and <footer> elements have child elements that are floated to the left, we can use the same approach as we did with our tagline.

    The floated elements within the <header> and <footer> elements are taken out of the normal flow of the page, and this causes other elements to wrap around them. In this specific case, our navigation menus are the elements wrapping around the floated elements.

    Because we’ll be sharing the same styles across both navigation menus, we’ll give them each the class of nav. Our <header> element will now look like this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <header class="container group">
    
      <h1 class="logo">...</h1>
    
      <h3 class="tagline">...</h3>
    
      <nav class="nav primary-nav">
        ...
      </nav>
    
    </header>
    

    And our <footer> element will now look like this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <footer class="primary-footer container group">
    
      <small>...</small>
    
      <nav class="nav">
        ...
      </nav>
    
    </footer>
    

    Let’s not forget, changes to our <header> and <footer> elements need to be made on every page.

  6. With the nav class in place on both navigation menus, let’s create a new section within our main.css file to add shared navigation styles. We’ll begin by adding the text-align property with a value of right to a nav class rule set. We’ll expand these styles later on, but this will serve as a great foundation.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    /*
      ========================================
      Navigation
      ========================================
    */
    
    .nav {
      text-align: right;
    }
    
  7. While we’re adding the text-align property to a few different elements, let’s also add the text-align property with a value of center to our hero class selector rule set. For reference, these styles, including our existing line-height and padding properties, are located within the home page section of our main.css file.
    1
    2
    3
    4
    5
    6
    .hero {
      line-height: 44px;
      padding: 22px 80px 66px 80px;
      text-align: center;
    }
    

Our Styles Conference now has some serious style. (Bad joke, sorry.) Seriously, though, all of our styles are coming along quite well, and our website is progressing.

Styles Conference website
Fig 6Our Styles Conference website is coming along quite well after adding a few text-based properties

Using Web-Safe Fonts

By default there are a few fonts that are pre-installed on every computer, tablet, smart-phone, or other web-browsing-capable device. Because they’ve been installed on every device, we can use these fonts freely within our websites, knowing that no matter what device is browsing our site, the font will render properly. These fonts have become known as “web-safe fonts.” There are only a handful of them, and the safest of the web-safe fonts are listed here:

  • Arial
  • Courier New, Courier
  • Garamond
  • Georgia
  • Lucida Sans, Lucida Grande, Lucida
  • Palatino Linotype
  • Tahoma
  • Times New Roman, Times
  • Trebuchet
  • Verdana

Embedding Web Fonts

We also have the ability to upload fonts to a server and include them on a website via the CSS @font-face at-rule. This capability has done wonders for online typography. Now, more than ever, typography is coming to life online.

Embedding our own web fonts looks a bit like the following CSS. First, we use the @font-face at-rule to identify our font’s name, via the font-family property, as well as the source of our font (the path to the font file containing our chosen font), via the src property. From there we are able to use this font by including its name within any font-family property value.

1
2
3
4
5
6
7
8
@font-face {
  font-family: "Lobster";
  src: local("Lobster"), url("lobster.woff") format("woff");
}
body {
  font-family: "Lobster", "Comic Sans", cursive;
}

Having the ability to embed any typeface on a website does not mean we legally have the authority to do so. Typefaces are works of art, and posting them on our server may allow others to easily steal them. The authority to use a typeface depends on the licensing we’ve been warranted.

Fortunately, the value of using new typefaces online has been recognized, and companies have begun developing ways to license and include new fonts on websites. Some of these companies, like Typekit and Fontdeck, work off a subscription model for licensing fonts, while others, like Google Fonts, license the fonts for free. Before uploading any fonts, let’s make sure we have permission to do so.

In Practice

To add a little character to our Styles Conference website, let’s try using a Google Font on our website.

  1. Let’s head over to the Google Fonts website and search for the font we’d like to use: Lato. Once we’ve found it, let’s proceed with adding it to our collection and following the steps on their website to use the font.

    When the time comes to choose which font weights we’d like to use, let’s make sure to select 300 and 400, as we’ve already been using those within our CSS. Let’s also add 100 to the collection for another variation, too.

    Google will give us an additional <link> element to include in the <head> element of all of our pages. We’ll place this new <link> element directly below our existing <link> element. The new element will include the proper style sheet reference to Google, which will take care of including a new CSS file with the proper @font-face at-rule necessary for us to use the Lato font.

    With the addition of the new <link> element, our <head> element will look like this:

    1
    2
    3
    4
    5
    6
    7
    8
    <head>
      <meta charset="utf-8">
      <title>Styles Conference</title>
      <link rel="stylesheet" href="assets/stylesheets/main.css">
      <link rel="stylesheet"
      href="http://fonts.googleapis.com/css?family=Lato:100,300,400">
    </head>
    
  2. Once we have added the new <link> element to all of our pages, we are ready to begin using the Lato font. We’ll do so by adding it to our primary font stack within the font property inside our <body> element styles.

    Let’s add Lato to the beginning of our font stack to make it "Lato", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif.

    Although Lato is a single word, because it is an embedded web font we’ll want to surround it with quotation marks within any CSS reference. Our new <body> element styles will look like this:

    1
    2
    3
    4
    5
    body {
      color: #888;
      font: 300 16px/22px "Lato", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
    }
    
  3. Lato should now be up and running, visible in all of our text across the Styles Conference website. Let’s take a closer look at our logo and update it a bit.

    Within our logo class selector rule set, we’ll begin by adding the font-weight property with a value of 100 to make the text fairly thin. We’ll also use the text-transform property with a value of uppercase to make all of the letters uppercase, as well as the letter-spacing property with a value of .5 pixels to add a tiny bit of space between each letter within the logo.

    Altogether the styles for our logo will look like this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    .logo {
      border-top: 4px solid #648880;
      float: left;
      font-size: 48px;
      font-weight: 100;
      letter-spacing: .5px;
      line-height: 44px;
      padding: 40px 0 22px 0;
      text-transform: uppercase;
    }
    
  4. Because we have a font-weight property value of 100 available, let’s also set the paragraph element within our hero section to that weight. We can use the existing selector to do so, and the new rule set will look like this:
    1
    2
    3
    4
    5
    .hero p {
      font-size: 24px;
      font-weight: 100;
    }
    

Our Styles Conference website has taken quite a few large steps this lesson, and the look and feel of our website is starting to really shine.

Styles Conference website
Fig 6Our Styles Conference home page after adding the Lato Google web font

Demo & Source Code

Below you may view the Styles Conference website in its current state, as well as download the source code for the website in its current state.

View the Styles Conference Website or Download the Source Code (Zip file)

Including Citations & Quotes

Writing online sometimes involves citing different sources or quotations. All of the different citation and quotation cases can be covered semantically in HTML using the <cite>, <q>, and <blockquote> elements. Because they are usually distinguished from regular text in appearance, we’ll discuss them here in the typography lesson.

Knowing when to use which element and attribute to properly mark up citations and quotes takes a bit of practice. In general, follow these rules:

  • <cite>: Used to reference a creative work, author, or resource
  • <q>: Used for short, inline quotations
  • <blockquote>: Used for longer external quotations

Citing a Creative Work

The <cite> inline element is used in HTML to specifically cite a creative work; the element must include either the title of the work, the author’s name, or a URL reference to the work. By default, content wrapped within the <cite> element will appear in italics within the browser.

For additional reference, it helps to include a hyperlink to the original source of the citation when relevant.

Here the book Steve Jobs, by Walter Isaacson, is referenced within the <cite> element. Inside the citation is also a hyperlink to the book.

1
2
<p>The book <cite><a href="http://www.amazon.com/Steve-Jobs-Walter-Isaacson/dp/1451648537">Steve Jobs</a></cite> is truly inspirational.</p>

Dialogue & Prose Quotation

Quite often, dialogue or prose is quoted inline, within other text. For this purpose, the <q> (or quote) inline element should be applied. The <q> element semantically indicates quoted dialogue or prose and shouldn’t be used for any other purposes.

By default, the browser will insert the proper quotation marks for us and will even change the quotation marks based on the language identified within the lang global attribute.

Here’s an example:

1
2
<p>Steve Jobs once said, <q>One home run is much better than two doubles.</q></p>

Dialogue & Prose Citation

An optional attribute to include on the <q> element is the cite attribute. The cite attribute acts as a citation reference to the quote in the form of a URL. This attribute doesn’t alter the appearance of the element; it simply adds value for screen readers and other devices. Because the attribute isn’t viewable within the browser, it’s also helpful to provide a hyperlink to this source next to the actual quotation.

Here’s an example:

1
2
<p><a href="http://www.businessweek.com/magazine/content/06_06/b3970001.htm">Steve Jobs</a> once said, <q cite="http://www.businessweek.com/magazine/content/06_06/b3970001.htm">One home run is much better than two doubles.</q></p>

External Quotation

To quote a large block of text that comes from an external source and spans several lines, we’ll use the <blockquote> element. The <blockquote> is a block-level element that may have other block-level elements nested inside it, including headings and paragraphs.

Here’s an example that uses the <blockquote> element:

1
2
3
4
<blockquote>
  <p>&#8220;In most people&#8217;s vocabularies, design is a veneer. It&#8217;s interior decorating. It&#8217;s the fabric of the curtains, of the sofa. But to me, nothing could be further from the meaning of design. Design is the fundamental soul of a human-made creation that ends up expressing itself in successive outer layers of the product.&#8221;</p>
</blockquote>

External Citation

Longer quotes used within the <blockquote> element will often include a citation. This citation may comprise both the cite attribute and the <cite> element.

The cite attribute can be included on the <blockquote> element—in the same way that it was used on the <q> element earlier—to provide a citation reference to the quote in the form of a URL. The <cite> element then can fall after the actual quote itself to specify the original source of the quote, if relevant.

The HTML here outlines an extended quote from Steve Jobs that originally appeared in Fortune magazine. The quotation is marked up using the <blockquote> element with a cite attribute to specify where the quote originally appeared. In the <blockquote> element, the <cite> element, along with an <a> element, provides an additional citation and reference for the quote that is visible to users.

1
2
3
4
5
<blockquote cite="http://money.cnn.com/magazines/fortune/fortune_archive/2000/01/24/272277/index.htm">
  <p>&#8220;In most people&#8217;s vocabularies, design is a veneer. It&#8217;s interior decorating. It&#8217;s the fabric of the curtains, of the sofa. But to me, nothing could be further from the meaning of design. Design is the fundamental soul of a human-made creation that ends up expressing itself in successive outer layers of the product.&#8221;</p>
  <p><cite>&#8212; Steve Jobs in <a href="http://money.cnn.com/ magazines/fortune/fortune_archive/2000/01/24/272277/index.htm"> Fortune Magazine</a></cite></p>
</blockquote>

Summary

Learning how to style text is exciting, as our content can begin to convey some emotion. We can also start to play around with the hierarchy of our content, making our website more legible and digestible.

To quickly recap, within this lesson we discussed the following:

  • Adding color to our text to enhance it
  • Applying font-based properties, including font-family, font-size, font-style, font-weight, and more
  • Applying text-based properties, including text-align, text-decoration, text-indent, text-shadow, and more
  • The history behind web-safe fonts and how to embed our own web fonts
  • How to properly mark up citations and quotations

Sharpening up our text and dabbling a bit with typography has brought our design along quite a way. Next, we’ll bring a little more color to our website by going over backgrounds and gradients.

Lesson 5 Positioning Content

Lesson 5

Positioning Content

One of the best things about CSS is that it gives us the ability to position content and elements on a page in nearly any imaginable way, bringing structure to our designs and helping make content more digestible.

There are a few different types of positioning within CSS, and each has its own application. In this chapter we’re going to take a look at a few different use cases—creating reusable layouts and uniquely positioning one-off elements—and describe a few ways to go about each.

Positioning with Floats

One way to position elements on a page is with the float property. The float property is pretty versatile and can be used in a number of different ways.

Essentially, the float property allows us to take an element, remove it from the normal flow of a page, and position it to the left or right of its parent element. All other elements on the page will then flow around the floated element. An <img> element floated to the side of a few paragraphs of text, for example, will allow the paragraphs to wrap around the image as necessary.

When the float property is used on multiple elements at the same time, it provides the ability to create a layout by floating elements directly next to or opposite each other, as seen in multiple-column layouts.

The float property accepts a few values; the two most popular values are left and right, which allow elements to be floated to the left or right of their parent element.

1
2
3
4
img {
  float: left;
}

Floats in Practice

Let’s create a common page layout with a header at the top, two columns in the center, and a footer at the bottom. Ideally this page would be marked up using the <header>, <section>, <aside>, and <footer> elements as discussed in Lesson 2, “Getting to Know HTML.” Inside the <body> element, the HTML may look like this:

1
2
3
4
5
<header>...</header>
<section>...</section>
<aside>...</aside>
<footer>...</footer>

Here the <section> and <aside> elements, as block-level elements, will be stacked on top of one another by default. However, we want these elements to sit side by side. By floating the <section> to the left and the <aside> to the right, we can position them as two columns sitting opposite one another. Our CSS should look like this:

1
2
3
4
5
6
7
section {
  float: left;
}
aside {
  float: right;
}

For reference, when an element is floated, it will float all the way to the edge of its parent element. If there isn’t a parent element, the floated element will then float all the way to the edge of the page.

When we float an element, we take it out of the normal flow of the HTML document. This causes the width of that element to default to the width of the content within it. Sometimes, such as when we’re creating columns for a reusable layout, this behavior is not desired. It can be corrected by adding a fixed width property value to each column. Additionally, to prevent floated elements from touching one another, causing the content of one to sit directly next to the content of the other, we can use the margin property to create space between elements.

Here, we are extending the previous code block, adding a margin and width to each column to better shape our desired outcome.

1
2
3
4
5
6
7
8
9
10
11
section {
  float: left;
  margin: 0 1.5%;
  width: 63%;
}
aside {
  float: right;
  margin: 0 1.5%;
  width: 30%;
}

Floats May Change an Element’s Display Value

When floating an element, it is also important to recognize that an element is removed from the normal flow of a page, and that may change an element’s default display value. The float property relies on an element having a display value of block, and may alter an element’s default display value if it is not already displayed as a block-level element.

For example, an element with a display value of inline, such as the <span> inline-level element, ignores any height or width property values. However, should that inline-level element be floated, its display value will be changed to block, and it may then accept height or width property values.

As we float elements we must keep an eye on how their display property values are affected.

With two columns we can float one column to the left and another to the right, but with more columns we must change our approach. Say, for example, we’d like to have a row of three columns between our <header> and <footer> elements. If we drop our <aside> element and use three <section> elements, our HTML might look like this:

1
2
3
4
5
6
<header>...</header>
<section>...</section>
<section>...</section>
<section>...</section>
<footer>...</footer>

To position these three <section> elements in a three-column row, instead of floating one column to the left and one column to the right, we’ll float all three <section> elements to the left. We’ll also need to adjust the width of the <section> elements to account for the additional columns and to get them to sit one next to the other.

1
2
3
4
5
6
section {
  float: left;
  margin: 0 1.5%;
  width: 30%;
}

Here we have three columns, all with equal width and margin values and all floated to the left.

Clearing & Containing Floats

The float property was originally designed to allow content to wrap around images. An image could be floated, and all of the content surrounding that image could then naturally flow around it. Although this works great for images, the float property was never actually intended to be used for layout and positioning purposes, and thus it comes with a few pitfalls.

One of those pitfalls is that occasionally the proper styles will not render on an element that it is sitting next to or is a parent element of a floated element. When an element is floated, it is taken out of the normal flow of the page, and, as a result, the styles of elements around that floated element can be negatively impacted.

Often margin and padding property values aren’t interpreted correctly, causing them to blend into the floated element; other properties can be affected, too.

Another pitfall is that sometimes unwanted content begins to wrap around a floated element. Removing an element from the flow of the document allows all the elements around the floated element to wrap and consume any available space around the floated element, which is often undesired.

With our previous two-column example, after we floated the <section> and <aside> elements, and before we set a width property value on either of them, the content within the <footer> element would have wrapped in between the two floated elements above it, filling in any available space. Consequently, the <footer> element would have sat in the gutter between the <section> and <aside> elements, consuming the available space.

To prevent content from wrapping around floated elements, we need to clear, or contain, those floats and return the page to its normal flow. We’ll proceed by looking at how to clear floats, and then we’ll take a look at how to contain floats.

Clearing Floats

Clearing floats is accomplished using the clear property, which accepts a few different values: the most commonly used values being left, right, and both.

1
2
3
4
div {
  clear: left;
}

The left value will clear left floats, while the right value will clear right floats. The both value, however, will clear both left and right floats and is often the most ideal value.

Going back to our previous example, if we use the clear property with the value of both on the <footer> element, we are able to clear the floats. It is important that this clear be applied to an element appearing after the floated elements, not before, to return the page to its normal flow.

1
2
3
4
footer {
  clear: both;
}

Containing Floats

Rather than clearing floats, another option is to contain the floats. The outcomes of containing floats versus those of clearing them are nearly the same; however, containing floats does help to ensure that all of our styles will be rendered properly.

To contain floats, the floated elements must reside within a parent element. The parent element will act as a container, leaving the flow of the document completely normal outside of it. The CSS for that parent element, represented by the group class below, is shown here:

1
2
3
4
5
6
7
8
9
10
11
12
13
.group:before,
.group:after {
  content: "";
  display: table;
}
.group:after {
  clear: both;
}
.group {
  clear: both;
  *zoom: 1;
}

There’s quite a bit going on here, but essentially what the CSS is doing is clearing any floated elements within the element with the class of group and returning the flow of the document back to normal.

More specifically, the :before and :after pseudo-elements, as mentioned in the Lesson 4 exercise, are dynamically generated elements above and below the element with the class of group. Those elements do not include any content and are displayed as table-level elements, much like block-level elements. The dynamically generated element after the element with the class of group is clearing the floats within the element with the class of group, much like the clear from before. And lastly, the element with the class of group itself also clears any floats that may appear above it, in case a left or right float may exist. It also includes a little trickery to get older browsers to play nicely.

It is more code than the clear: both; declaration alone, but it can prove to be quite useful.

Looking at our two-column page layout from before, we could wrap the <section> and <aside> elements with a parent element. That parent element then needs to contain the floats within itself. The code would look like this:

HTML
1
2
3
4
5
6
7
<header>...</header>
<div class="group">
  <section>...</section>
  <aside>...</aside>
</div>
<footer>...</footer>
CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
.group:before,
.group:after {
  content: "";
  display: table;
}
.group:after {
  clear: both;
}
.group {
  clear: both;
  *zoom: 1;
}
section {
  float: left;
  margin: 0 1.5%;
  width: 63%;
}
aside {
  float: right;
  margin: 0 1.5%;
  width: 30%;
}

The technique shown here for containing elements is know as a “clearfix” and can often be found in other websites with the class name of clearfix or cf. We’ve chosen to use the class name of group, though, as it is representing a group of elements, and better expresses the content.

As elements are floated, it is important to keep note of how they affect the flow of a page and to make sure the flow of a page is reset by either clearing or containing the floats as necessary. Failing to keep track of floats can cause quite a few headaches, especially as pages begin to have multiple rows of multiple columns.

In Practice

Let’s return to the Styles Conference website to try floating some content.

  1. First things first, before we begin floating any elements, let’s provide a way to contain those floats by adding the clearfix to our CSS. Within the main.css file, just below our grid styles, let’s add the clearfix under the class name group, just like before.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    /*
      ========================================
      Clearfix
      ========================================
    */
    .group:before,
    .group:after {
      content: "";
      display: table;
    }
    .group:after {
      clear: both;
    }
    .group {
      clear: both;
      *zoom: 1;
    }
    
  2. Now that we can contain floats, let’s float the primary <h1> within the <header> element to the left and allow all of the other content in the header to wrap to the right of it.

    To do this, let’s add a class of logo to the <h1> element. Then within our CSS, let’s add a new section of styles for the primary header. In this section we’ll select the <h1> element with the logo class and then float it to the left.

    HTML
    1
    2
    3
    4
    <h1 class="logo">
      <a href="index.html">Styles Conference</a>
    </h1>
    
    CSS
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    /*
      ========================================
      Primary header
      ========================================
    */
    
    .logo {
      float: left;
    }
    
  3. While we’re at it, let’s add a little more detail to our logo. We’ll begin by placing a <br> element, or line break, between the word “Styles” and the word “Conference” to force the text of our logo to sit on two lines.

    Within the CSS, let’s add a border to the top of our logo and some vertical padding to give the logo breathing room.

    HTML
    1
    2
    3
    4
    <h1 class="logo">
      <a href="index.html">Styles <br> Conference</a>
    </h1>
    
    CSS
    1
    2
    3
    4
    5
    6
    .logo {
      border-top: 4px solid #648880;
      padding: 40px 0 22px 0;
      float: left;
    }
    
  4. Because we floated the <h1> element, we’ll want to contain that float. The closest parent element of the <h1> element is the <header> element, so we’ll want to add the class of group to the <header> element. Doing this applies the clearfix styles we set up earlier to the <header> element.
    1
    2
    3
    4
    <header class="container group">
      ...
    </header>
    
  5. The <header> element is taking shape, so let’s take a look at the <footer> element. Much like we did with the <header> element, we’ll float our copyright to the left within the <small> element and let all other elements wrap around it to the right.

    Unlike the <header> element, though, we’re not going to use a class directly on the floated element. This time we’re going to apply a class to the parent of the floated element and use a unique CSS selector to select the element and then float it.

    Let’s start by adding the class of primary-footer to the <footer> element. Because we know we’ll be floating an element within the <footer> element, we should also add the class of group while we’re at it.

    1
    2
    3
    4
    <footer class="primary-footer container group">
      ...
    </footer>
    
  6. Now that the class of primary-footer is on the <footer> element, we can use that class to prequalify the <small> element with CSS. We’ll want to select and float the <small> element to the left. Let’s not forget to create a new section within our main.css file for these primary footer styles.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    /*
      ========================================
      Primary footer
      ========================================
    */
    
    .primary-footer small {
      float: left;
    }
    

    To review, here we are selecting the <small> element, which must reside within an element with the class attribute value of primary-footer, such as our <footer> element, for example.

  7. Lastly, let’s put some padding on the top and bottom of the <footer> element to help separate it a little more from the rest of the page. We can do this directly by using the primary-footer class with a class selector.
    1
    2
    3
    4
    5
    .primary-footer {
      padding-bottom: 44px;
      padding-top: 44px;
    }
    

With all of these changes to the <header> and <footer> elements, we have to be sure to make them on every page, not just the index.html page.

Styles Conference website
Fig 5With a few floats, the <header> and <footer> elements on our Styles Conference home page are coming together

Positioning with Inline-Block

In addition to using floats, another way we can position content is by using the display property in conjunction with the inline-block value. The inline-block method, as we’ll discuss, is primarily helpful for laying out pages or for placing elements next to one another within a line.

Recall that the inline-block value for the display property will display elements within a line while allowing them to accept all box model properties, including height, width, padding, border, and margin. Using inline-block elements allows us to take full advantage of the box model without having to worry about clearing any floats.

Inline-Block in Practice

Let’s take a look at our three-column example from before. We’ll start by keeping our HTML just as it is:

1
2
3
4
5
6
<header>...</header>
<section>...</section>
<section>...</section>
<section>...</section>
<footer>...</footer>

Now instead of floating our three <section> elements, we’ll change their display values to inline-block, leaving the margin and width properties from before alone. Our resulting CSS will look like this:

1
2
3
4
5
6
section {
  display: inline-block;
  margin: 0 1.5%;
  width: 30%;
}

Unfortunately, this code alone doesn’t quite do the trick, and the last <section> element is pushed to a new row. Remember, because inline-block elements are displayed on the same line as one another, they include a single space between them. When the size of each single space is added to the width and horizontal margin values of all the elements in the row, the total width becomes too great, pushing the last <section> element to a new row. In order to display all of the <section> elements on the same row, the white space between each <section> element must be removed.

Removing Spaces Between Inline-Block Elements

There are a number of ways to remove the space between inline-block elements, and some are more complex than others. We are going to focus on two of the easiest ways, both of which happen inside HTML.

The first solution is to put each new <section> element’s opening tag on the same line as the previous <section> element’s closing tag. Rather than using a new line for each element, we’ll end and begin elements on the same line. Our HTML could look like this:

1
2
3
4
5
6
7
8
9
10
<header>...</header>
<section>
  ...
</section><section>
  ...
</section><section>
  ...
</section>
<footer>...</footer>

Writing inline-block elements this way ensures that the space between inline-block elements within HTML doesn’t exist; consequently, the space will not appear when the page is rendered.

Another way to remove the white space between inline-block elements is to open an HTML comment directly after an inline-block element’s closing tag. Then, close the HTML com- ment immediately before the next inline-block element’s opening tag. Doing this allows inline-block elements to begin and end on separate lines of HTML and “comments out” any potential spaces between the elements. The resulting code would look like this:

1
2
3
4
5
6
7
8
9
10
11
12
<header>...</header>
<section>
  ...
</section><!--
--><section>
  ...
</section><!--
--><section>
  ...
 </section>
 <footer>...</footer>

Neither of these options is perfect, but they are helpful. I tend to favor using comments for better organization, but which option you choose is entirely up to you.

Creating Reusable Layouts

When building a website, it is always best to write modular styles that may be reused elsewhere, and reusable layouts are high on the list of reusable code. Layouts can be created using either floats or inline-block elements, but which works best and why?

Whether it’s better to use floats or inline-block elements to lay out the structure of a page is open to debate. My approach is to use inline-block elements to create the grid—or layout—of a page and to then use floats when I want content to wrap around a given element (as floats were intended to do with images). Generally, I also find inline-block elements easier to work with.

That said, use whatever works best for you. If you are comfortable with one approach over the other, then go for it.

Currently there are new CSS specifications in the works—specifically flex- and grid- based properties—that will help address how to best lay out pages. Keep an eye out for these methods as they begin to surface.

In Practice

With a solid understanding of reusable layouts, the time has come to implement one in our Styles Conference website.

  1. For the Styles Conference website, we’ll create a three-column reusable layout using inline-block elements. We’ll do so in a way that allows us to have three columns of equal width or two columns with the total width split between them, two-thirds in one and one-third in the other.

    To begin, we’ll create classes that define the width of these columns. The two classes we’ll create are col-1-3, for one-third, and col-2-3, for two-thirds. Within the grid section of our main.css file, let’s go ahead and define these classes and their corresponding widths.

    1
    2
    3
    4
    5
    6
    7
    .col-1-3 {
      width: 33.33%;
    }
    .col-2-3 {
      width: 66.66%;
    }
    
  2. We’ll want both of the columns to be displayed as inline-block elements. We’ll need to make sure that their vertical alignment is set to the top of each column, too.

    Let’s create two new selectors that will share the display and vertical-alignment property styles.

    1
    2
    3
    4
    5
    6
    .col-1-3,
    .col-2-3 {
      display: inline-block;
      vertical-align: top;
    }
    

    Looking at the CSS again, we’ve created two class selectors, col-1-3 and col-2-3, that are separated with a comma. The comma at the end of the first selector signifies that another selector is to follow. The second selector is followed by the opening curly bracket, {, which signifies that style declarations are to follow. By comma-separating the selectors, we can bind the same styles to multiple selectors at one time.

  3. We’ll want to put some space in between each of the columns to help break up the content. We can accomplish this by putting horizontal padding on each of the columns.

    This works well; however, when two columns are sitting next to one another, the width of the space between them will be double that of the space from the outside columns to the edge of the row. To balance this we’ll place all of our columns within a grid and add the same padding from our columns to that grid.

    Let’s use a class name of grid to identify our grid, and then let’s identify the same horizontal padding for our grid, col-1-3, and col-2-3 classes. With commas separating our selectors again, our CSS looks like this:

    1
    2
    3
    4
    5
    6
    7
    .grid,
    .col-1-3,
    .col-2-3 {
      padding-left: 15px;
      padding-right: 15px;
    }
    
  4. When we’re setting up the horizontal padding, we’ll need to be careful. Remember, in the last lesson we created a container element, known by the class of container, to center all of our content on a page within a 960-pixel-wide element. Currently if we were to put an element with the class of grid inside an element with the class of container, their horizontal paddings would add to one another, and our columns would not appear proportionate to the width of the rest of the page.

    We don’t want this to happen, so instead, we’ll have to share some of the styles from the container rule set with the grid rule set. Specifically, we’ll need to share the width property and values (to make sure our page stays fixed at 960 pixels wide) and the margin property and values (to center any element with the class of grid on the page).

    We’ll accomplish this by breaking up the old container rule set into the following:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    .container,
    .grid {
      margin: 0 auto;
      width: 960px;
    }
    .container {
      padding-left: 30px;
      padding-right: 30px;
    }
    

    Now any element with the class of container or grid will be 960 pixels wide and centered on the page. Additionally, we’ve preserved the existing horizontal padding for any element with the class of container by moving it into a new, separate rule set.

  5. All right—all of the heavy lifting needed to get our reusable grid styles into place is finished. Now it’s time to work in our HTML and to see how these classes perform.

    We’ll begin with the teasers on the home page, within our index.html file, aligning them into three columns. Currently, the teasers are wrapped in a <section> element with the class of container. We’ll want to change that class from container to grid so that we can begin placing columns within it.

    1
    2
    3
    4
    <section class="grid">
      ...
    </section>
    
  6. Next, we’ll want to add a class of col-1-3 to each of the <section> elements within the <section> element with the class of grid.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    <section class="grid">
    
      <section class="col-1-3">
        ...
      </section>
    
      <section class="col-1-3">
        ...
      </section>
      
      <section class="col-1-3">
        ...
      </section>
    
    </section>
    
  7. And lastly, because each of our columns is an inline-block element, we’ll want to make sure we remove the empty white space between them. We’ll use comments to do this, and we’ll add a little bit of documentation noting each upcoming section while we’re at it to better organize our code.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    <section class="grid">
      
      <!-- Speakers -->
      
      <section class="col-1-3">
        ...
      </section><!--
      
      Schedule
      
      --><section class="col-1-3">
        ...
      </section><!--
      
      Venue
      
      --><section class="col-1-3">
        ...
      </section>
    
    </section>
    

    To review, on line 3 we leave a comment identifying the “Speakers” section to follow. At the end of line 7, we open a comment immediately after the closing </section> tag. Within that comment, on line 9 we identify the “Schedule” section to come. We then close the comment at the beginning of line 11, just before the opening <section> tag. This same comment structure reappears on lines 13 through 17 between the two <section> elements, right before the “Venue” section. In all, we’ve commented out any potential white space between the columns while also using those comments to identify our sections.

We now have a reusable three-column grid that supports multiple arrangements, using both one-third- and two-thirds-width columns. Our home page now has three columns, breaking up all the different teasers.

Styles Conference website
Fig 5Our Styles Conference home page now includes a three-column layout

Demo & Source Code

Below you may view the Styles Conference website in its current state, as well as download the source code for the website in its current state.

View the Styles Conference Website or Download the Source Code (Zip file)

Uniquely Positioning Elements

Every now and then we’ll want to precisely position an element, but floats or inline-block elements won’t do the trick. Floats, which remove an element from the flow of a page, often produce unwanted results as surrounding elements flow around the floated element. Inline-block elements, unless we’re creating columns, can be fairly awkward to get into the proper position. For these situations we can use the position property in connection with box offset properties.

The position property identifies how an element is positioned on a page and whether or not it will appear within the normal flow of a document. This is used in conjunction with the box offset properties—top, right, bottom, and left—which identify exactly where an element will be positioned by moving elements in a number of different directions.

By default every element has a position value of static, which means that it exists in the normal flow of a document and it doesn’t accept any box offset properties. The static value is most commonly overwritten with a relative or absolute value, which we’ll examine next.

Relative Positioning

The relative value for the position property allows elements to appear within the normal flow a page, leaving space for an element as intended while not allowing other elements to flow around it; however, it also allows an element’s display position to be modified with the box offset properties. For example, consider the following HTML and CSS:

HTML
1
2
3
4
<div>...</div>
<div class="offset">...</div>
<div>...</div>
CSS
1
2
3
4
5
6
7
8
9
10
div {
  height: 100px;
  width: 100px;
}
.offset {
  left: 20px;
  position: relative;
  top: 20px;
}

Here the second <div> element, the element with the class of offset, has a position value of relative and two box offset properties, left and top. This preserves the original position of the element, and other elements are not allowed to move into this space. Additionally, the box offset properties reposition the element, pushing it 20 pixels from the left and 20 pixels from the top of its original location.

With relatively positioned elements, it’s important to know that the box offset properties identify where an element will be moved from given its original position. Thus, the left property with a value of 20 pixels will actually push the element towards the right, from the left, 20 pixels. The top property with a value of 20 pixels, then, will push an element towards the bottom, from the top, 20 pixels.

When we position the element using the box offset properties, the element overlaps the element below it rather than moving that element down as the margin or padding properties would.

Absolute Positioning

The absolute value for the position property is different from the relative value in that an element with a position value of absolute will not appear within the normal flow of a document, and the original space and position of the absolutely positioned element will not be preserved.

Additionally, absolutely positioned elements are moved in relation to their closest relatively positioned parent element. Should a relatively positioned parent element not exist, the absolutely positioned element will be positioned in relation to the <body> element. That’s quite a bit of information; let’s take a look at how this works inside some code:

HTML
1
2
3
4
<section>
  <div class="offset">...</div>
</section>
CSS
1
2
3
4
5
6
7
8
9
section {
  position: relative;
}
div {
  position: absolute;
  right: 20px;
  top: 20px;
}

Relative Positioning Demo

In this example the <section> element is relatively positioned but doesn’t include any box offset properties. Consequently its position doesn’t change. The <div> element with a class of offset includes a position value of absolute. Because the <section> element is the closest relatively positioned parent element to the <div> element, the <div> element will be positioned in relation to the <section> element.

With relatively positioned elements, the box offset properties identify in which direction an element would be moved in relation to itself. With absolutely positioned elements, the box offset properties identify in which direction an element will be moved in relation to its closest relatively positioned parent element.

As a result of the right and top box offset properties, the <div> element will appear 20 pixels from the right and 20 pixels from the top of the <section>.

Because the <div> element is absolutely positioned, it does not sit within the normal flow of the page and will overlap any surrounding elements. Additionally, the original position of the <div> is not preserved, and other elements are able to occupy that space.

Typically, most positioning can be handled without the use of the position property and box offset properties, but in certain cases they can be extremely helpful.

Summary

Learning how to position content within HTML and CSS is a huge step toward mastering the two languages. Add to this the box model, and we’re well on our way to becoming front-end developers.

To review, within this lesson we covered the following:

  • What floats are and how to use them to position content
  • How to clear and contain floated elements
  • How to position content with inline-block elements
  • How to remove the white space between inline-block elements
  • How to uniquely position content with relatively and absolutely positioned elements

We’re adding new skills with each lesson, so let’s keep going. Next up, typography!

Lesson 4 Opening the Box Model

 

Lesson 4

Opening the Box Model

We’ve familiarized ourselves with HTML and CSS; we know what they look like and how to accomplish some of the basics. Now we’re going to go a bit deeper and look at exactly how elements are displayed on a page and how they are sized.

In the process we’ll discuss what is known as the box model and how it works with HTML and CSS. We’re also going to look at a few new CSS properties and use some of the length values we covered in Lesson 3. Let’s begin.

How Are Elements Displayed?

Before jumping into the box model, it helps to understand how elements are displayed. In Lesson 2 we covered the difference between block-level and inline-level elements. To quickly recap, block-level elements occupy any available width, regardless of their content, and begin on a new line. Inline-level elements occupy only the width their content requires and line up on the same line, one after the other. Block-level elements are generally used for larger pieces of content, such as headings and structural elements. Inline-level elements are generally used for smaller pieces of content, such as a few words selected to be bold or italicized.

Display

Exactly how elements are displayed—as block-level elements, inline elements, or something else—is determined by the display property. Every element has a default display property value; however, as with all other property values, that value may be overwritten. There are quite a few values for the display property, but the most common are block, inline, inline-block, and none.

We can change an element’s display property value by selecting that element within CSS and declaring a new display property value. A value of block will make that element a block-level element.

1
2
3
4
p {
  display: block;
}

A value of inline will make that element an inline-level element.

1
2
3
4
p {
  display: inline;
}

Things get interesting with the inline-block value. Using this value will allow an element to behave as a block-level element, accepting all box model properties (which we’ll cover soon). However, the element will be displayed in line with other elements, and it will not begin on a new line by default.

1
2
3
4
p {
  display: inline-block;
}

The Space Between Inline-Block Elements

One important distinction with inline-block elements is that they are not always touching, or displayed directly against one another. Usually a small space will exist between two inline-block elements. This space, though perhaps annoying, is normal. We’ll discuss why this space exists and how to remove it in the next lesson.

Lastly, using a value of none will completely hide an element and render the page as if that element doesn’t exist. Any elements nested within this element will also be hidden.

1
2
3
4
div {
  display: none;
}

Knowing how elements are displayed and how to change their display is fairly important, as the display of an element has implications on how the box model is rendered. As we discuss the box model, we’ll be sure to look at these different implications and how they can affect the presentation of an element.

What Is the Box Model?

According to the box model concept, every element on a page is a rectangular box and may have width, height, padding, borders, and margins.

That’s worth repeating: Every element on a page is a rectangular box.

Outline of DOM Element Boxes
Fig 4When we look at each element individually, we can see how they are all rectangular, regardless of their presented shapes

Every element on every page conforms to the box model, so it’s incredibly important. Let’s take a look at it, along with a few new CSS properties, to better understand what we are working with.

Working with the Box Model

Every element is a rectangular box, and there are several properties that determine the size of that box. The core of the box is defined by the width and height of an element, which may be determined by the display property, by the contents of the element, or by specified width and height properties. padding and then border expand the dimensions of the box outward from the element’s width and height. Lastly, any margin we have specified will follow the border.

Each part of the box model corresponds to a CSS property: width, height, padding, border, and margin.

Let’s look these properties inside some code:

1
2
3
4
5
6
7
8
div {
  border: 6px solid #949599;
  height: 100px;
  margin: 20px;
  padding: 20px;
  width: 400px;
}

According to the box model, the total width of an element can be calculated using the following formula:

1
2
margin-right + border-right + padding-right + width + padding-left + border-left + margin-left

In comparison, according to the box model, the total height of an element can be calculated using the following formula:

1
2
margin-top + border-top + padding-top + height + padding-bottom + border-bottom + margin-bottom
The Box Model
Fig 4The box model broken down, including a base height and width plus paddings, borders, and margins

Using the formulas, we can find the total height and width of our example code.

  • Width: 492px = 20px + 6px + 20px + 400px + 20px + 6px + 20px
  • Height: 192px = 20px + 6px + 20px + 100px + 20px + 6px + 20px

The box model is without question one of the more confusing parts of HTML and CSS. We set a width property value of 400 pixels, but the actual width of our element is 492 pixels. By default the box model is additive; thus to determine the actual size of a box we need to take into account padding, borders, and margins for all four sides of the box. Our width not only includes the width property value, but also the size of the left and right padding, left and right borders, and left and right margins.

So far a lot of these properties might not make a whole lot of sense, and that’s all right. To clarify things, let’s take a close look at all of the properties—width, height, padding, border, and margin—that go into forming the box model.

Width & Height

Every element has default width and height. That width and height may be 0 pixels, but browsers, by default, will render every element with size. Depending on how an element is displayed, the default width and height may be adequate. If an element is key to the layout of a page, it may require specified width and height property values. In this case, the property values for non-inline elements may be specified.

Width

The default width of an element depends on its display value. Block-level elements have a default width of 100%, consuming the entire horizontal space available. Inline and inline-block elements expand and contract horizontally to accommodate their content. Inline-level elements cannot have a fixed size, thus the width and height properties are only relevant to non-inline elements. To set a specific width for a non-inline element, use the width property:

1
2
3
4
div {
  width: 400px;
}

Height

The default height of an element is determined by its content. An element will expand and contract vertically as necessary to accommodate its content. To set a specific height for a non-inline element, use the height property:

1
2
3
4
div {
  height: 100px;
}

Sizing Inline-Level Elements

Please keep in mind that inline-level elements will not accept the width and height properties or any values tied to them. Block and inline-block elements will, however, accept the width and height properties and their corresponding values.

Margin & Padding

Depending on the element, browsers may apply default margins and padding to an element to help with legibility and clarity. We will generally see this with text-based elements. The default margins and padding for these elements may differ from browser to browser and element to element. In Lesson 1 we discussed using a CSS reset to tone all of these default values down to zero. Doing so allows us to work from the ground up and to specify our own values.

Margin

The margin property allows us to set the amount of space that surrounds an element. Margins for an element fall outside of any border and are completely transparent in color. Margins can be used to help position elements in a particular place on a page or to provide breathing room, keeping all other elements a safe distance away. Here’s the margin property in action:

1
2
3
4
div {
  margin: 20px;
}

One oddity with the margin property is that vertical margins, top and bottom, are not accepted by inline-level elements. These vertical margins are, however, accepted by block-level and inline-block elements.

Padding

The padding property is very similar to the margin property; however, it falls inside of an element’s border, should an element have a border. The padding property is used to provide spacing directly within an element. Here’s the code:

1
2
3
4
div {
  padding: 20px;
}

The padding property, unlike the margin property, works vertically on inline-level elements. This vertical padding may blend into the line above or below the given element, but it will be displayed.

Margin & Padding on Inline-Level Elements

Inline-level elements are affected a bit differently than block and inline-block elements when it comes to margins and padding. Margins only work horizontally—left and right—on inline-level elements. Padding works on all four sides of inline-level elements; however, the vertical padding—the top and bottom—may bleed into the lines above and below an element.

Margins and padding work like normal for block and inline-block elements.

Margin & Padding Declarations

In CSS, there is more than one way to declare values for certain properties. We can use longhand, listing multiple properties and values one after the other, in which each value has its own property. Or we can use shorthand, listing multiple values with one property. Not all properties have a shorthand alternative, so we must make sure we are using the correct property and value structure.

The margin and padding properties come in both longhand and shorthand form. When using the shorthand margin property to set the same value for all four sides of an element, we specify one value:

1
2
3
4
div {
  margin: 20px;
}

To set one value for the top and bottom and another value for the left and right sides of an element, specify two values: top and bottom first, then left and right. Here we are placing margins of 10 pixels on the top and bottom of a <div> and margins of 20 pixels on the left and right:

1
2
3
4
div {
  margin: 10px 20px;
}

To set unique values for all four sides of an element, specify those values in the order of top, right, bottom, and left, moving clockwise. Here we are placing margins of 10 pixels on the top of a <div>, 20 pixels on the right, 0 pixels on the bottom, and 15 pixels on the left.

1
2
3
4
div {
  margin: 10px 20px 0 15px;
}

Using the margin or padding property alone, with any number of values, is considered shorthand. With longhand, we can set the value for one side at a time using unique properties. Each property name (in this case margin or padding) is followed by a dash and the side of the box to which the value is to be applied: top, right, bottom, or left. For example, the padding-left property accepts only one value and will set the left padding for that element; the margin-top property accepts only one value and will set the top margin for that element.

1
2
3
4
5
div {
  margin-top: 10px;
  padding-left: 6px;
}

When we wish to identify only one margin or padding value, it is best to use the longhand properties. Doing so keeps our code explicit and helps us to avoid any confusion down the road. For example, did we really want to set the top, right, and left sides of the element to have margins of 0 pixels, or did we really only want to set the bottom margin to 10 pixels? Using longhand properties and values here helps to make our intentions clear. When dealing with three or more values, though, shorthand is incredibly helpful.

Margin & Padding Colors

The margin and padding properties are completely transparent and do not accept any color values. Being transparent, though, they show the background colors of relative elements. For margins, we see the background color of the parent element, and for padding, we see the background color of the element the padding is applied to.

Borders

Borders fall between the padding and margin, providing an outline around an element. The border property requires three values: width, style, and color. Shorthand values for the border property are stated in that order—width, style, color. In longhand, these three values can be broken up into the border-width, border-style, and border-color properties. These longhand properties are useful for changing, or overwriting, a single border value.

The width and color of borders can be defined using common CSS units of length and color, as discussed in Lesson 3.

Borders can have different appearances. The most common style values are solid, double, dashed, dotted, and none, but there are several others to choose from.

Here is the code for a 6-pixel-wide, solid, gray border that wraps around all four sides of a <div>:

1
2
3
4
div {
  border: 6px solid #949599;
}

Individual Border Sides

As with the margin and padding properties, borders can be placed on one side of an element at a time if we’d like. Doing so requires new properties: border-top, border-right, border-bottom, and border-left. The values for these properties are the same as those of the border property alone: width, style, and color. If we want, we can make a border appear only on the bottom of an element:

1
2
3
4
div {
  border-bottom: 6px solid #949599;
}

Additionally, styles for individual border sides may be controlled at an even finer level. For example, if we wish to change only the width of the bottom border we can use the following code:

1
2
3
4
div {
  border-bottom-width: 12px;
}

These highly specific longhand border properties include a series of hyphen-separated words starting with the border base, followed by the selected side—top, right, bottom, or left—and then width, style, or color, depending on the desired property.

Border Radius

While we’re looking at borders and their different properties, we need to examine the border-radius property, which enables us to round the corners of an element.

The border-radius property accepts length units, including percentages and pixels, that identify the radius by which the corners of an element are to be rounded. A single value will round all four corners of an element equally; two values will round the top-left/bottom-right and top-right/bottom-left corners in that order; four values will round the top-left, top-right, bottom-right, and bottom-left corners in that order.

When considering the order in which multiple values are applied to the border-radius property (as well as the margin and padding properties), remember that they move in a clockwise fashion starting at the top left of an element.

1
2
3
4
div {
  border-radius: 5px;
}

The border-radius property may also be broken out into longhand properties that allow us to change the radii of individual corners of an element. These longhand properties begin with border, continue with the corner’s vertical location (top or bottom) and the corner’s horizontal location (left or right), and then end with radius. For example, to change the top-right corner radius of a <div>, the border-top-right-radius property can be used.

1
2
3
4
div {
  border-top-right-radius: 5px;
}

Box Sizing

Until now the box model has been an additive design. If you set the width of an element to 400 pixels and then add 20 pixels of padding and a border of 10 pixels on every side, the actual full width of the element becomes 460 pixels. Remember, we need to add the width, padding, and border property values together to get the actual, full width of an element.

The box model may, however, be changed to support different calculations. CSS3 introduced the box-sizing property, which allows us to change exactly how the box model works and how an element’s size is calculated. The property accepts three primary values—content-box, padding-box, and border-box—each of which has a slightly different impact on how the box size is calculated.

Content Box

The content-box value is the default value, leaving the box model as an additive design. If we don’t use the box-sizing property, this will be the default value for all elements. The size of an element begins with the width and height properties, and then any padding, border, or margin property values are added on from there.

1
2
3
4
5
6
div {
  -webkit-box-sizing: content-box;
     -moz-box-sizing: content-box;
          box-sizing: content-box;
}

Browser-Specific Properties & Values

What are all those hyphens and letters on the box-sizing property?

As CSS3 was introduced, browsers gradually began to support different properties and values, including the box-sizing property, by way of vendor prefixes. As parts of the CSS3 specification are finalized and new browser versions are released, these vendor prefixes become less and less relevant. As time goes on, vendor prefixes are unlikely to be a problem; however, they still provide support for some of the older browsers that leveraged them. We may run across them from time to time, and we may even want to use them should we wish to support older browsers.

Vendor prefixes may be seen on both properties and values, all depending on the CSS specification. Here they are shown on the box-sizing property. Browser vendors were free to chose when to use a prefix and when not to. Thus, some properties and values require vendor prefixes for certain browser vendors but not for others.

Moving forward, when a property or value needs a vendor prefix, the prefix will only be used in the introduction of that property or value (in the interest of keeping our code digestible and concise). Do not forget to add the necessary vendor prefixes when you’re actually writing the code.

For reference, the most common vendor prefixes are outlined here:

  • Mozilla Firefox: -moz-
  • Microsoft Internet Explorer: -ms-
  • Webkit (Google Chrome and Apple Safari): -webkit-

Padding Box

The padding-box value alters the box model by including any padding property values within the width and height of an element. When using the padding-box value, if an element has a width of 400 pixels and a padding of 20 pixels around every side, the actual width will remain 400 pixels. As any padding values increase, the content size within an element shrinks proportionately.

If we add a border or margin, those values will be added to the width or height properties to calculate the full box size. For example, if we add a border of 10 pixels and a padding of 20 pixels around every side of the element with a width of 400 pixels, the actual full width will become 420 pixels.

1
2
3
4
div {
  box-sizing: padding-box;
}

Border Box

Lastly, the border-box value alters the box model so that any border or padding property values are included within the width and height of an element. When using the border-box value, if an element has a width of 400 pixels, a padding of 20 pixels around every side, and a border of 10 pixels around every side, the actual width will remain 400 pixels.

If we add a margin, those values will need to be added to calculate the full box size. No matter which box-sizing property value is used, any margin values will need to be added to calculate the full size of the element.

1
2
3
4
div {
  box-sizing: border-box;
}
CSS3 Box Sizing
Fig 4Different box-sizing values allow the width of an element—and its box—to be calculated from different areas

Picking a Box Size

Generally speaking, the best box-sizing value to use is border-box. The border-box value makes our math much, much easier. If we want an element to be 400 pixels wide, it is, and it will remain 400 pixels wide no matter what padding or border values we add to it.

Additionally, we can easily mix length values. Say we want our box to be 40% wide. Adding a padding of 20 pixels and a border of 10 pixels around every side of an element isn’t difficult, and we can still guarantee that the actual width of our box will remain 40% despite using pixel values elsewhere.

The only drawback to using the box-sizing property is that as part of the CSS3 specification, it isn’t supported in every browser; it especially lacks support in older browsers. Fortunately this is becoming less and less relevant as new browsers are released. Chances are we’re safe to use the box-sizing property, but should we notice any issues, it’s worth looking into which browser those issues are occurring with.

Developer Tools

Most browsers have what are known as Developer Tools. These tools allow us to inspect an element on a page, see where that element lives within the HTML document, and see what CSS properties and values are being applied to it. Most of these tools also include a box model diagram to show the computed size of an element.

To see the Developer Tools in Google Chrome, click “View” within the menu bar and navigate to “Developer” and then “Developer Tools.” This loads a drawer at the bottom of the browser window that provides a handful of tools for inspecting our code.

Clicking the magnifying glass at the bottom of this drawer enables us to hover over and then click on different elements on the page to review more information about them.

After selecting an element, we’ll see a handful of tabs on the right-hand side of the Elements panel within our Developer Tools. Selecting the “Computed” tab will show us a breakdown of the box model for our selected element.

Play around with the Developer Tools, be it in Google Chrome, Mozilla Firefox, Apple Safari, or other browsers; there is much to learn from looking at our code. I generally leave the Developer Tools open at all times when writing HTML and CSS. And I frequently inspect the code of other websites to see how they are built, too.

Google Chrome Developer Tools
Fig 4The Google Chrome Developer Tools, which help us to inspect the HTML and CSS on any page

The box model is one of the most confusing parts of learning how to write HTML and CSS. It is also one of the most powerful parts of HTML and CSS, and once we have it mastered, most everything else—like positioning content—will come to us fairly easily.

In Practice

Let’s jump back into our Styles Conference website to center it on the page and add some more content.

  1. Let’s start by adjusting our box size to use the border-box version of the box model, which will make sizing all of our elements much easier. Within our main.css file, just below our reset, let’s add a comment to identify the code for what will become our grid and help determine the layout of our website. We’re putting this below our reset so that it falls in the proper position within the cascade.

    From there, we can use the universal selector, *, along with universal pseudo-elements, *:before and *:after, to select every imaginable element and change the box-sizing to border-box. Remember, we’re going to want to include the necessary vendor prefixes for the box-sizing property, as it is a relatively new property.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    /*
      ========================================
      Grid
      ========================================
    */
    
    *,
    *:before,
    *:after {
      -webkit-box-sizing: border-box;
         -moz-box-sizing: border-box;
              box-sizing: border-box;
    }
    
  2. Next we’ll want to create a class that will serve as a container for our elements. We can use this container class on different elements to set a common width, center the elements on the page, and apply some common horizontal padding.

    Just below our universal selector rule set, let’s create a selector with a class of container. Within this selector let’s set our width to 960 pixels, our left and right padding to 30 pixels, our top and bottom margins to 0, and our left and right margins to auto.

    Setting a width tells the browser definitively how wide any element with the class of container should be. Using a left and right margin of auto in conjunction with this width lets the browser automatically figure out equal left and right margins for the element, thus centering it on the page. Lastly, the left and right padding ensures that our content isn’t sitting directly on the edge of the element and provides a little breathing room for the content.

    1
    2
    3
    4
    5
    6
    7
    .container {
      margin: 0 auto;
      padding-left: 30px;
      padding-right: 30px;
      width: 960px;
    }
    
  3. Now that we have a container class available to use, let’s go ahead and apply the class of container throughout our HTML to the <header> and <footer> elements on each page, including the index.html, speakers.html, schedule.html, venue.html, and register.html files.
    1
    2
    3
    4
    <header class="container">...</header>
    
    <footer class="container">...</footer>
    
  4. While we’re at it, let’s go ahead and center the rest of the content on our pages. On the home page, our index.html file, let’s add the class of container to each <section> element on the page, one for our hero section (the section that introduces our conference) and one for our teasers section.
    1
    2
    <section class="container">...</section>
    

    Additionally, let’s wrap all of the <h1> elements on each page with a <section> element with the class of container.

    1
    2
    3
    4
    <section class="container">
      <h1>...</h1>
    </section>
    

    We’ll come back and adjust these elements and classes later, but for now we’re headed in the right direction.

  5. Now that all of our content is centered, let’s create some vertical spacing between elements. For starters let’s place a 22-pixel bottom margin on a few of our heading and paragraph elements. We’ll place and comment on these typography styles below our grid styles.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    /*
      ========================================
      Typography
      ========================================
    */
    
    h1, h3, h4, h5, p {
      margin-bottom: 22px;
    }
    

    We intentionally skipped <h2> and <h6> elements, as the design does not call for margins on <h2> elements and as we won’t be using any <h6> elements at this time.

  6. Let’s also try our hand at creating a border and some rounded corners. We’ll start by placing a button within the top <section> element on our home page, just below the header.

    Previously we added an <a> element within this <section> element. Let’s add the classes of btn and btn-alt to this anchor.

    1
    2
    <a class="btn btn-alt">...</a>
    

    Now let’s create some styles for those classes within our CSS. Below our typography rule set, let’s create a new section of the CSS file for buttons.

    To begin let’s add the btn class and apply some common styles that can be shared across all buttons. We’ll want all of our buttons to have a 5-pixel border-radius. They should be displayed as inline-block elements so we can add padding around all four sides without issue; we’ll remove any margin.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    /*
      ========================================
      Buttons
      ========================================
    */
    
    .btn {
      border-radius: 5px;
      display: inline-block;
      margin: 0;
    }
    

    We’ll also want to include styles specific to this button, which we’ll do by using the btn-alt class. Here we’ll add a 1-pixel, solid, gray border with 10 pixels of padding on the top and bottom of the button and 30 pixels of padding on the left and right of the button.

    1
    2
    3
    4
    5
    .btn-alt {
      border: 1px solid #dfe2e5;
      padding: 10px 30px;
    }
    

    Using both the btn and btn-alt classes on the same <a> element allows these styles to be layered on, rendering all of the styles on a single element.

  7. Because we’re working on the home page, let’s also add a bit of padding to the <section> element that contains our <a> element with the classes of btn and btn-alt. We’ll do so by adding a class attribute value of hero to the <section> element, alongside the container class attribute value, as this will be the leading section of our website.
    1
    2
    3
    4
    <section class="hero container">
      ...
    </section>
    

    Next we’ll want to create a new section within our CSS file for home page styles, and, once we’re ready, we’ll use the class of hero to apply padding around all four sides of the <section> element.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    /*
      ========================================
      Home
      ========================================
    */
    
    .hero {
      padding: 22px 80px 66px 80px;
    }
    

Our website is starting to come together, especially the home page.

Styles Conference website
Fig 4Our Styles Conference home page, taking shape after a few updates

Demo & Source Code

Below you may view the Styles Conference website in its current state, as well as download the source code for the website in its current state.

View the Styles Conference Website or Download the Source Code (Zip file)

The Universal Selector

In the first step of this exercise we were introduced to the universal selector. In CSS the asterisk, *, is the universal selector, which selects every element. Rather than listing every single element imaginable, we can use the asterisk as a catch-all to select all elements for us.

The :before and :after pseudo-elements also mentioned in this step are elements that can be dynamically generated with CSS. We’re not going to be using these elements within our project; however, when using the universal selector it’s a good practice to also include these pseudo-elements in case they should ever appear.

Summary

Take a second and pat yourself on the back. I’ll wait.

Learning all the different parts of the box model is no small feat. These concepts, although briefly introduced, take quite a bit of time to fully master, and we’re on the right path toward doing so.

In brief, within this lesson we talked about the following:

  • How different elements are displayed
  • What the box model is and why it’s important
  • How to change the size, including the height and width, of elements
  • How to add margin, padding, and borders to elements
  • How to change the box sizing of elements and the effects this has on the box model

Now that we have a better understanding of how elements are displayed and sized, it’s time to move into positioning these elements.

Lesson 3 : Getting to Know CSS

Lesson 3

Getting to Know CSS

It allows us to add layout and design to our pages, and it allows us to share those styles from element to element and page to page. Before we can unlock all of its features, though, there are a few aspects of the language we must fully understand.

First, it’s crucial to know exactly how styles are rendered. Specifically, we’ll need to know how different types of selectors work and how the order of those selectors can affect how our styles are rendered. We’ll also want to understand a few common property values that continually appear within CSS, particularly those that deal with color and length.

Let’s look under the hood of CSS to see exactly what is going on.

The Cascade

We’ll begin breaking down exactly how styles are rendered by looking at what is known as the cascade and studying a few examples of the cascade in action. Within CSS, all styles cascade from the top of a style sheet to the bottom, allowing different styles to be added or overwritten as the style sheet progresses.

For example, say we select all paragraph elements at the top of our style sheet and set their background color to orange and their font size to 24 pixels. Then towards the bottom of our style sheet, we select all paragraph elements again and set their background color to green, as seen here.

1
2
3
4
5
6
7
8
p {
  background: orange;
  font-size: 24px;
}
p {
  background: green;
}

Because the paragraph selector that sets the background color to green comes after the paragraph selector that sets the background color to orange, it will take precedence in the cascade. All of the paragraphs will appear with a green background. The font size will remain 24 pixels because the second paragraph selector didn’t identify a new font size.

Cascading Properties

The cascade also works with properties inside individual selectors. Again, for example, say we select all the paragraph elements and set their background color to orange. Then directly below the orange background property and value declaration, we add another property and value declaration setting the background color to green, as seen here.

1
2
3
4
5
p {
  background: orange;
  background: green;
}

Because the green background color declaration comes after the orange background color declaration, it will overrule the orange background, and, as before, our paragraphs will appear with a green background.

All styles will cascade from the top of our style sheet to the bottom of our style sheet. There are, however, times where the cascade doesn’t play so nicely. Those times occur when different types of selectors are used and the specificity of those selectors breaks the cascade. Let’s take a look.

Calculating Specificity

Every selector in CSS has a specificity weight. A selector’s specificity weight, along with its placement in the cascade, identifies how its styles will be rendered.

In Lesson 1, “Building Your First Web Page,” we talked about three different types of selectors: the type, class, and ID selectors. Each of these selectors has a different specificity weight.

The type selector has the lowest specificity weight and holds a point value of 0-0-1. The class selector has a medium specificity weight and holds a point value of 0-1-0. Lastly, the ID selector has a high specificity weight and holds a point value of 1-0-0. As we can see, specificity points are calculated using three columns. The first column counts ID selectors, the second column counts class selectors, and the third column counts type selectors.

What’s important to note here is that the ID selector has a higher specificity weight than the class selector, and the class selector has a higher specificity weight than the type selector.

Specificity Points

Specificity points are intentionally hyphenated, as their values are not computed from a base of 10. Class selectors do not hold a point value of 10, and ID selectors do not hold a point value of 100. Instead, these points should be read as 0-1-0 and 1-0-0 respectively. We’ll take a closer look at why these point values are hyphenated shortly, when we combine selectors.

The higher the specificity weight of a selector, the more superiority the selector is given when a styling conflict occurs. For example, if a paragraph element is selected using a type selector in one place and an ID selector in another, the ID selector will take precedence over the type selector regardless of where the ID selector appears in the cascade.

HTML
1
2
<p id="food">...</p>
CSS
1
2
3
4
5
6
7
#food {
  background: green;
}
p {
  background: orange;
}

Here we have a paragraph element with an id attribute value of food. Within our CSS, that paragraph is being selected by two different kinds of selectors: one type selector and one ID selector. Although the type selector comes after the ID selector in the cascade, the ID selector takes precedence over the type selector because it has a higher specificity weight; consequently the paragraph will appear with a green background.

The specificity weights of different types of selectors are incredibly important to remember. At times styles may not appear on elements as intended, and chances are the specificity weights of our selectors are breaking the cascade, therefore our styles are not appearing properly.

Understanding how the cascade and specificity work is a huge hurdle, and we’ll continue to cover this topic. For now, let’s look at how to be a little more particular and intentional with our selectors by combining them. Keep in mind that as we combine selectors, we’ll also be changing their specificity.

Combining Selectors

So far we’ve looked at how to use different types of selectors individually, but we also need to know how to use these selectors together. By combining selectors we can be more specific about which element or group of elements we’d like to select.

For example, say we want to select all paragraph elements that reside within an element with a class attribute value of hotdog and set their background color to brown. However, if one of those paragraphs happens to have the class attribute value of mustard, we want to set its background color to yellow. Our HTML and CSS may look like the following:

HTML
1
2
3
4
5
6
<div class="hotdog">
  <p>...</p>
  <p>...</p>
  <p class="mustard">...</p>
</div>
CSS
1
2
3
4
5
6
7
.hotdog p {
  background: brown;
}
.hotdog p.mustard {
  background: yellow;
}

When selectors are combined they should be read from right to left. The selector farthest to the right, directly before the opening curly bracket, is known as the key selector. The key selector identifies exactly which element the styles will be applied to. Any selector to the left of the key selector will serve as a prequalifier.

The first combined selector above, .hotdog p, includes two selectors: a class and a type selector. These two selectors are separated by a single space. The key selector is a type selector targeting paragraph elements. And because this type selector is prequalified with a class selector of hotdog, the full combined selector will only select paragraph elements that reside within an element with a class attribute value of hotdog.

The second selector above, .hotdog p.mustard, includes three selectors: two class selectors and one type selector. The only difference between the second selector and the first selector is the addition of the class selector of mustard to the end of the paragraph type selector. Because the new class selector, mustard, falls all the way to the right of the combined selector, it is the key selector, and all of the individual selectors coming before it are now prequalifiers.

Spaces Within Selectors

Within the previous combined selector, .hotdog p.mustard, there is a space between the hotdog class selector and the paragraph type selector but not between the paragraph type selector and the mustard class selector. The use, and omission, of spaces makes a large difference in selectors.

Since there isn’t a space between the paragraph type selector and the mustard class selector that means the selector will only select paragraph elements with the class of mustard. If the paragraph type selector was removed, and the mustard class selector had spaces on both sides of it, it would select any element with the class of mustard, not just paragraphs.

The best practice is to not prefix a class selector with a type selector. Generally we want to select any element with a given class, not just one type of element. And following this best practice, our new combined selector would be better as .hotdog .mustard.

Reading the combined selector from right to left, it is targeting paragraphs with a class attribute value of mustard that reside within an element with the class attribute value of hotdog.

Different types of selectors can be combined to target any given element on a page. As we continue to write different combined selectors, we’ll see their powers come to life. Before we do that, though, let’s take a look at how combining selectors changes a selector’s specificity weight.

Specificity Within Combined Selectors

When selectors are combined, so are the specificity weights of the individual selectors. These combined specificity weights can be calculated by counting each different type of selector within a combined selector.

Looking at our combined selectors from before, the first selector, .hotdog p, had both a class selector and a type selector. Knowing that the point value of a class selector is 0-1-0 and the point value of a type selector is 0-0-1, the total combined point value would be 0-1-1, found by adding up each kind of selector.

The second selector, .hotdog p.mustard, had two class selectors and one type selector. Combined, the selector has a specificity point value of 0-2-1. The 0 in the first column is for zero ID selectors, the 2 in the second column is for two class selectors, and the 1 in the last column is for one type selector.

Comparing the two selectors, the second selector, with its two classes, has a noticeably higher specificity weight and point value. As such it will take precedence within the cascade. If we were to flip the order of these selectors within our style sheet, placing the higher-weighted selector above the lower-weighted selector as shown here, the appearance of their styles would not be affected due to each selector’s specificity weight.

1
2
3
4
5
6
7
.hotdog p.mustard {
  background: yellow;
}
.hotdog p {
  background: brown;
}

In general we want to always keep an eye on the specificity weights of our selectors. The higher our specificity weights rise, the more likely our cascade is to break.

Layering Styles with Multiple Classes

One way to keep the specificity weights of our selectors low is to be as modular as possible, sharing similar styles from element to element. And one way to be as modular as possible is to layer on different styles by using multiple classes.

Elements within HTML can have more than one class attribute value so long as each value is space separated. With that, we can place certain styles on all elements of one sort while placing other styles only on specific elements of that sort.

We can tie styles we want to continually reuse to one class and layer on additional styles from another class.

Let’s take a look at buttons, for example. Say we want all of our buttons to have a font size of 16 pixels, but we want the background color of our buttons to vary depending on where the buttons are used. We can create a few classes and layer them on an element as necessary to apply the desired styles.

HTML
1
2
3
<a class="btn btn-danger">...</a>
<a class="btn btn-success">...</a>
CSS
1
2
3
4
5
6
7
8
9
10
.btn {
  font-size: 16px;
}
.btn-danger {
  background: red;
}
.btn-success {
  background: green;
}

Here you can see two anchor elements, both with multiple class attribute values. The first class, btn, is used to apply a font size of 16 pixels to each of the elements. Then, the first anchor element uses an additional class of btn-danger to apply a red background color while the second anchor element uses an additional class of btn-success to apply a green background color. Our styles here are clean and modular.

Using multiple classes, we can layer on as many styles as we wish, keeping our code lean and our specificity weights low. Much like understanding the cascade and calculating specificity, this is a practice that will take time to fully absorb, but we’ll get better with each lesson.

Common CSS Property Values

We’ve used a handful of common CSS property values already, such as the keyword color values of red and green. You may not have thought too much about them; that’s okay. We’re going to take time now to go over some previously used property values as well as to explore some of the more common property values that we’ll soon be using.

Specifically, we’ll look at property values that relate to colors and length measurements.

Colors

All color values within CSS are defined on an sRGB (or standard red, green, and blue) color space. Colors within this space are formed by mixing red, green, and blue color channels together, mirroring the way that televisions and monitors generate all the different colors they display. By mixing different levels of red, green, and blue, we can create millions of colors—and find nearly any color we’d like.

Currently there are four primary ways to represent sRGB colors within CSS: keywords, hexadecimal notation, and RGB and HSL values.

Keyword Colors

Keyword color values are names (such as red, green, or blue) that map to a given color. These keyword names and their corresponding colors are determined by the CSS specification. Most common colors, along with a few oddities, have keyword names.

A complete list of these keyword names can be found within the CSS specification.

Color Name Hex Values RGB Values HSL Values
black #000000 rgb(0, 0, 0) hsl(0, 0%, 0%)
silver #c0c0c0 rgb(192, 192, 192) hsl(0, 0%, 75%)
gray #808080 rgb(128, 128, 128) hsl(0, 0%, 50%)
white #ffffff rgb(255, 255, 255) hsl(0, 100%, 100%)
maroon #800000 rgb(128, 0, 0) hsl(0, 100%, 25%)
red #ff0000 rgb(255, 0, 0) hsl(0, 100%, 50%)
purple #800080 rgb(128, 0, 128) hsl(300, 100%, 25%)
fuchsia #ff00ff rgb(255, 0, 255) hsl(300, 100%, 50%)
green #008000 rgb(0, 128, 0) hsl(120, 100%, 25%)
olive #808000 rgb(0, 255, 0) hsl(120, 100%, 50%)
lime #00ff00 rgb(128, 128, 0) hsl(60, 100%, 25%)
yellow #ffff00 rgb(255, 255, 0) hsl(60, 100%, 50%)
navy #000080 rgb(0, 0, 128) hsl(240, 100%, 25%)
blue #0000ff rgb(0, 0, 255) hsl(240, 100%, 50%)
teal #008080 rgb(0, 128, 128) hsl(180, 100%, 25%)
aqua #00ffff rgb(0, 255, 255) hsl(180, 100%, 50%)

Here we are applying a maroon background to any element with the task class attribute value and a yellow background to any element with the count class attribute value.

1
2
3
4
5
6
7
.task {
  background: maroon;
}
.count {
  background: yellow;
}

While keyword color values are simple in nature, they provide limited options and thus are not the most popular color value choice.

Hexadecimal Colors

Hexadecimal color values consist of a pound, or hash, #, followed by a three- or six- character figure. The figures use the numbers 0 through 9 and the letters a through f, upper or lower case. These values map to the red, green, and blue color channels.

In six-character notation, the first two characters represent the red channel, the third and fourth characters represent the green channel, and the last two characters represent the blue channel. In three-character notation, the first character represents the red channel, the second character represents the green channel, and the last character represents the blue channel.

If in six-character notation the first two characters are a matching pair, the third and fourth characters are a matching pair, and the last two characters are a matching pair, the six-character figure may be shortened to a three-character figure. To do this the repeated character from each pair should be used once. For example, a shade of orange represented by the hexadecimal color #ff6600 could also be written as #f60.

Hexadecimal Color Syntax
Fig 3Six-character hexadecimal values may be written as three-character hexadecimal values when the red, green, and blue color channels each contain a repeating character

The character pairs are obtained by converting 0 through 255 into a base-16, or hexadecimal, format. The math is a little tricky—and worthy of its own book—but it helps to know that 0 equals black and f equals white.

The Millions of Hexadecimal Colors

There are millions of hexadecimal colors, over 16.7 million to be exact. Here’s how…

There are 16 options for every character in a hexadecimal color, 0 through 9 and a through f. With the characters grouped in pairs, there are 256 color options per pair (16 multiplied by 16, or 16 squared).

And with three groups of 256 color options we have a total of over 16.7 million colors (256 multiplied by 256 multiplied by 256, or 256 cubed).

To create the same maroon and yellow background colors from before, we could replace the keyword color values with hexadecimal color values, as seen here.

1
2
3
4
5
6
7
.task {
  background: #800000;
}
.count {
  background: #ff0;
}

Hexadecimal color values have been around for a while, and they have become fairly popular because they offer a large number of color options. They are, however, a little difficult to work with, especially if you’re not too familiar with them. Fortunately Adobe has created Adobe Kuler, a free application that provides a color wheel to help us find any color we want and its corresponding hexadecimal value.

Additionally, most image editing applications, such as Adobe Photoshop, provide the capability to locate hexadecimal color values.

Adobe Photoshop Color Picker
Fig 3The color picker tool within Adobe Photoshop displays the hexadecimal, RGB, and HSL color values

RGB & RGBa Colors

RGB color values are stated using the rgb() function, which stands for red, green, and blue. The function accepts three comma-separated values, each of which is an integer from 0 to 255. A value of 0 would be pure black; a value of 255 would be pure white.

As we might expect, the first value within the rgb() function represents the red channel, the second value represents the green channel, and the third value represents the blue channel.

If we were to recreate the shade of orange from before as an RGB color value, it would be represented as rgb(255, 102, 0).

Also, using the same maroon and yellow background colors from before, we could replace the keyword or hexadecimal color values with RGB color values.

1
2
3
4
5
6
7
.task {
  background: rgb(128, 0, 0);
}
.count {
  background: rgb(255, 255, 0);
}

RGB color values may also include an alpha, or transparency, channel by using the rgba() function. The rgba() function requires a fourth value, which must be a number between 0 and 1, including decimals. A value of 0 creates a fully transparent color, meaning it would be invisible, and a value of 1 creates a fully opaque color. Any decimal value in between 0 and 1 would create a semi-transparent color.

If we wanted our shade of orange to appear 50% opaque, we would use an RGBa color value of rgba(255, 102, 0, .5).

We can also change the opacity of our maroon and yellow background colors. The following code sets the maroon background color to 25% opaque and leaves the yellow background color 100% opaque.

1
2
3
4
5
6
7
.task {
  background: rgba(128, 0, 0, .25);
}
.count {
  background: rgba(255, 255, 0, 1);
}

RGB color values are becoming more popular, especially due to the ability to create semi-transparent colors using RGBa.

HSL & HSLa Colors

HSL color values are stated using the hsl() function, which stands for hue, saturation, and lightness. Within the parentheses, the function accepts three comma-separated values, much like rgb().

The first value, the hue, is a unitless number from 0 to 360. The numbers0through 360 represent the color wheel, and the value identifies the degree of a color on the color wheel.

The second and third values, the saturation and lightness, are percentage values from 0 to 100%. The saturation value identifies how saturated with color the hue is, with 0 being grayscale and 100% being fully saturated. The lightness identifies how dark or light the hue value is, with 0 being completely black and 100% being completely white.

Returning to our shade of orange, as an HSL color value it would be written as hsl(24, 100%, 50%).

Our maroon and yellow background colors can also be stated as HSL color values, as shown here.

1
2
3
4
5
6
7
.task {
  background: hsl(0, 100%, 25%);
}
.count {
  background: hsl(60, 100%, 50%);
}

HSL color values, like RGBa, may also include an alpha, or transparency, channel with the use of the hsla() function. The behavior of the alpha channel is just like that of the rgba() function. A fourth value between 0 and 1, including decimals, must be added to the function to identify the degree of opacity.

Our shade of orange as an HSLa color set to 50% opaque would be represented as hsla(24, 100%, 50%, .5).

The same 25% opaque maroon background color and 100% opaque yellow background color from before would look like the following as HSLa color values.

1
2
3
4
5
6
7
.task {
  background: hsla(0, 100%, 25%, .25);
}
.count {
  background: hsla(60, 100%, 50%, 1);
}

The HSL color value is the newest color value available within CSS. Due to its age and support within browsers, though, it isn’t as widely used as the other values.

For the time being, hexadecimal color values remain the most popular as they are widely supported; though when an alpha channel for transparency is needed, RGBa color values are preferred. These preferences may change in the future, but for now we’ll use hexadecimal and RGBa color values.

Lengths

Length values within CSS are similar to colors in that there are a handful of different types of values for length, all of which serve distinct purposes. Length values come in two different forms, absolute and relative, each of which uses different units of measurement.

We’re going to stick to the more common—and more straightforward—values at the moment, as more complex values will provide much more power than we need for now.

Absolute Lengths

Absolute length values are the simplest length values, as they are fixed to a physical measurement, such as inches, centimeters, or millimeters. The most popular absolute unit of measurement is known as the pixel and is represented by the px unit notation.

Pixels

The pixel is equal to 1/96th of an inch; thus there are 96 pixels in an inch. The exact measurement of a pixel, however, may vary slightly between high-density and low-density viewing devices.

Pixels have been around for quite some time and are commonly used with a handful of different properties. The code here is using pixels to set the font size of all paragraphs to 14 pixels.

1
2
3
4
p {
  font-size: 14px;
}

With the changing landscape of viewing devices and their varying screen sizes, pixels have lost some of their popularity. As an absolute unit of measurement, they don’t provide too much flexibility. Pixels are, however, trustworthy and great for getting started. We’re going to lean on them quite a bit as we’re learning the ropes of HTML and CSS.

Relative Lengths

In addition to absolute length values, there are also relative length values. Relative length values are a little more complicated, as they are not fixed units of measurement; they rely on the length of another measurement.

Percentages

Percentages, represented by the % unit notation, are one of the most popular relative values. Percentage lengths are defined in relation to the length of another object. For example, to set the width of an element to 50%, we have to know the width of its parent element, the element it is nested within, and then identify 50% of the parent element’s width.

1
2
3
4
.col {
  width: 50%;
}

Here we’ve set the width of the element with the class attribute value of col to 50%. That 50% will be calculated relative to the width of the element’s parent.

Percentages are extremely helpful for setting the height and width of elements and building out a web page’s layout. We’re going to rely on them often to help us out in these areas.

Em

The em unit is also a very popular relative value. The em unit is represented by the em unit notation, and its length is calculated based on an element’s font size.

A single em unit is equivalent to an element’s font size. So, for example, if an element has a font size of 14 pixels and a width set to 5em, the width would equal 70 pixels (14 pixels multiplied by 5).

1
2
3
4
5
.banner {
  font-size: 14px;
  width: 5em;
}

When a font size is not explicitly stated for an element, the em unit will be relative to the font size of the closest parent element with a stated font size.

The em unit is often used for styling text, including font sizes, as well as spacing around text, including margins and paddings. We’ll explore text a bit more in Lesson 6, “Working with Typography.”

There are a lot more absolute and relative units of measurement than those mentioned here. However, these three—pixels, percentages, and em units—are the most popular and the ones we’re going to primarily use.

Summary

Sadly our Styles Conference website lay dormant this lesson. We focused on the foundations of CSS, covering exactly how it works and some common values we’re sure to use.

To briefly recap, within this lesson we’ve discussed the following:

  • How style sheets cascade from the top to the bottom of a file
  • What specificity is and how we can calculate it
  • How to combine selectors to target specific elements or groups of elements
  • How to use multiple classes on a single element to layer on different styles for more modular code
  • The different color values available to use within CSS, including keyword, hexadecimal, RGB, and HSL values
  • The different length values available to use within CSS, including pixels, percentages, and em units

We still have a lot to cover, but the fundamentals are starting to fall into place. Within the next few lessons we’ll continue to dive in to CSS, and our website will really begin to take shape.

Learn jQuery – Day 6

AJAX

Nothing without  AJAX! jQuery offers a powerful package of  AJAX possibilities.
JQUERY.AJAX()
Main method for connection with AJAX. Parameters that forward can be:
URL
  The from where the request is sent. If you want a cross-domain request (request sent to a different domain), you have to enable that with  crossDomain parameters.
CROSSDOMAIN
It is used for sending requests on pages that are on different domains, using JSONPs request. Options are true and  false.
TYPE
Represents the type of data transfer (the same as in the HTML form). Can be GET and POST
DATA
Data that is passed to a given page. So basically, it is like you sending some data via HTML forms from some input element. Example: name = Peter & Year = 1980
DATATYPE
Determines the type of returned data.Supports: jsonxmlscript and html
ASYNC
Will the request be executed  synchronously or asynchronously. Possible options are true and false.
SUCCESS
With this parameter you forward some function that will be executed after the AJAX request is finished.
ERROR
Calls a certain function if there is an error in the request.
TIMEOUT
Time of  delay from the start of the execution of the request in milliseconds.
STATUSCODE
Executing given functions on certain HTTP conditions. For example, if the return status is 404 (the page doesn’t exist), a certain function is executed.
USERNAME
User name that will be forwarded in the case of  HTTP authentication.
PASSWORD
The password that will be forwarded in the case of  HTTP authentication.
1 /*as it is mentioned above,
2 it doesn’t matter if you are using $ or  jQuery object */
3
4  $.ajax({
5     url: “test.html”,
6     data: “ID=182&location=Chicago”,
7     type: “GET”,
8     async: false,
9     statusCode: {404: function() {
10         alert(‘Page is not found’);
11     },
12     error: function() {
13         alert(“error”);
14     },
15     success: function(){
16         $(this).addClass(“done”);
17     }
18 });
JQUERY.GET()
Loads the information from the server using  HTTP GET request  (shortened and purpose-specific version of jQuery.ajax () method). Accepts  4 parameters: url to the
page (mandatory), the info that is being sent with the request  (data),function for execution after the ajax request, and the dataType that defines how will the returned info look like.
1 $.get(“test.php”);
2
3 $.get(“test.php”, { name: “Peter”, age: “26” } );
4
5 $.get(
6     “test.php”,
7     { name: “Peter”, age: “26” },
8     function(){ alert(‘Over’)},
9     “json”
10 );
JQUERY.POST()
Same as  jQuery.get() method,but the type of request demands  HTTP POST
JQUERY.GETJSON()
Same as  jQuery.ajax() method that would return  JSON type of data. The parameters are: urldata and function for calling after the request is executed.
1 $.getJSON(“test.php”,
2     {name:”Peter”},
3     function() {
4         //code for execution
5     }
6 );
JQUERY.GETSCRIPT()
Loads the script from the server and executes it. The parameters are: url and callback function
1 $.getScript(‘ajax/test.js’, function() {
2     alert(‘Script is loaded.’);
3 });
.LOAD()
Loads information from the server and places them in a certain element. The parameters are: urldata and callback function
1 $(‘#my-div’).load(“page.html”,
2     function() {
3         //code for execution after finishing
4     }
5 );
.SERIALIZE()
Very useful function. Reads data from HTML form.
1 function takeData() {
2     return $(‘#my-forma’).serialize();
3 }
4
5 $(‘#button).click(
6     function(){
7         var data = takeData ();
8         alert(data);
9     }
10 );
The example will execute the takeData() function on the click of a button, that by the help of .serialize() loads the values from all elements in a form  (inputselecttextarea), and
places them in the variable  data. Then, those data will show up on the screen. The returned data will look like this, for example :name=Peter & surename=Willson & married=no

15 Top Resume Objectives Examples

Employers and recruiters review hundreds of resumes every day.
Therefore, writing a resume that stands out from the crowd is a key success factor for job seekers. An eye-catching resume will increase your chances of getting a job interview.
Writing a resume is challenging. You have to work hard on every phrase to effectively describe your achievements, skills, strengths and most importantly your resume objectives statement.

This article offers sample objectives for resumes and describes the importance of resume objectives with many examples.

What is a Good Objective for a Resume?

What is a resume objective statement and why is it so important?
The resume objectives statements are a short summary of your profile and your career goals and it is what employers are looking for.
In other words, the objectives are for the employers so they can evaluate your competencies. The resume objectives help them perceive whether you would suit the position.

Employers tend to search for phrases and basic qualities that fit the job position. That is why you may place the resume objective paragraph at the beginning.
You also want to be brief and to the point to increase the chances that your resume will be read and chosen/selected.

Your career summary may be part of the resume objectives paragraph, that is if you have years of professional experience.
Therefore, the resume objectives should be divided into two elements –
1. Your career summary (i.e. professional history)
2. Resume objectives: description of the job that you are seeking.

Important Note: The free Resume Samples section of the site contains many examples of career objectives and career profiles that you wouldn’t want to miss.

Let’s start with #2 – the resume objective statement examples.

Resume Objective Examples

Here are 15 objective statements that you can rewrite/edit and use for your resume:

1. “Obtain a position at ABC institute where I can maximize my training experience, program development skills and my teaching abilities.“

2. “Seeking a position that will benefit from my sales experience, positive interaction skills and industry contacts where my twelve years’ experience can improve the sales results.”

3. “Sales manager position where my skills and experience can be effectively utilized for increased profitability and product sales volume by developing a dynamic team.”

4. “Seeking a project management position with leadership responsibilities including problem solving, planning, organizing and managing budgets.”

5. “Seeking a position in an office environment, where there is a need for a variety of office management tasks including – computer knowledge, organizational abilities, business intelligence and database program use.”

6. “Obtain a position as a team-player in a people-oriented organization where I can maximize my customer-service experience in a challenging environment to achieve the corporate goals.”

7. “To obtain a position as a School Teacher that will utilize my strong dedication to children’s development and to their educational needs.”

8. “To obtain a position as an office Secretary in which my computer knowledge, and organizational abilities can be fully utilized.”

9. “To obtain a position as a software program designer in a challenging environment that utilizes team-work effort for researching, learning and developing new high-tech products. “

10. “Customer care representative position where my customer relations experience can be fully utilized to improve customer satisfaction and enhance the company brand name.”

11. “Create business strategies and develop existing customer sales, marketing tools and product launching.”

12. “To obtain a human resources management position where I can effectively utilize my expertise in employee relations and staff recruitment.”

13. “Product Marketing position that utilizes my marketing experience and enables me to make a positive contribution to the company.”

14. “To secure a position that will lead to a lasting working relationship in the field of accounting or bookkeeping.”

15. “To obtain a position that will enable me to use my strong organizational skills, educational background and ability to work well with people.”

Career Summary – Examples for Resume Objectives Paragraphs

Here are two examples for a career summary:
1. “As a fully qualified headteacher with 15 years of varied experience, there’s much I can offer to the education of our young children. I have more than 10 years of experience in mentoring and coaching teaching staff in ABC school. I’m confident that my passion for the teachers’ and children’s development, together with my skills and experience will enable me to make a significant difference at your school.”

2. “I am a PhD business management professional with more than 16 years of experience. I possess multiple skills covering many fields including – business development, organization management and marketing enhancement. I have been a managing director where I led a marketing division of 2000 marketing engineers across 3 countries. I have a long list of corporate achievements that I would be pleased to present.”

Lession 2 : Getting to Know HTML

Lesson 2

Getting to Know HTML

In order to start building websites, we need to learn a little about which HTML elements are best used to display different types of content. It’s also important to understand how elements are visually displayed on a web page, as well as what different elements mean semantically.

Using the proper element for the job goes a long way, and we’ll want to make well-informed decisions in the process.

Semantics Overview

So what exactly are semantics? Semantics within HTML is the practice of giving content on the page meaning and structure by using the proper element. Semantic code describes the value of content on a page, regardless of the style or appearance of that content. There are several benefits to using semantic elements, including enabling computers, screen readers, search engines, and other devices to adequately read and understand the content on a web page. Additionally, semantic HTML is easier to manage and work with, as it shows clearly what each piece of content is about.

Moving forward, as new elements are introduced, we’ll talk about what those elements actually mean and the type of content they best represent. Before we do that, though, let’s look at two elements—<div>s and <span>s—that actually don’t hold any semantic value. They exist for styling purposes only.

Identifying Divisions & Spans

Divisions, or <div>s, and <span>s are HTML elements that act as containers solely for styling purposes. As generic containers, they do not come with any overarching meaning or semantic value. Paragraphs are semantic in that content wrapped within a <p> element is known and understood as a paragraph. <div>s and <span>s do not hold any such meaning and are simply containers.

Block vs. Inline Elements

Most elements are either block- or inline-level elements. What’s the difference?

Block-level elements begin on a new line, stacking one on top of the other, and occupy any available width. Block-level elements may be nested inside one another and may wrap inline-level elements. We’ll most commonly see block-level elements used for larger pieces of content, such as paragraphs.

Inline-level elements do not begin on a new line. They fall into the normal flow of a document, lining up one after the other, and only maintain the width of their content. Inline-level elements may be nested inside one another; however, they cannot wrap block-level elements. We’ll usually see inline-level elements with smaller pieces of content, such as a few words.

Both <div>s and <span>s, however, are extremely valuable when building a website in that they give us the ability to apply targeted styles to a contained set of content.

A <div> is a block-level element that is commonly used to identify large groupings of content, and which helps to build a web page’s layout and design. A <span>, on the other hand, is an inline-level element commonly used to identify smaller groupings of text within a block-level element.

We’ll commonly see <div>s and <span>s with class or id attributes for styling purposes. Choosing a class or id attribute value, or name, requires a bit of care. We want to choose a value that refers to the content of an element, not necessarily the appearance of an element.

For example, if we have a <div> with an orange background that contains social media links, our first thought might be to give the <div> a class value of orange. What happens if that orange background is later changed to blue? Having a class value of orange no longer makes sense. A more sensible choice for a class value would be social, as it pertains to the contents of the <div>, not the style.

1
2
3
4
5
6
7
8
9
<!-- Division -->
<div class="social">
  <p>I may be found on...</p>
  <p>Additionally, I have a profile on...</p>
</div>

<!-- Span -->
<p>Soon we'll be <span class="tooltip">writing HTML</span> with the best of them.</p>

Comments within HTML & CSS

The previous code includes exclamation points within the HTML, and that’s all right. Those are not elements, those are comments.

HTML and CSS give us the ability to leave comments within our code, and any content wrapped within a comment will not be displayed on the web page. Comments help keep our files organized, allow us to set reminders, and provide a way for us to more effectively manage our code. Comments become especially useful when there are multiple people working on the same files.

HTML comments start with <!-- and end with -->. CSS comments start with /* and end with */.

Using Text-Based Elements

Many different forms of media and content exist online; however, text is predominant. Accordingly, there are a number of different elements for displaying text on a web page. For now we’ll focus on the more popular elements, including headings, paragraphs, bold text to show importance, and italics for emphasis. Later, within Lesson 6, “Working with Typography,” we’ll take a closer look at how to style text.

Headings

Headings are block-level elements, and they come in six different rankings, <h1> through <h6>. Headings help to quickly break up content and establish hierarchy, and they are key identifiers for users reading a page. They also help search engines to index and determine the content on a page.

Headings should be used in an order that is relevant to the content of a page. The primary heading of a page or section should be marked up with an <h1> element, and subsequent headings should use <h2>, <h3>, <h4>, <h5>, and <h6> elements as necessary.

Each heading level should be used where it is semantically valued, and should not be used to make text bold or big—there are other, better ways to do that.

Here is an example of HTML for all the different heading levels and the resulting display on a web page.

1
2
3
4
5
6
7
<h1>Heading Level 1</h1>
<h2>Heading Level 2</h2>
<h3>Heading Level 3</h3>
<h4>Heading Level 4</h4>
<h5>Heading Level 5</h5>
<h6>Heading Level 6</h6>

Paragraphs

Headings are often followed by supporting paragraphs. Paragraphs are defined using the <p> block-level element. Paragraphs can appear one after the other, adding information to a page as desired. Here is example of how to set up paragraphs.

1
2
3
4
<p>Steve Jobs was a co-founder and longtime chief executive officer at Apple. On June 12, 2005, Steve gave the commencement address at Stanford University.</p>

<p>In his address Steve urged graduates to follow their dreams and, despite any setbacks, to never give up&ndash;advice which he sincerely took to heart.</p>

Bold Text with Strong

To make text bold and place a strong importance on it, we’ll use the <strong> inline-level element. There are two elements that will bold text for us: the <strong> and <b> elements. It is important to understand the semantic difference between the two.

The <strong> element is semantically used to give strong importance to text, and is thus the most popular option for bolding text. The <b> element, on the other hand, semantically means to stylistically offset text, which isn’t always the best choice for text deserving prominent attention. We have to gauge the significance of the text we wish to set as bold and to choose an element accordingly.

Here are the two HTML options for creating bold text in action:

1
2
3
4
5
6
<!-- Strong importance -->
<p><strong>Caution:</strong> Falling rocks.</p>

<!-- Stylistically offset -->
<p>This recipe calls for <b>bacon</b> and <b>baconnaise</b>.</p>

Italicize Text with Emphasis

To italicize text, thereby placing emphasis on it, we’ll use the <em> inline-level element. As with the elements for bold text, there are two different elements that will italicize text, each with a slightly different semantic meaning.

The <em> element is used semantically to place a stressed emphasis on text; it is thus the most popular option for italicizing text. The other option, the <i> element, is used semantically to convey text in an alternative voice or tone, almost as if it were placed in quotation marks. Again, we will need to gauge the significance of the text we want to italicize and choose an element accordingly.

Here’s the HTML code for italicizing:

1
2
3
4
5
6
<!-- Stressed emphasis -->
<p>I <em>love</em> Chicago!</p>

<!-- Alternative voice or tone -->
<p>The name <i>Shay</i> means a gift.</p>

These text-level elements are quite handy for bringing our content to life. In addition to these, there are structurally based elements. Whereas text-based elements identify headings and paragraphs, structural elements identify groupings of content such as headers, articles, footers, and so forth. Let’s take a look.

Building Structure

For the longest time the structure of a web page was built using divisions. The problem was that divisions provide no semantic value, and it was fairly difficult to determine the intention of these divisions. Fortunately HTML5 introduced new structurally based elements, including the <header>, <nav>, <article>, <section>, <aside>, and <footer> elements.

All of these new elements are intended to give meaning to the organization of our pages and improve our structural semantics. They are all block-level elements and do not have any implied position or style. Additionally, all of these elements may be used multiple times per page, so long as each use reflects the proper semantic meaning.

Let’s roll up our sleeves and take a closer look.

Building Structure

Fig 2One possible example of HTML5 structural elements giving meaning to the organization of our pages

Header

The <header> element, like it sounds, is used to identify the top of a page, article, section, or other segment of a page. In general, the <header> element may include a heading, introductory text, and even navigation.

1
2
<header>...</header>

<header> vs. <head> vs. <h1> through <h6> Elements

It is easy to confuse the <header> element with the <head> element or the heading elements, <h1> through <h6>. They all have different semantic meanings and should be used according to their meanings. For reference…

The <header> element is a structural element that outlines the heading of a segment of a page. It falls within the <body> element.

The <head> element is not displayed on a page and is used to outline metadata, including the document title, and links to external files. It falls directly within the <html> element.

Heading elements, <h1> through <h6>, are used to designate multiple levels of text headings throughout a page.

Navigation

The <nav> element identifies a section of major navigational links on a page. The <nav> element should be reserved for primary navigation sections only, such as global navigation, a table of contents, previous/next links, or other noteworthy groups of navigational links.

Most commonly, links included within the <nav> element will link to other pages within the same website or to parts of the same web page. Miscellaneous one-off links should not be wrapped within the <nav> element; they should use the anchor element, <a>, and the anchor element alone.

1
2
<nav>...</nav>

Article

The <article> element is used to identify a section of independent, self-contained content that may be independently distributed or reused. We’ll often use the <article> element to mark up blog posts, newspaper articles, user-submitted content, and the like.

When deciding whether to use the <article> element, we must determine if the content within the element could be replicated elsewhere without any confusion. If the content within the <article> element were removed from the context of the page and placed, for example, within an email or printed work, that content should still make sense.

1
2
<article>...</article>

Section

The <section> element is used to identify a thematic grouping of content, which generally, but not always, includes a heading. The grouping of content within the <section> element may be generic in nature, but it’s useful to identify all of the content as related.

The <section> element is commonly used to break up and provide hierarchy to a page.

1
2
<section>...</section>

Deciding Between <article>, <section>, or <div> Elements

At times it becomes fairly difficult to decide which element—<article>, <section>, or <div>—is the best element for the job based on its semantic meaning. The trick here, as with every semantic decision, is to look at the content.

Both the <article> and <section> elements contribute to a document’s structure and help to outline a document. If the content is being grouped solely for styling purposes and doesn’t provide value to the outline of a document, use the <div> element.

If the content adds to the document outline and it can be independently redistributed or syndicated, use the <article> element.

If the content adds to the document outline and represents a thematic group of content, use the <section> element.

Aside

The <aside> element holds content, such as sidebars, inserts, or brief explanations, that is tangentially related to the content surrounding it. When used within an <article> element, for example, the <aside> element may identify content related to the author of the article.

We may instinctively think of an <aside> element as an element that appears off to the left or right side of a page. We have to remember, though, that all of the structural elements, including the <aside> element, are block-level elements and as such will appear on a new line, occupying the full available width of the page or of the element they are nested within, also known as their parent element.

1
2
<aside>...</aside>

We’ll discuss how to change the position of an element, perhaps placing it to the right or left of a group of content, in Lesson 5, “Positioning Content.”

Footer

The <footer> element identifies the closing or end of a page, article, section, or other segment of a page. Generally the <footer> element is found at the bottom of its parent. Content within the <footer> element should be relative information and should not diverge from the document or section it is included within.

1
2
<footer>...</footer>

With structural elements and text-based elements under our belts, our HTML knowledge is really starting to come together. Now is a good time to revisit our Styles Conference website and see if we can provide it with a little better structure.

In Practice

Currently, our Styles Conference website lacks real structure—and content for that matter. Let’s take some time to flesh out our home page a bit.

  1. Using our existing index.html file, let’s add in a <header> element. Our <header> element should include our existing <h1> element; let’s also add an <h3> element as a tagline to support our <h1> element.
    1
    2
    3
    4
    5
    <header>
      <h1>Styles Conference</h1>
      <h3>August 24&ndash;26th &mdash; Chicago, IL</h3>
    </header>
    
  2. After our <header> element, let’s add a new group of content, using the <section> element, that introduces our conference. We’ll begin this section with a new <h2> element and end it with our existing paragraph.
    1
    2
    3
    4
    5
    <section>
      <h2>Dedicated to the Craft of Building Websites</h2>
      <p>Every year the brightest web designers and front-end developers descend on Chicago to discuss the latest technologies. Join us this August!</p>
    </section>
    
  3. Following the introduction to our conference, let’s add another group of content that teases a few of the pages we’ll be adding, specifically the Speakers, Schedule, and Venue pages. Each of the pages we’re teasing should also reside within its own section and include supporting text.We’ll group all of the teasers inside a <section> element, and each individual teaser will be wrapped within a <section> element as well. In all, we’ll have three <section> elements inside another <section> element, which is all right.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <section>
    
      <section>
        <h5>Speakers</h5>
        <h3>World-Class Speakers</h3>
        <p>Joining us from all around the world are over twenty fantastic speakers, here to share their stories.</p>
      </section>
    
      ...
    
    </section>
    
  4. Lastly, let’s add our copyright within the <footer> element at the end of our page. To do so let’s use the <small> element, which semantically represents side comments and small print—perfect for our copyright.Generally, content within the <small> element will be rendered as, well, small, but our CSS reset will prevent that from happening.
    1
    2
    3
    4
    <footer>
      <small>&copy; Styles Conference</small>
    </footer>
    

Now we can see our home page beginning to come to life.

Styles Conference website

Fig 2Our home page after adding more content and structure

Encoding Special Characters

The <h3> element within our <header> element, as well as the <small> element within our <footer> element, has some interesting things going on. Specifically, a few special characters within these elements are being encoded.

Special characters include various punctuation marks, accented letters, and symbols. When typed directly into HTML, they can be misunderstood or mistaken for the wrong character; thus they need to be encoded.

Each encoded character will begin with an ampersand, &, and end with a semicolon, ;. What falls between the ampersand and semicolon is a character’s unique encoding, be it a name or numeric encoding.

For example, we would encode the word “resumé” as resum&eacute;. Within our header we have encoded both en and em dashes, and within our footer we have encoded the copyright symbol. For reference, a long list of character encodings may be found at Copy Paste Character.

With our home page taking shape, let’s take a look at creating hyperlinks so that we may add additional pages and build out the rest of our website.

Along with text, one of the core components of the Internet is the hyperlink, which provides the ability to link from one web page or resource to another. Hyperlinks are established using the anchor, <a>, inline-level element. In order to create a link from one page (or resource) to another, the href attribute, known as a hyperlink reference, is required. The href attribute value identifies the destination of the link.

For example, clicking the text “Shay,” which is wrapped inside the anchor element with the href attribute value of http://shayhowe.com, will take users to my website.

1
2
<a href="http://shayhowe.com">Shay</a>

Wrapping Block-Level Elements with Anchors

By nature the anchor element, <a>, is an inline element, and, according to web standards, inline-level elements may not wrap block-level elements. With the introduction of HTML5, however, anchor elements specifically have permission to wrap either block-, inline-, or any other level elements. This is a break from the standard convention, but it’s permissible in order to enable entire blocks of content on a page to become links.

Relative & Absolute Paths

The two most common types of links are links to other pages of the same website and links to other websites. These links are identified by their href attribute values, also known as their paths.

Links pointing to other pages of the same website will have a relative path, which does not include the domain (.com, .org, .edu, etc.) in the href attribute value. Because the link is pointing to another page on the same website, the href attribute value needs to include only the filename of the page being linked to: about.html, for example.

Should the page being linked to reside within a different directory, or folder, the href attribute value needs to reflect this as well. Say the about.html page resides within the pages directory; the relative path would then be pages/about.html.

Linking to other websites outside of the current one requires an absolute path, where the href attribute value must include the full domain. A link to Google would need the href attribute value of http://google.com, starting with http and including the domain, .com in this case.

Here clicking on the text “About” will open the about.html page inside our browser. Clicking the text “Google,” on the other hand, will open http://google.com/ within our browser.

1
2
3
4
5
6
<!-- Relative Path -->
<a href="/about.html">About</a>

<!-- Absolute Path -->
<a href="http://www.google.com/">Google</a>

Linking to an Email Address

Occasionally we may want to create a hyperlink to our email address—for example, hyperlink text that says “Email Me,” which when clicked opens a user’s default email client and pre-populates part of an email. At a minimum the email address to which the email is being sent is populated; other information such as a subject line and body text may also be included.

To create an email link, the href attribute value needs to start with mailto: followed by the email address to which the email should be sent. To create an email link to shay@awesome.com, for example, the href attribute value would be mailto:shay@awesome.com.

Additionally, subject, body text, and other information for the email may be populated. To add a subject line, we’ll include the subject= parameter after the email address. The first parameter following the email address must begin with a question mark, ?, to bind it to the hyperlink path. Multiple words within a subject line require that spaces be encoded using %20.

Adding body text works in the same way as adding the subject, this time using the body= parameter in the href attribute value. Because we are binding one parameter to another we need to use the ampersand, &, to separate the two. As with the subject, spaces must be encoded using %20, and line breaks must be encoded using %0A.

Altogether, a link to shay@awesome.com with the subject of “Reaching Out” and body text of “How are you” would require an href attribute value of mailto:shay@awesome.com?subject=Reaching%20Out&body=How%20are%20you.

Here’s the full breakdown:

1
2
<a href="mailto:shay@awesome.com?subject=Reaching%20Out&body=How%20are%20you">Email Me</a>

Opening Links in a New Window

One feature available with hyperlinks is the ability to determine where a link opens when clicked. Typically, links open in the same window from which they are clicked; however, links may also be opened in new windows.

To trigger the action of opening a link in a new window, use the target attribute with a value of _blank. The target attribute determines exactly where the link will be displayed, and the _blank value specifies a new window.

To open http://shayhowe.com/ in a new window, the code would look like this:

1
2
<a href="http://shayhowe.com/" target="_blank">Shay Howe</a>

Linking to Parts of the Same Page

Periodically we’ll see hyperlinks that link to part of the same page the link appears on. A common example of these same-page links are “Back to top” links that return a user to the top of a page.

We can create an on-page link by first setting an id attribute on the element we wish to link to, then using the value of that id attribute within an anchor element’s href attribute.

Using the “Back to top” link as an example, we can place an id attribute value of top on the <body> element. Now we can create an anchor element with an href attribute value of #top, pound sign and all, to link to the beginning of the <body> element.

Our code for this same-page link would look like the following:

1
2
3
4
5
6
<body id="top">
  ...
  <a href="#top">Back to top</a>
  ...
</body>

Hyperlinks are incredibly useful and have revolutionized how we use the Internet. So far we’ve covered how to link to other pages or websites, as well as how to create email links and links to parts of the same page. Before we go any further, let’s create some links of our own.

In Practice

It’s time to take Styles Conference from a single-page website to a full-blown website with multiple pages, all of which will be linked together using hyperlinks.

  1. We’ll begin by making our “Styles Conference” text inside the <h1> element within our <header> element link to the index.html page.Because we are already on the index.html page, this may seem a little odd—and rightfully so—but as the header is replicated on other pages, linking back to the home page will make sense.
    1
    2
    3
    4
    <h1>
      <a href="index.html">Styles Conference</a>
    </h1>
    
  2. In order to navigate across all of the different pages, we’re going add in a navigation menu, using the <nav> element, within our <header> element. We’ll be creating Speakers, Schedule, Venue, and Register pages to go with our home page, so we should create links for all of them.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <header>
    
      ...
    
      <nav>
        <a href="index.html">Home</a>
        <a href="speakers.html">Speakers</a>
        <a href="schedule.html">Schedule</a>
        <a href="venue.html">Venue</a>
        <a href="register.html">Register</a>
      </nav>
    
    </header>
    
  3. Let’s also add the same navigation menu from our <header> element to our <footer> element for convenience.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <footer>
    
      ...
    
      <nav>
        <a href="index.html">Home</a>
        <a href="speakers.html">Speakers</a>
        <a href="schedule.html">Schedule</a>
        <a href="venue.html">Venue</a>
        <a href="register.html">Register</a>
      </nav>
    
    </footer>
    
  4. Within the <section> element that introduces our conference, just below our header, we should also include a link to register for the conference. Placing a link below the paragraph will work perfectly.
    1
    2
    3
    4
    5
    6
    7
    8
    <section>
    
      ...
    
      <a href="register.html">Register Now</a>
    
    </section>
    
  5. We can’t forget to add links to all of the sections teasing our other pages. Inside each section, let’s wrap both the <h3> and <h5> elements within an anchor element linking to the proper page.We’ll want to make sure we do this for every section accordingly.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <section>
    
      <section>
        <a href="speakers.html">
          <h5>Speakers</h5>
          <h3>World-Class Speakers</h3>
        </a>
        <p>Joining us from all around the world are over twenty fantastic speakers, here to share their stories.</p>
      </section>
    
      ...
    
    </section>
    
  6. Now we need to create a handful of new pages. Let’s create speakers.html, schedule.html, venue.html, and register.html files. These files should live within the same folder as the index.html file, and, because we’re keeping them inside the same folder, all of our links should work as expected.To ensure that all of our pages look the same, let’s make sure that all of these new files have the same document structure and <header> and <footer> elements as the index.html file.

It’s official, we’re no longer working with a single page but indeed a full website.

Styles Conference website

Fig 2Our home page after all of the different links and navigation have been added

Demo & Source Code

Below you may view the Styles Conference website in its current state, as well as download the source code for the website in its current state.

View the Styles Conference Website or Download the Source Code (Zip file)

Summary

Semantics, as discussed within this lesson, are essential for providing our HTML with structure and meaning. Moving forward we’ll periodically introduce new elements, all of which will come with their own semantic meaning. It is the meaning of all of these elements that will provide our content with the most value.

Once again, in this lesson we covered the following:

  • What semantics are and why they are important
  • <div>s and <spans>s, and the difference between block- and inline-level elements
  • Which text-based elements best represent the content of a page
  • The HTML5 structural elements and how to define the structure and organization of our content and page
  • How to use hyperlinks to navigate between web pages or websites

Hopefully you’re starting to feel pretty good about HTML. There is still quite a bit to learn, but the foundation is in place. Next up, we’ll take a deeper look into CSS.

Learn jQuery – Day 5

CSS

Here we don’t have to explain the purpose in detail. These methods are used to manage CSS element values.
.CSS()
Returns or sets the value of any CSS property in the element
1 // Returns the value
2 $(‘p’).css(‘color’);
3
4 // sets the value
5 $(‘p’).css(‘color’, ‘#FFE’);

 

.HEIGHT()
Returns or sets the height of the element
1 // Returns the height
2 $(‘#mydiv’).height();
3
4 // sets the height
5 $(‘#mydiv’).height(200);
The difference between getting height by using  .height() method and by using .css(‘height’) is that the .css() method returns the value with the unit of measure  (450px),while  .height() returns only a numerical value.
.INNERHEIGHT()
Returns the height of the element including padding (if it is set)
.OUTERHEIGHT()
Returns the height of the element including (if  there are any) margins, borders and padding
.WIDTH(), .INNERWIDTH(), .OUTERWIDTH()
Does the same as the height methods, only it returns the width of the element.
.OFFSET()
Returns or sets the coordinates of the element compared to the position in the document  (top and left)
1 // first we have to assign an offset element to a string
2 var offset = $(‘#mydiv’).offset();
3 // then through him return the top and left coordinates
4 offset.left;
5 offset.top;
6
7 // sets the top and left coordinates
8 $(‘#mydiv’).offset({top:200, left:30});
.POSITION()
Returns the coordinates of the element compared to the position in the parent element (top i left)
1 /* like in offset first we the element position to a string
2 and then read the coordinates from him */
3 var pos = $(‘#mydiv’).position();
4 pos.left;
5 pos.top;

Effects

jQuery has a few techniques for animating content on a web page. These include simple, standard animations that are often used, but also sophisticated effects custom for your needs.
.ANIMATE()
Executes an animation over one or multiple given CSS values. As the first value it takes given CSS values, as the  second it takes the speed of execution measured in milliseconds, the third value is optional and can represent the way of the animation execution,and  the fourth represents the callback function that will be triggered after the execution of the animation.
1 $(‘#someElement’).animate(
2     {width : 100, opacity : 0.5},
3     500,
4     ‘linear’,
5     function() { $(this).after(‘Animation complete.’); }
6 );
.FADEIN()
Animates the transparency of an element from any of the values that on 1 (short for using  .animate() method just  for  opacity value)
1 $(‘#someElement’).fadeIn(500, function(){
2     // function for executing after the animation is finished
3 });
.FADEOUT()
Opposite of  .fadeIn(),animates the transparency of the element on  0
1 $(‘#someElement’).fadeOut();
.FADETO()
Opposite of  .fadeIn(), animates the transparency of the element on 0. As the first value it takes the duration of the animation in milliseconds, as the second value the desired visibility of the element. And the third method is optional and represents the callback function.
1 $(‘#someElement’).fadeTo(1000, 0,5, function() {
2      // function for executing after the animation is done
3 });
.FADETOGGLE()
A combination of .fadeIn() and  .fadeOut(),animates the transparency of the element from 0 to 1 and reverse. It takes the speed of execution, the effect of the animation and the callback function as values.
1 $(‘#someElement’).fadeToggle(1000, function() {
2      // function for executing after the animation is done
3 });
.SHOW()
Reveals a hidden element with simultaneous transparency animation, and also width and height animation of the element.
1 $(‘#someElement’).show(1000, function() {
2      // function for executing after the animation is done
3 });
.HIDE()
Opposite of .show() method, hides the element with simultaneous animation of the transparency, width and height.
1 $(‘#someElement’).hide(1000, function() {
2      // function for executing after the animation is done
3 });
.TOGGLE()
A combination of .show() and  .hide() methods, reveals or hides the element with simultaneous animation of the transparency width and height of the element..
1 $(‘#someElement’).toggle(1000, function() {
2      // function for executing after the animation is done
3 });
.SLIDEDOWN()
Reveals the hidden element by increasing it’s height.
1 $(‘#someElement’).slideDown(1000, function() {
2      // function for executing after the animation is done
3 });
.SLIDEUP()
Opposite to  .slideDown(), hides the element by decreasing it’s height.
1 $(‘#someElement’).slideUp(1000, function() {
2      // function for executing after the animation is done
3 });

.SLIDETOGGLE()

A combination of .slideDown() and .slideUp() methods, hides or reveales the element by animating it’s height.
1 $(‘#someElement’).slideToggle(1000, function() {
2      // function for executing after the animation is done
3 });

.STOP()

Stops any animation of the element that is currently happening
1 $(‘#someElement’).stop();

Everything here is free, and we hope you like our work and tutorials. If you do, feel free that you link to this tutorial on your website, blog or anywhere else where do you think is appropriate. Let knowledge be available to all.

Read next tutorial tomorrow.

Other jquery tutorials you may like :

Learn jQuery – Day 5

Learn jQuery – Day 4

Learn jQuery – Day 3

Learn jQuery – Day 2

Learn jQuery – Day 1

What Are HTML & CSS?

HTML, HyperText Markup Language, gives content structure and meaning by defining that content as, for example, headings, paragraphs, or images. CSS, or Cascading Style Sheets, is a presentation language created to style the appearance of content—using, for example, fonts or colors.

The two languages—HTML and CSS—are independent of one another and should remain that way. CSS should not be written inside of an HTML document and vice versa. As a rule, HTML will always represent content, and CSS will always represent the appearance of that content.

With this understanding of the difference between HTML and CSS, let’s dive into HTML in more detail.

Understanding Common HTML Terms

While getting started with HTML, you will likely encounter new—and often strange—terms. Over time you will become more and more familiar with all of them, but the three common HTML terms you should begin with are elements, tags, and attributes.

Elements

Elements are designators that define the structure and content of objects within a page. Some of the more frequently used elements include multiple levels of headings (identified as <h1> through <h6> elements) and paragraphs (identified as the <p> element); the list goes on to include the <a>, <div>, <span>, <strong>, and <em> elements, and many more.

Elements are identified by the use of less-than and greater-than angle brackets, < >, surrounding the element name. Thus, an element will look like the following:

1
2
<a>

Tags

The use of less-than and greater-than angle brackets surrounding an element creates what is known as a tag. Tags most commonly occur in pairs of opening and closing tags.

An opening tag marks the beginning of an element. It consists of a less-than sign followed by an element’s name, and then ends with a greater-than sign; for example, <div>.

A closing tag marks the end of an element. It consists of a less-than sign followed by a forward slash and the element’s name, and then ends with a greater-than sign; for example, </div>.

The content that falls between the opening and closing tags is the content of that element. An anchor link, for example, will have an opening tag of <a> and a closing tag of </a>. What falls between these two tags will be the content of the anchor link.

So, anchor tags will look a bit like this:

1
2
<a>...</a>

Attributes

Attributes are properties used to provide additional information about an element. The most common attributes include the id attribute, which identifies an element; the class attribute, which classifies an element; the src attribute, which specifies a source for embeddable content; and the href attribute, which provides a hyperlink reference to a linked resource.

Attributes are defined within the opening tag, after an element’s name. Generally attributes include a name and a value. The format for these attributes consists of the attribute name followed by an equals sign and then a quoted attribute value. For example, an <a> element including an href attribute would look like the following:

1
2
<a href="http://shayhowe.com/">Shay Howe</a>

Common HTML Terms Demo

The preceding code will display the text “Shay Howe” on the web page and will take users to http://shayhowe.com/ upon clicking the “Shay Howe” text. The anchor element is declared with the opening <a> and closing </a> tags encompassing the text, and the hyperlink reference attribute and value are declared with href="http://shayhowe.com" in the opening tag.

HTML Syntax Outline
Fig 1HTML syntax outline including an element, attribute, and tag

Now that you know what HTML elements, tags, and attributes are, let’s take a look at putting together our first web page. If anything looks new here, no worries—we’ll decipher it as we go.

Setting Up the HTML Document Structure

HTML documents are plain text documents saved with an .html file extension rather than a .txt file extension. To begin writing HTML, you first need a plain text editor that you are comfortable using. Sadly this does not include Microsoft Word or Pages, as those are rich text editors. Two of the more popular plain text editors for writing HTML and CSS are Dreamweaver and Sublime Text. Free alternatives also include Notepad++ for Windows and TextWrangler for Mac.

All HTML documents have a required structure that includes the following declaration and elements: <!DOCTYPE html>, <html>, <head>, and <body>.

The document type declaration, or <!DOCTYPE html>, informs web browsers which version of HTML is being used and is placed at the very beginning of the HTML document. Because we’ll be using the latest version of HTML, our document type declaration is simply <!DOCTYPE html>. Following the document type declaration, the <html> element signifies the beginning of the document.

Inside the <html> element, the <head> element identifies the top of the document, including any metadata (accompanying information about the page). The content inside the <head> element is not displayed on the web page itself. Instead, it may include the document title (which is displayed on the title bar in the browser window), links to any external files, or any other beneficial metadata.

All of the visible content within the web page will fall within the <body> element. A breakdown of a typical HTML document structure looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Hello World</title>
  </head>
  <body>
    <h1>Hello World</h1>
    <p>This is a web page.</p>
  </body>
</html>

HTML Document Structure Demo

The preceding code shows the document beginning with the document type declaration, <!DOCTYPE html>, followed directly by the <html> element. Inside the <html> element come the <head> and <body> elements. The <head> element includes the character encoding of the page via the <meta charset="utf-8"> tag and the title of the document via the <title> element. The <body> element includes a heading via the <h1> element and a paragraph via the <p> element. Because both the heading and paragraph are nested within the <body> element, they are visible on the web page.

When an element is placed inside of another element, also known as nested, it is a good idea to indent that element to keep the document structure well organized and legible. In the previous code, both the <head> and <body> elements were nested—and indented—inside the <html> element. The pattern of indenting for elements continues as new elements are added inside the <head> and <body> elements.

Self-Closing Elements

In the previous example, the <meta> element had only one tag and didn’t include a closing tag. Fear not, this was intentional. Not all elements consist of opening and closing tags. Some elements simply receive their content or behavior from attributes within a single tag. The <meta> element is one of these elements. The content of the previous <meta> element is assigned with the use of the charset attribute and value. Other common selfclosing elements include

  • <br>
  • <embed>
  • <hr>
  • <img>
  • <input>
  • <link>
  • <meta>
  • <param>
  • <source>
  • <wbr>

The structure outlined here, making use of the <!DOCTYPE html> document type and <html>, <head>, and <body> elements, is quite common. We’ll want to keep this document structure handy, as we’ll be using it often as we create new HTML documents.

Code Validation

No matter how careful we are when writing our code, we will inevitably make mistakes. Thankfully, when writing HTML and CSS we have validators to check our work. The W3C has built both HTML and CSS validators that will scan code for mistakes. Validating our code not only helps it render properly across all browsers, but also helps teach us the best practices for writing code.

In Practice

As web designers and front-end developers, we have the luxury of attending a number of great conferences dedicated to our craft. We’re going to make up our own conference, Styles Conference, and build a website for it throughout the following lessons. Here we go!

  1. Let’s open our text editor, create a new file named index.html, and save it to a location we won’t forget. I’m going to create a folder on my Desktop named “styles- conference” and save this file there; feel free to do the same.
  2. Within the index.html file, let’s add the document structure, including the <!DOCTYPE html> document type and the <html>, <head>, and <body> elements.
    1
    2
    3
    4
    5
    6
    7
    8
    <!DOCTYPE html>
    <html lang="en">
      <head>
      </head>
      <body>
      </body>
    </html>
    
  3. Inside the <head> element, let’s add <meta> and <title> elements. The <meta> element should include the proper charset attribute and value, while the <title> element should contain the title of the page—let’s say “Styles Conference.”
    1
    2
    3
    4
    5
    <head>
      <meta charset="utf-8">
      <title>Styles Conference</title>
    </head>
    
  4. Inside the <body> element, let’s add <h1> and <p> elements. The <h1> element should include the heading we wish to include—let’s use “Styles Conference” again—and the <p> element should include a simple paragraph to introduce our conference.
    1
    2
    3
    4
    5
    <body>
      <h1>Styles Conference</h1>
      <p>Every year the brightest web designers and front-end developers descend on Chicago to discuss the latest technologies. Join us this August!</p>
    </body>
    
  5. Now it’s time to see how we’ve done! Let’s go find our index.html file (mine is within the “styles-conference” folder on my Desktop). Double-clicking this file or dragging it into a web browser will open it for us to review.
Styles Conference website
Fig 1Our first steps into building our Styles Conference website

Let’s switch gears a bit, moving away from HTML, and take a look at CSS. Remember, HTML will define the content and structure of our web pages, while CSS will define the visual style and appearance of our web pages.

Understanding Common CSS Terms

In addition to HTML terms, there are a few common CSS terms you will want to familiarize yourself with. These terms include selectors, properties, and values. As with the HTML terminology, the more you work with CSS, the more these terms will become second nature.

Selectors

As elements are added to a web page, they may be styled using CSS. A selector designates exactly which element or elements within our HTML to target and apply styles (such as color, size, and position) to. Selectors may include a combination of different qualifiers to select unique elements, all depending on how specific we wish to be. For example, we may want to select every paragraph on a page, or we may want to select only one specific paragraph on a page.

Selectors generally target an attribute value, such as an id or class value, or target the type of element, such as <h1> or <p>.

Within CSS, selectors are followed with curly brackets, {}, which encompass the styles to be applied to the selected element. The selector here is targeting all <p> elements.

1
2
p { ... }

Properties

Once an element is selected, a property determines the styles that will be applied to that element. Property names fall after a selector, within the curly brackets, {}, and immediately preceding a colon, :. There are numerous properties we can use, such as background, color, font-size, height, and width, and new properties are often added. In the following code, we are defining the color and font-size properties to be applied to all <p> elements.

1
2
3
4
5
p {
  color: ...;
  font-size: ...;
}

Values

So far we’ve selected an element with a selector and determined what style we’d like to apply with a property. Now we can determine the behavior of that property with a value. Values can be identified as the text between the colon, :, and semicolon, ;. Here we are selecting all <p> elements and setting the value of the color property to be orange and the value of the font-size property to be 16 pixels.

1
2
3
4
5
p {
  color: orange;
  font-size: 16px;
}

To review, in CSS our rule set begins with the selector, which is immediately followed by curly brackets. Within these curly brackets are declarations consisting of property and value pairs. Each declaration begins with a property, which is followed by a colon, the property value, and finally a semicolon.

It is a common practice to indent property and value pairs within the curly brackets. As with HTML, these indentations help keep our code organized and legible.

CSS Syntax Outline
Fig 1CSS syntax outline including a selector, properties, and values

Knowing a few common terms and the general syntax of CSS is a great start, but we have a few more items to learn before jumping in too deep. Specifically, we need to take a closer look at how selectors work within CSS.

Working with Selectors

Selectors, as previously mentioned, indicate which HTML elements are being styled. It is important to fully understand how to use selectors and how they can be leveraged. The first step is to become familiar with the different types of selectors. We’ll start with the most common selectors: type, class, and ID selectors.

Type Selectors

Type selectors target elements by their element type. For example, should we wish to target all division elements, <div>, we would use a type selector of div. The following code shows a type selector for division elements as well as the corresponding HTML it selects.

CSS
1
2
div { ... }
HTML
1
2
3
<div>...</div>          
<div>...</div>

Class Selectors

Class selectors allow us to select an element based on the element’s class attribute value. Class selectors are a little more specific than type selectors, as they select a particular group of elements rather than all elements of one type.

Class selectors allow us to apply the same styles to different elements at once by using the same class attribute value across multiple elements.

Within CSS, classes are denoted by a leading period, ., followed by the class attribute value. Here the class selector will select any element containing the class attribute value of awesome, including both division and paragraph elements.

CSS
1
2
.awesome { ... }
HTML
1
2
3
<div class="awesome">...</div>
<p class="awesome">...</p>

ID Selectors

ID selectors are even more precise than class selectors, as they target only one unique element at a time. Just as class selectors use an element’s class attribute value as the selector, ID selectors use an element’s id attribute value as a selector.

Regardless of which type of element they appear on, id attribute values can only be used once per page. If used they should be reserved for significant elements.

Within CSS, ID selectors are denoted by a leading hash sign, #, followed by the id attribute value. Here the ID selector will only select the element containing the id attribute value of shayhowe.

CSS
1
2
#shayhowe { ... }
HTML
1
2
<div id="shayhowe">...</div>

Additional Selectors

Selectors are extremely powerful, and the selectors outlined here are the most common selectors we’ll come across. These selectors are also only the beginning. Many more advanced selectors exist and are readily available. When you feel comfortable with these selectors, don’t be afraid to look into some of the more advanced selectors.

All right, everything is starting to come together. We add elements to a page inside our HTML, and we can then select those elements and apply styles to them using CSS. Now let’s connect the dots between our HTML and CSS, and get these two languages working together.

Referencing CSS

In order to get our CSS talking to our HTML, we need to reference our CSS file within our HTML. The best practice for referencing our CSS is to include all of our styles in a single external style sheet, which is referenced from within the <head> element of our HTML document. Using a single external style sheet allows us to use the same styles across an entire website and quickly make changes sitewide.

Other Options for Adding CSS

Other options for referencing CSS include using internal and inline styles. You may come across these options in the wild, but they are generally frowned upon, as they make updating websites cumbersome and unwieldy.

To create our external CSS style sheet, we’ll want to use our text editor of choice again to create a new plain text file with a .css file extension. Our CSS file should be saved within the same folder, or a subfolder, where our HTML file is located.

Within the <head> element of the HTML document, the <link> element is used to define the relationship between the HTML file and the CSS file. Because we are linking to CSS, we use the rel attribute with a value of stylesheet to specify their relationship. Furthermore, the href (or hyperlink reference) attribute is used to identify the location, or path, of the CSS file.

Consider the following example of an HTML document <head> element that references a single external style sheet.

1
2
3
4
<head>
  <link rel="stylesheet" href="main.css">
</head>

In order for the CSS to render correctly, the path of the href attribute value must directly correlate to where our CSS file is saved. In the preceding example, the main.css file is stored within the same location as the HTML file, also known as the root directory.

If our CSS file is within a subdirectory or subfolder, the href attribute value needs to correlate to this path accordingly. For example, if our main.css file were stored within a subdirectory named stylesheets, the href attribute value would be stylesheets/main.css, using a forward slash to indicate moving into a subdirectory.

At this point our pages are starting to come to life, slowly but surely. We haven’t delved into CSS too much, but you may have noticed that some elements have default styles we haven’t declared within our CSS. That is the browser imposing its own preferred CSS styles for those elements. Fortunately we can overwrite these styles fairly easily, which is what we’ll do next using CSS resets.

Using CSS Resets

Every web browser has its own default styles for different elements. How Google Chrome renders headings, paragraphs, lists, and so forth may be different from how Internet Explorer does. To ensure cross-browser compatibility, CSS resets have become widely used.

CSS resets take every common HTML element with a predefined style and provide one unified style for all browsers. These resets generally involve removing any sizing, margins, paddings, or additional styles and toning these values down. Because CSS cascades from top to bottom—more on that soon—our reset needs to be at the very top of our style sheet. Doing so ensures that those styles are read first and that all of the different web browsers are working from a common baseline.

There are a bunch of different resets available to use, all of which have their own fortes. One of the most popular resets is Eric Meyer’s reset, which has been adapted to include styles for the new HTML5 elements.

If you are feeling a bit more adventurous, there is also Normalize.css, created by Nicolas Gallagher. Normalize.css focuses not on using a hard reset for all common elements, but instead on setting common styles for these elements. It requires a stronger understanding of CSS, as well as awareness of what you’d like your styles to be.

Cross-Browser Compatibility & Testing

As previously mentioned, different browsers render elements in different ways. It’s important to recognize the value in cross-browser compatibility and testing. Websites don’t need to look exactly the same in every browser, but they should be close. Which browsers you wish to support, and to what degree, is a decision you will need to make based on what is best for your website.

In all there are a handful of things to be on the lookout for when writing CSS. The good news is that anything is possible, and with a little patience we’ll figure it all out.

In Practice

Picking back up where we last left off on our conference website, let’s see if we can add in a bit of CSS.

  1. Inside of our “styles-conference” folder, let’s create a new folder named “assets.” We’ll store all of the assets for our website, such as our style sheets, images, videos, and so forth, in this folder. For our style sheets, let’s go ahead and add another folder named “stylesheets” inside the “assets” folder.
  2. Using our text editor, let’s create a new file named main.css and save it within the “stylesheets” folder we just created.
  3. Looking at our index.html file in a web browser, we can see that the <h1> and <p> elements each have default CSS styles. Specifically, they each have a unique font size and spacing around them. Using Eric Meyer’s reset, we can tone down these styles, allowing each of them to be styled from the same base. To do this let’s head over to Eric’s website, copy his reset, and paste it at the top of our main.css file.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    /* http://meyerweb.com/eric/tools/css/reset/ 2. v2.0 | 20110126
      License: none (public domain)
    */
    
    html, body, div, span, applet, object, iframe,
    h1, h2, h3, h4, h5, h6, p, blockquote, pre,
    a, abbr, acronym, address, big, cite, code,
    del, dfn, em, img, ins, kbd, q, s, samp,
    small, strike, strong, sub, sup, tt, var,
    b, u, i, center,
    dl, dt, dd, ol, ul, li,
    fieldset, form, label, legend,
    table, caption, tbody, tfoot, thead, tr, th, td,
    article, aside, canvas, details, embed,
    figure, figcaption, footer, header, hgroup,
    menu, nav, output, ruby, section, summary,
    time, mark, audio, video {
      margin: 0;
      padding: 0;
      border: 0;
      font-size: 100%;
      font: inherit;
      vertical-align: baseline;
    }
    /* HTML5 display-role reset for older browsers */
    article, aside, details, figcaption, figure,
    footer, header, hgroup, menu, nav, section {
      display: block;
    }
    body {
      line-height: 1;
    }
    ol, ul {
      list-style: none;
    }
    blockquote, q {
      quotes: none;
    }
    blockquote:before, blockquote:after,
    q:before, q:after {
      content: '';
      content: none;
    }
    table {
      border-collapse: collapse;
      border-spacing: 0;
    }
    
  4. With our main.css file starting to take shape, let’s connect it to our index.html file. Opening the index.html file in our text editor, let’s add the <link> element within our <head> element, just after the <title> element.
  5. Because we’ll be referencing a style sheet within the <link> element, let’s add the relation attribute, rel, with a value of stylesheet.
  6. We also want to include a hyperlink reference, using the href attribute, to our main.css file. Remember, our main.css file is saved within the “stylesheets” folder, which is inside the “assets” folder. Therefore, the href attribute value, which is the path to our main.css file, needs to be assets/stylesheets/main.css.
    1
    2
    3
    4
    5
    6
    <head>
      <meta charset="utf-8">
      <title>Styles Conference</title>
      <link rel="stylesheet" href="assets/stylesheets/main.css">
    </head>
    

Time to check out our work and see if our HTML and CSS are getting along. Now opening our index.html file (or refreshing the page if it’s already opened) within a web browser should show slightly different results than before.

Styles Conference website
Fig 1Our Styles Conference website with a CSS reset

Demo & Source Code

Below you may download the source code for the website in its current state.

Download the Source Code (Zip file)

Summary

So far, so good! We’ve taken a few big steps in this lesson.

Just think, you now know the basics of HTML and CSS. As we continue and you spend more time writing HTML and CSS, you’ll become much more comfortable with the two languages.

To recap, so far we’ve covered the following:

  • The difference between HTML and CSS
  • Getting acquainted with HTML elements, tags, and attributes
  • Setting up the structure of your first web page
  • Getting acquainted with CSS selectors, properties, and values
  • Working with CSS selectors
  • Referencing CSS in your HTML
  • The value of CSS resets

Web Developer Courses at Rayagada.

Web Developer Courses at Rayagada.

All The courses covers real life web developement examples.
There are more then 200 companies in India who hire fresh graduates for web development using php and mysql. Normally companies have to give 2-3 months of full time training in php and mysql to new hires. This online course provides this real life training for web development before graduates join a company. This will help the companies save 3 months of time and 50,000 to 100,000 Rs that companies spend in salaries and training of fresh graduates before they become productive.
Certified jquery developer Course Content is designed by working java professionals with a combined experience of nearly 25 years in java behind them. The development of this IT course was the meeting point of all these java professionals where they shared their magical ideas, concepts, real life experience and problems which resulted in this exciting Online course. Come! Join the gang and enjoy the world of Java.
PHP being one of the most widely used open source language for web development, there is a huge demand in the market for PHP developers. SiliconIndia’s PHP course consists of 100s of real time examples and assignments, which will help you, understand what is used in the industry and get your dream job.
MySQL is the M factor of the LAMP stack, since more than 70% of the big websites use MySQL for their database. SiliconIndia’s MySQL course cover from the basic to the advanced level of database techniques and concepts. By doing this course you will undergo lot of real time examples on database management. This will ensure you to stand-alone in the market and get a job easily.

SEO training course

Search Engine Optimization (SEO) training is most sought by companies to train their employees in this new field of SEO. This is first SEO course of its kind in India for SEO training and certification which has been designed by a team of US and India based experts.

f this course is that each and every student should be benefitted to the maximum.

 

Angular JS course

Learn to use Angular.js by adding behavior to your HTML and speeding up your application’s responsiveness. Get ready to dive into all the angles of Angular.js!

 

WordPress course

WordPress is the most popular way for people to build a blog or a website.

Since WordPress was founded in 2003, it has grown every year and is now seen and used by tens of millions of people every day.

WordPress is easy to use and easy to modify. That’s why millions of people every day use it to create their own site. Famous users of WordPress include the BBC, the New York Times and Ford.

Html5 and CSS3 course

Learn to Code HTML & CSS is a simple and comprehensive guide dedicated to helping beginners learn HTML and CSS. Outlining the fundamentals, this guide works through all common elements of front-end design and development.

Learn jQuery – Day 4

Events

These methods are used for registering user actions in a browser and acting after the same ones, and also as a way to manipulate registered actions.

jQuery supports the following events:

BLUR
– when an element loses focus

FOCUS
– when an element gets focus

FOCUSIN
– when a child element gets focus

FOCUSOUT
– when a child element loses focus

LOAD
– when an element is completely loaded (supported elements: img, script, frame, iframe, window)

RESIZE
– when a window object changes size

SCROLL
– when the user moves his scroller (works on a window object but also on all elements that have CSS overflow turned on)

UNLOAD
– is linked to the window element and is triggered when the user leaves the page

CLICK
– when the element is clicked

DBLCLICK
– when the element is double clicked

MOUSEDOWN
– when the cursor is above the element and the left mouse button is pressed

MOUSEUP
– when the cursor is above the element and the left mouse button is released

MOUSEMOVE
– when the cursor is moving inside the element

MOUSEOVER
– when the passes over the element

MOUSEOUT
– when the cursor leaves the element field

MOUSEENTER
– when the cursor enters the element field

MOUSELEAVE
– same as mouseout

CHANGE
– when the value of the element is changed (supported elements: input, textarea, select)

SELECT
– when a user selects a text inside the element (supported elements: input i textarea)

SUBMIT
– when a user tries to send a form (supports only form element)

KEYDOWN
– when the user presses any key on the keyboard. It can be linked to any element, but that elements must be in focus

KEYPRESS
– same as keydown, only it doesn’t register auxiliary keys (shift, ctrl, alt…)

KEYUP
– when a user presses and releases any button on the keyboard. It can be linked to any element, but that element must be in focus

ERROR
– when elements, like pictures, don’t load properly

 

.BIND()
Binds a function to execute a certain element in reaction to an action that the user made.

$('#myElement').bind('click', function(){        alert('User clicked on button');     });

 

.LIVE()
Does the same as the .bind() method , only it connects events to all elements added in the future. For example, if we link a certain event that has the class my class, and will later add a second element with the same class, .bind() element will not give him that event, but .live() will.

 $('#myElement').bind('click', function() {       alert('User clicked on button');    });

 

.ONE()
Links a certain event to an element that will be executed only once.

 /* the function will be executed only after the first click.   After every next click nothing will happen */       $('#myElement').one('click', function() {    alert('User clicked on button'

 

.DIE()
Removes all or a certain event from an element. It can also delete a certain function that has been assigned to an element through a event.

// removes all events    $('#myElement').die();      // removes all click events    $('#myElement').die('click');      // removes acertain function that has been previously assigned on a click event    $('#myElement').die('click', someFunction);

 

All above mentioned events can be used with .bind(), .live(), .one() and .die() methods or as independent methods (example: .click(), .focus()…)

 

.READY()
Starts when DOM is completely loaded. Always use this method when you are starting your functions. It links exclusively on a document object.

 $(document).ready(function() {       // your functions are called here });

 

Read next tutorial tomorrow.

 

Links you may like :

Learn jQuery – Day 1

Learn jQuery – Day 2

Learn jQuery – Day 3

 

 

Learn jQuery – Day 3

MANIPULATION

The Methods in this group are used to manipulate DOM elements. You can use them to do modifications, make new ones, copy, delete etc.

 

.APPEND( )
Makes a new object according to given parameters and places it at the end of the element set inside the selected element.

$('div#mydiv').append('<p>some paragraph</p>');

 

.APPENDTO( )
Opposite to the .append() methods. Adds the selected element at the end of the element set inside the forwarded element.

$('<p>My heading</p>').appendTo('div#heading');

 

.PREPEND( )
Opposite to the .append() methods. Makes a new object according to the given parameters and places it at the beginning of the element set inside the selected element.It uses selectors, HTML code or already existing elements as parameters.

$('#mydiv').prepand('<p>My text</p>');

Decoding jQuery

.AFTER( )
Makes a new object according to the given parameters and places it immediately after the selected element. It uses selectors, HTML code or already existing elements as parameters.

// makes <div> an element with id second and places it after the element with id first  $('#first').after('div#second');  // makes a new <p> element and places it after the element with id heading  $('#heading).after('<p>My text</p>');

 

.BEFORE( )
Makes a new object according to the given parameters and places it immediately before the selected element. It uses selectors, HTML code or already existing elements as parameters.

$('#heading).before('<p>My text</p>');

.CLONE( )
Makes a duplicate of the selected element that can be later added to other elements using different methods

// example of cloning and adding the cloned element to a different element $('#heading).clone( ).appendTo('div#content);

 

.DETACH( )
Removes elements from DOM but retains their copy in the case you want to return them later

// removes element and places copy in abc object var abc = $('#mydiv').detach( );

 

.EMPTY( )
Deletes all child elements in the selected element from DOM

$('#mydiv').empty( );

 

.REMOVE( )
Similar to the .empty() method. Deletes the selected element and all his childs from DOM. It is possible to forward a parameter for choosing the elements to delete.

//  deletes the element with the id mydiv and with all of his childs $('#mydiv').remove( );  // deletes all <div> elements with the myclass class $('div').remove('.myclass');

.REPLACEWITH( )
Changes every selected element with new given elements, It uses selectors, HTML code or already existing elements as parameters.

$('.myclass').replaceWith('<h2>heading</h2>');

 

.TEXT( )
Returns the text from the selected element and from all his childs or enters new textual content inside the element. If there is a new textual content that is being entered, all elements that were in the selected element are deleted.

// returns textual content $('div.container').text( );  // enters textual content $('div.container').text('Some new text');

 

.WRAP( )
Makes a new element and places it as a parent of the selected element. It uses selectors, HTML code or already existing elements as parameters.

$('p#mytext').wrap('div#container');

 

.UNWRAP( )
Deletes the parent element leaving the selected element and all his childs in place.

$('div.container').unwrap( );

 

.WRAPINNER( )
Makes a new element and places it as a child element to the selected element, enveloping all elements inside him. It uses selectors, HTML code or already existing elements as parameters.

$('div#container').wrapInner('div#wrapper');

Read next part of tutorial tomorrow.

Links you may like :

Learn jQuery – Day 1

Learn jQuery – Day 2

Animating AngularJS Apps: ngView

AngularJS provides a great way to create single page applications. This allows for our site to feel more and more like a native mobile application since we have a single page app. To make it feel even more native, we can add transitions and animations using ngAnimate module.

This module allows us to create beautiful looking applications. Today we’ll be looking at how to animate ng-view.

What We’ll Be Building

Let’s say we have a single page application where we want to animate the page change. Clicking on a link will slide one view out and another into view.

We’ll use:

  • ngRoute for our page routing
  • ngAnimate to create our page animations
  • CSS Animations will be applied to the pages
  • Each of our pages will have different animations when leaving or entering the view

Extreme Animations: The animations we’ll be using here are a little over the top. Animations that are subtle can be useful for your production sites, we’re just going crazy for demonstration purposes. *Animations are from this great tutorial from Codrops: A Collection of Page Transitions

How Does It Work?

Let’s take a look at how ngAnimate works. ngAnimate will add and remove CSS classes to different Angular directives based on if they are entering or leaving the view. For example, when we load up a site, whatever is populated in ng-view gets a .ng-enter class.

All we have to do is apply a CSS animation to that .ng-enter class and that will be applied upon entry.

ngAnimate Works On: ngRepeat, ngInclude, ngIf, ngSwitch, ngShow, ngHide, ngView, and ngClass

Definitely go through the ngAnimate documentation to see more of what ngAnimate can do. Now let’s see it in action.

Starting Our Application

Here are the files we’ll need.

    - index.html
    - style.css
    - app.js
    - page-home.html
    - page-about.html
    - page-contact.html

Let’s start up an index.html file. We’ll load up AngularJS, ngRoute, and ngAnimate. Oh and don’t forget Bootstrap for stylings.

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>

    <!-- CSS -->
    <!-- load bootstrap (bootswatch version) -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/3.1.1/readable/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">
    
    <!-- JS -->
    <!-- load angular, ngRoute, ngAnimate -->
    <script src="http://code.angularjs.org/1.2.13/angular.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-route.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-animate.js"></script>
    <script src="app.js"></script>

</head>

<!-- apply our angular app -->
<body ng-app="animateApp">

    <!-- inject our views using ng-view -->
    <!-- each angular controller applies a different class here -->
    <div class="page {{ pageClass }}" ng-view></div>
        
</body>
</html>

Here is our very simple HTML file. Load up our resources necessary, apply our Angular app, and add ng-view for our injected views.

Let’s take a look at the other files we’ll need.

    - index.html
    - style.css
    - app.js
    - page-home.html
    - page-about.html
    - page-contact.html

Our Angular Application app.js

Now we will create our Angular application with routing so that we can change pages without a page refresh. For more information on Angular routing, check out our other tutorial: Single Page Apps with AngularJS Routing and Templating.

// app.js

// define our application and pull in ngRoute and ngAnimate
var animateApp = angular.module('animateApp', ['ngRoute', 'ngAnimate']);

// ROUTING ===============================================
// set our routing for this application
// each route will pull in a different controller
animateApp.config(function($routeProvider) {

    $routeProvider

        // home page
        .when('/', {
            templateUrl: 'page-home.html',
            controller: 'mainController'
        })

        // about page
        .when('/about', {
            templateUrl: 'page-about.html',
            controller: 'aboutController'
        })

        // contact page
        .when('/contact', {
            templateUrl: 'page-contact.html',
            controller: 'contactController'
        });

});


// CONTROLLERS ============================================
// home page controller
animateApp.controller('mainController', function($scope) {
    $scope.pageClass = 'page-home';
});

// about page controller
animateApp.controller('aboutController', function($scope) {
    $scope.pageClass = 'page-about';
});

// contact page controller
animateApp.controller('contactController', function($scope) {
    $scope.pageClass = 'page-contact';
});

We have now created our application, created our routing, and created our controllers.

Each controller will have its own pageClass variable. This is applied to our ng-view in the index.html file so that we have a different class for each page. With a different class for each page, we will be able to apply different animations to each specific page.

Views page-home.html, page-about.html, page-contact.html

These will be clean and straightforward. We just need some text for each and the links to the other pages.

<!-- page-home.html -->
<h1>Angular Animations Shenanigans</h1>
<h2>Home</h2>

<a href="#about" class="btn btn-success btn-lg">About</a>
<a href="#contact" class="btn btn-danger btn-lg">Contact</a>

<!-- page-about.html -->
<h1>Animating Pages Is Fun</h1>
<h2>About</h2>

<a href="#" class="btn btn-primary btn-lg">Home</a>
<a href="#contact" class="btn btn-danger btn-lg">Contact</a>

<!-- page-contact.html -->
<h1>Tons of Animations</h1> 
<h2>Contact</h2>

<a href="#" class="btn btn-primary btn-lg">Home</a>
<a href="#about" class="btn btn-success btn-lg">About</a>

We now have our pages and they will be injected into our main index.html file with the power of Angular routing.

Now all the boring stuff is done. Our app should work and be able to change pages nicely. Now let’s get to the part we actually wanted, the animations!

Animating Our App style.css

All of the animations we will create will be with CSS. This is great because all we had to do was add ngAnimate and now, without any changes to our Angular code, we can apply CSS animations.

Two classes that ngAnimate adds to our ng-view are .ng-enter and .ng-leave. You can guess what each of those are used for.

Base Styles

Here we’ll add some base styles so that our app doesn’t look too boring.


/* make our pages be full width and full height */
/* positioned absolutely so that the pages can overlap each other as they enter and leave */
.page        {
    bottom:0; 
    padding-top:200px;
    position:absolute; 
    text-align:center;
    top:0;  
    width:100%; 
}

.page h1    { font-size:60px; }
.page a     { margin-top:50px; }

/* PAGES (specific colors for each page)
============================================================================= */
.page-home      { background:#00D0BC; color:#00907c; }
.page-about     { background:#E59400; color:#a55400; }
.page-contact   { background:#ffa6bb; color:#9e0000; }

With that, we have base styles for all three pages. As we click through our app, we can see those applied with the colors and spacing.

CSS Animations

Let’s define our animations and then we’ll look at how we can apply them to each of the pages as they enter and leave.

Vendor Prefixes: We will be using the default CSS attributes without the vendor prefixes. The full code will have all the vendor prefixes.

Let’s make 6 different animations. Each page will have their very own ng-enter and ng-leave animation.

/* style.css */
...

/* ANIMATIONS
============================================================================= */

/* leaving animations ----------------------------------------- */
/* rotate and fall */
@keyframes rotateFall {
    0%      { transform: rotateZ(0deg); }
    20%     { transform: rotateZ(10deg); animation-timing-function: ease-out; }
    40%     { transform: rotateZ(17deg); }
    60%     { transform: rotateZ(16deg); }
    100%    { transform: translateY(100%) rotateZ(17deg); }
}

/* slide in from the bottom */
@keyframes slideOutLeft {
    to      { transform: translateX(-100%); }
}

/* rotate out newspaper */
@keyframes rotateOutNewspaper {
    to      { transform: translateZ(-3000px) rotateZ(360deg); opacity: 0; }
}

/* entering animations --------------------------------------- */
/* scale up */
@keyframes scaleUp {
    from    { opacity: 0.3; -webkit-transform: scale(0.8); }
}

/* slide in from the right */
@keyframes slideInRight {
    from    { transform:translateX(100%); }
    to      { transform: translateX(0); }
}

/* slide in from the bottom */
@keyframes slideInUp {
    from    { transform:translateY(100%); }
    to      { transform: translateY(0); }
}

With these animations all made, we will now apply them to our pages.

Entering and Leaving Animations

To apply our animations to our pages, we will just apply these animations to .ng-enter or .ng-leave.

/* style.css */
...

    .ng-enter           { animation: scaleUp 0.5s both ease-in; z-index: 8888; }
    .ng-leave           { animation: slideOutLeft 0.5s both ease-in; z-index: 9999; }

...

Now our application will animate just like that. Pages will slide out to the left when leaving and scale up when entering. We also added z-index so that the page leaving would be placed above the one entering.

Let’s look at creating page specific animations.

Page Specific Animations

We created separate Angular controllers for each of the pages. Inside of these controllers we added a pageClass and applied that to our <div ng-view>. We’ll use these classes to call out a page specifically.

Instead of the .ng-enter and .ng-leave code above, let’s make them page specific.

...

    .ng-enter       { z-index: 8888; }
    .ng-leave       { z-index: 9999; }

    /* page specific animations ------------------------ */

    /* home -------------------------- */
    .page-home.ng-enter         { animation: scaleUp 0.5s both ease-in; }
    .page-home.ng-leave         { transform-origin: 0% 0%; animation: rotateFall 1s both ease-in; }

    /* about ------------------------ */
    .page-about.ng-enter        { animation:slideInRight 0.5s both ease-in; }
    .page-about.ng-leave        { animation:slideOutLeft 0.5s both ease-in; }

    /* contact ---------------------- */
    .page-contact.ng-leave      { transform-origin: 50% 50%; animation: rotateOutNewspaper .5s both ease-in; }
    .page-contact.ng-enter      { animation:slideInUp 0.5s both ease-in; }

...

Now each page will have its own unique enter and leave animation!

Conclusion

It’s fairly easy to add animations to your Angular application. All you have to do is load up ngAnimate and create your CSS animations. Hopefully this has helped you see a couple cool things you can animate when using ng-view.

We’ll be creating other articles on how to animate with ngRepeat, ngSwitch, and all of its brothers.

To get the complete source code of this page send mail to subratsir.

Single Page Apps with angularjs routing and templeting

Overview

Single page apps are becoming increasingly popular. Sites that mimic the single page app behavior are able to provide the feel of a phone/tablet application. Angular helps to create applications like this easily.

Our Simple App

We’re just going to make a simple site with a home, about, and contact page. Angular is built for much more advanced applications than this, but this tutorial will show many of the concepts needed for those larger projects.

Goals

  • Single page application
  • No page refresh on page change
  • Different data on each page
While this can be done with just Javascript and AJAX calls, Angular will make this process easier as our app starts growing.

File Structure

    - script.js             <!-- stores all our angular code -->
    - index.html            <!-- main layout -->
    - pages                 <!-- the pages that will be injected into the main layout -->
    ----- home.html
    ----- about.html
    ----- contact.html

HTML

This is the simple part. We’re using Bootstrap and Font Awesome. Open up your index.html file and we’ll add a simple layout with a navigation bar.

<!-- index.html -->
    <!DOCTYPE html>
    <html>
    <head>
      <!-- SCROLLS -->
      <!-- load bootstrap and fontawesome via CDN -->
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" />
      <!-- SPELLS -->
      <!-- load angular and angular route via CDN -->
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
          <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
      <script src="script.js"></script>
    </head>
    <body>

        <!-- HEADER AND NAVBAR -->
        <header>
            <nav class="navbar navbar-default">
            <div class="container">
                <div class="navbar-header">
                    <a class="navbar-brand" href="/">Angular Routing Example</a>
                </div>

                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#"><i class="fa fa-home"></i> Home</a></li>
                    <li><a href="#about"><i class="fa fa-shield"></i> About</a></li>
                    <li><a href="#contact"><i class="fa fa-comment"></i> Contact</a></li>
                </ul>
            </div>
            </nav>
        </header>

        <!-- MAIN CONTENT AND INJECTED VIEWS -->
        <div id="main">

            <!-- angular templating -->
            <!-- this is where content will be injected -->

        </div>

    </body>
    </html>

For linking to pages, we’ll use the #. We don’t want the browser to think we are actually travelling to about.html or contact.html.

Angular Application

Module and Controller

We’re going to setup our application. Let’s create the angular module and controller. Check out the docs for more information on each.

First, we have to create our module and controller in javascript. We will do that now in script.js.

// script.js

    // create the module and name it scotchApp
    var scotchApp = angular.module('scotchApp', []);

    // create the controller and inject Angular's $scope
    scotchApp.controller('mainController', function($scope) {

        // create a message to display in our view
        $scope.message = 'Everyone come and see how good I look!';
    });

Let’s add the module and controller to our HTML so that Angular knows how to bootstrap our application. To test that everything is working, we will also show the $scope.message variable that we created.

<!-- index.html -->
    <!DOCTYPE html>

    <!-- define angular app -->
    <html ng-app="scotchApp">
    <head>
      <!-- SCROLLS -->

      <!-- load bootstrap and fontawesome via CDN -->
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" />
      <!-- SPELLS -->
      <!-- load angular and angular route via CDN -->
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
          <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
      <script src="script.js"></script>
</head> 
<!-- define angular controller --> 
<body ng-controller="mainController"> 
... 
<!-- MAIN CONTENT AND INJECTED VIEWS --> 
<div id="main"> 
      {{ message }} <!-- angular templating --> 
      <!-- this is where content will be injected --> 
</div>

Inside of our main div, we will now see the message that we created. Since we have our module and controller set up and we know that Angular is working properly, we will start working on using this layout to show the different pages.

Injecting Pages into the Main Layout

ng-view is an Angular directive that will include the template of the current route (/home, /about, or /contact) in the main layout file. In plain words, it takes the file we want based on the route and injects it into our main layout (index.html).

We will add the ng-view code to our site in the div#main to tell Angular where to place our rendered pages.

<!-- index.html -->
    ...

    <!-- MAIN CONTENT AND INJECTED VIEWS -->
    <div id="main">

        <!-- angular templating -->
        <!-- this is where content will be injected -->
        <div ng-view></div>

    </div>

    ...

Configure Routes and Views

Since we are making a single page application and we don’t want any page refreshes, we’ll use Angular’s routing capabilities.

Let’s look in our Angular file and add to our application. We will be using $routeProvider in Angular to handle our routing. This way, Angular will handle all of the magic required to go get a new file and inject it into our layout.

AngularJS 1.2 and Routing The ngRoute module is no longer included in Angular after version 1.1.6. You will need to call the module and add it to the head of your document to use it. This tutorial has been updated for AngularJS 1.2
// script.js

    // create the module and name it scotchApp
        // also include ngRoute for all our routing needs
    var scotchApp = angular.module('scotchApp', ['ngRoute']);

    // configure our routes
    scotchApp.config(function($routeProvider) {
        $routeProvider

            // route for the home page
            .when('/', {
                templateUrl : 'pages/home.html',
                controller  : 'mainController'
            })

            // route for the about page
            .when('/about', {
                templateUrl : 'pages/about.html',
                controller  : 'aboutController'
            })

            // route for the contact page
            .when('/contact', {
                templateUrl : 'pages/contact.html',
                controller  : 'contactController'
            });
    });

    // create the controller and inject Angular's $scope
    scotchApp.controller('mainController', function($scope) {
        // create a message to display in our view
        $scope.message = 'Everyone come and see how good I look!';
    });

    scotchApp.controller('aboutController', function($scope) {
        $scope.message = 'Look! I am an about page.';
    });

    scotchApp.controller('contactController', function($scope) {
        $scope.message = 'Contact us! JK. This is just a demo.';
    });

Now we have defined our routes with $routeProvider. As you can see by the configuration, you can specify the route, the template file to use, and even a controller. This way, each part of our application will use its own view and Angular controller.

Clean URLs: By default, Angular will throw a hash (#) into the URL. To get rid of this, we will need to use $locationProvider to enable the HTML History API. This will remove the hash and make pretty URLs. For more information: Pretty URLs in AngularJS: Removing the #.

Our home page will pull the home.html file. About and contact will pull their respective files. Now if we view our app, and click through the navigation, our content will change just how we wanted.

To finish off this tutorial, we just need to define the pages that will be injected. We will also have them each display a message from its respectiive controller.

<!-- home.html -->
    <div class="jumbotron text-center">
        <h1>Home Page</h1>

        <p>{{ message }}</p>
    </div>

<!-- about.html -->
    <div class="jumbotron text-center">
        <h1>About Page</h1>

        <p>{{ message }}</p>
    </div>

<!-- contact.html -->
    <div class="jumbotron text-center">
        <h1>Contact Page</h1>

        <p>{{ message }}</p>
    </div>

Working Locally: Angular routing will only work if you have an environment set for it. Make sure you are using http://localhost or some sort of environment. Otherwise Angular will spit out a Cross origin requests are only supported for HTTP.

Animating Angular Apps

Once you have all the routing done, you can start to get really fancy with your site and add in animations. To do this, you will need the ngAnimate module provided by Angular. After that you can animate your pages into view with CSS animations.

For a tutorial on how to get animations in your site, read: Animating AngularJS Apps: ngView.

SEO on Single Page Apps

Ideally, this technique would be used for an application after a person has signed in. You wouldn’t really want those pages indexed since they are personalized to that specific user. For example, you wouldn’t want your Reader account, Facebook logged in pages, or Blog CMS pages indexed.

If you did want SEO for you application though, how does SEO work for applications/sites that get their pages built with Javascript? Search engines have a difficult time processing these applications because the content is built dynamically by the browser and not visible to crawlers.

Making Your App SEO Friendly

Techniques to make Javascript single page applications SEO friendly require regular maintenance. According to the official Google suggestions, you would create HTML snapshots. The basic overview of how it would work is that:

  1. A crawler would find a pretty URL (https://scotch.io/seofriendly#key=value)
  2. The crawler would then ask the server for the contents of this URL (in a special modified way)
  3. Web server returns content using an HTML snapshot
  4. HTML snapshot is processed by the crawler
  5. Search results then show the original URL

For more information on this process, be sure to look at Google’s AJAX Crawling and their guide on creating HTML snapshots.

SEO Article: We’ve written up a tutorial on how to make Angular SEO friendly. Give it a read if you’re interested: AngularJS SEO with Prerender.io.

Conclusion

This was a very simple tutorial on how to get Angular routing to work with a layout and separate views. Now you can go ahead and create larger single page applications. There is much more to learn with Angular and I’ll keep writing about different features along my learning journey of Angular.

If anyone has any suggestions for future Angular articles or different ways to do what we’ve just done here (there are so many ways to write the same thing, it can drive a person insane), sound off in the comments.

Further Reading If you are looking for more flexibility in routing like nested views and state based templating instead of route based, then you’ll definitely be interested in

 

To get the complete source code of this page send mail to subratsir.

Webcam Chat – Shocking Climax – IndiViral

We live in the world of Networking. Today social media is a part of our daily life. It is something we cannot live without. From Facebook to Twitter to Skype we meet and talk to many people. Some are known to us, close to us.. Some are those whom we have never even met. We all love making friends on Social Media, talk to new people across the globe. It was for this Primary Objective Social Media was developed, so that people can talk to each other across the globe without any barriers. But every coin has two sides. With such massive usage of Social media there are Cyber Crimes going up too. We come across Online Cases of Cyber Bullying, Cheating etc on a Daily Basis. One such crime people especially girls get trapped into is Webcam Chat!! Here is a video by Indi Viral of how a boy traps a girl in his Love. Talks sweetly and then forces a girl to do what he says. And shockingly girl finds no other option other than accepting it. Reports suggest that every year there are Thousands of Private chat making their way directly to Porn Sites. Many who fall into this trap take this as an embarrassment and end their Lives. A Webcam or a Phone Cam can be easily hacked and your personal video chats can be recorded. PLEASE BEWARE OF SUCH WEBCAM HACKING!! STAY SAFE!!

Learn jQuery – Day 2

jQuery has it’s methods for working with DOM attribute elements. They are very simple and there are just a few of them.

.ADDCLASS()

Adds a class or a group of classes to elements

1 $(‘p’).addClass(‘myClass yourClass’);

 

.HASCLASS()

Checks if the elements have the appropriate class

1 $(‘#mydiv’).hasClass(‘foo’);

 

.TOGGLECLASS()

Deletes or adds classes from elements depending on if the elements have a given class or not. If the element has a given class it’s deleted and vice versa

1 $(‘p’).toggleClass(‘myClass’);

 

.REMOVECLASS()

Deletes a certain class, multiple classes or all the classes from an element.

12

3

4

5

6

7

8

// Deletes one class$(‘p’).removeClass(‘myClass’);

 

// Deletes multiple class

$(‘p’).removeClass(‘myClass yourClass’);

 

// Deletes all classes from an element

$(‘p’).removeClass();

 

.ATTR()

Returns or enters any value for elements

12

3

4

5

// Return value$(‘a’).attr(‘title’);

 

// Assigns value

$(‘a’).attr(‘title’, ‘My link’);

 

.REMOVEATTR()

Deletes a certain attribute from the elements

1 $(‘div.container’).removeAttr(‘title’);

 

.HTML()

Returns the HTML element content. If there is a forwarded value (HTML), it is entered in the same element

12

3

4

5

// Returns the HTML element content$(‘div.container’).html();

 

// Enters the HTML element content

$(‘div.container’).html(‘<p>New paragraph</p>’);

 

.VAL()

Returns or enters the given value to the elements. It is used for element forms that have the attribute value

12

3

4

5

// Returns value$(‘input.name’).val();

 

// Enters value

$(‘input.name’).val(‘Peter’);

 

METHODS FOR MOVING THROUGH DOM

This group represents a collection of jQuerys methods for getting information about elements in DOM (order, layout, parent-child  relationship etc.). Since there are many of them we will give only the most important ones.

 

.ADD()

Adds elements to selected elements. It can contain a selector, an already exisitng element or an HTML code

12

3

4

5

6

7

8

9

// Adding elements through selectors$(‘div’).add(‘p.myclass’);

 

// Adding elements that already exist

var myElement = $(‘p#content’);

$(‘div’).add(myElement);

 

// Adding elements through HTML code

$(‘div’).add(‘<p id=”new”>New paragraph </p>’);

 

.PARENT()

Returns the first parent element. It is possible to forward a certain selector for checking a parent

12

3

4

5

// Returns all parent elements$(‘div.myclass’).parent();

 

// Returns parent elements only if they are this type <li>

$(‘div.myclass’).parent(‘li’);

 

.CHILDREN()

Returns all children elements. It is possible to forward a certain selector for filltering elements

12

3

4

5

// Returning all children elements$(‘div’).children();

 

// Returning only the children elements with the class .myclass

$(‘div’).children(‘.myclass’);

 

.FIND()

Returns all the children elements with a certain type of element (simillar to the .children() method).

12

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

<div id=”mydiv”><ul>

<li>1</li>

<li>

<ul>

<li>2.1</li>

<li>

<div>2.2</div>

</li>

<li>2.3</li>

</ul>

</li>

<li>3</li>

<li>

<div>4</div>

</li>

</ul>

</div>

 

$(‘#mydiv’).find(‘div’);

In the example above, we have a HTML structure that is made of of two list inside each other. Every one of those lists contains one <div> element. Our .find()  method will select only those two elements.

 

.NEXT()

Returns the next element in a row besides the selected element. It is possible to forward the selector to search only for a certain element.

12

3

4

5

//Returns the next element$(‘div.myclass’).next();

 

// Returns the next element

Only if its the type <ul>

$(‘div.myclass’).next(‘ul’);

 

.PREV()

Returns the previous element in arow by the selected element. It is possible to forward the selector to just search for a certain element

12

3

4

5

// Returns the previous element$(‘div.myclass’).prev();

 

// Returns the previous element only if it’s the type <ul>

$(‘div.myclass’).prev(‘ul’);

 

.FILTER()

Returns only certain elements from selected elements

1 $(‘li’).filter(‘.selected’);

The stated example will return only those <li> elements that have the class selected in them

 

.HAS()

Returns only elements that contain a certain element

1 $(‘div’).has(‘ul’);

The stated example will return only those <li> elements that contain a <ul> element

 

.NOT()

Returns all selected elements except a certain element. It accepts selectors or already existing elements

12

3

4

5

6

// Returns all <div> elements that don’t have an already existing selected elementvar mylement = $(‘p.myclass’);

$(‘div’).not(myelement);

 

// Returns all <div> elements that don’t have the myclass class

$(‘div’).not(‘.myclass’);

 

.SLICE()

Limits searched elements to a certain amount according to the ordinal number starting with the given index. It is possible to forward another parameter that represents where the search should end. The first index enters in the search while the other one doesn’t.

Remark: indexing starts with 0

12

3

4

5

// Returns all elements after the third one$(‘div’).slice(2);

 

// returns 4, 5 i 6 element (the last index didn’t enter the group of returned elements)

$(‘div’).slice(3,6);

 

This was the second part of the lesson about jQuery read the next part of the jQuery tutorial tomorrow.

How NOT to End Up in the Social Media Graveyard

How NOT to End Up in the Social Media Graveyard – Here’s a Free eBook to Keep Your Campaigns Alive + Helpful Job Resources

Remember that saying, “If you build it, they will come.”? Well, it’s not true. Abandoned corporate social media accounts. Deserted Twitter profiles littered with weak posts. Facebook pages with little to no engagement. Youtube channels with a video or two- uploaded half a decade ago. Is this how you want your social media campaigns to end?

Didn’t think so. Simplilearn has developed this informative eBook that will help make your social media efforts stand out and breathe life into your campaigns.

Grab your FREE copy here: ‘The Essentials of Social Media Marketing’ – http://goo.gl/r9TWgm

Bonus: FREE eBook on 9 High-Paying Certifications of 2015 – A certification from a respected source can further your career and validate your skills. Choose wisely –put our free eBook to good use! Get your copy here: http://goo.gl/YOX8RT

Social Media marketing budgets have jumped through the roof –experts note a 128% rise in funding campaigns! Candidates merely claiming expertise in Social Media marketing will no longer make the cut. Validate your skills and expertise with this Social Media Certification course from Simplilearn: http://goo.gl/7DAVmu (Use coupon code ‘ONLINE30′ to get a 30% discount!)

And sharing is caring – be sure to forward this email to your friends and colleagues who might be interested.

Here’s to your success!

Mike Crosson
Moderator & Publisher
www.socialmediopolis.com

AngularJS SQL

Fetching Data From a PHP Server Running MySQL

<div ng-app=“myApp” ng-controller=“customersCtrl”>

<table>
<tr ng-repeat=“x in names”>
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>

</div>

<script>
var app = angular.module(‘myApp’, []);
app.controller(‘customersCtrl’, function($scope, $http) {
$http.get(“http://www.w3schools.com/angular/customers_mysql.php”)
.success(function (response) {$scope.names = response.records;});
});
</script>

Server Code Examples

The following section is a listing of the server code used to fetch SQL data.

  1. Using PHP and MySQL. Returning JSON.
  2. Using PHP and MS Access. Returning JSON.

1. Server Code PHP and MySQL

<?php
header(“Access-Control-Allow-Origin: *”);
header(“Content-Type: application/json; charset=UTF-8″);

$conn = new mysqli(“myServer”, “myUser”, “myPassword”, “Northwind”);

$result = $conn->query(“SELECT CompanyName, City, Country FROM Customers”);

$outp = “”;
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != “”) {$outp .= “,”;}
$outp .= ‘{“Name”:”‘  . $rs[“CompanyName”] . ‘”,';
$outp .= ‘”City”:”‘   . $rs[“City”]        . ‘”,';
$outp .= ‘”Country”:”‘. $rs[“Country”]     . ‘”}';
}
$outp ='{“records”:[‘.$outp.’]}';
$conn->close();

echo($outp);
?>

2. Server Code PHP and MS Access

<?php
header(“Access-Control-Allow-Origin: *”);
header(“Content-Type: application/json; charset=ISO-8859-1″);

$conn = new COM(“ADODB.Connection”);
$conn->open(“PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb”);

$rs = $conn->execute(“SELECT CompanyName, City, Country FROM Customers”);

$outp = “”;
while (!$rs->EOF) {
if ($outp != “”) {$outp .= “,”;}
$outp .= ‘{“Name”:”‘  . $rs[“CompanyName”] . ‘”,';
$outp .= ‘”City”:”‘   . $rs[“City”]        . ‘”,';
$outp .= ‘”Country”:”‘. $rs[“Country”]     . ‘”}';
$rs->MoveNext();
}
$outp ='{“records”:[‘.$outp.’]}';

$conn->close();

echo ($outp);
?>

Learn jQuery – Day 1

jquery tutorialIn this jQuery tutorial you can see the things that sets jQuery apart from other libraries. jQuery methods are divided in multiple groups that, when they are combined make his API.

JQUERY API
The thing that sets jQuery apart from other libraries are his very simple, yet very powerful methods. jQuery methods are divided in multiple groups that, when they are combined make his API.

  • jQuery core
  • Selectors
  • Attributes
  • Moving through DOM
  • Manipulation
  • CSS
  • Events
  • Effects
  • AJAX
  • Utilities

JQUERY Core
jQuerys core represents his main jQuery object which we have talked about. It is used for catching elements from DOM by using selectors. It can be used in two ways.

1
2
3
4
5
// through jQuery names
jQuery();
// or through the mentioned dollar sign
$();

 I doesn’t matter which way you are going to use, but practice shows that it is standard to use the dollar sign because of easier recognition in the code.
But, sometimes it is necessary to have another library on your pages next to jQuery. Because most other libraries also use the dollar sign as their main object this could present a problem because of the conflict between the two libraries. Which brings us to jQuerys .noConflict() method, that allows undisturbed use of jQuery together with any other library that the dollar object. Because we can see from the above stated that jQuery can be called in two ways, this method disables the use of the dollar object. In other words, after the use of this function you will call jQuery through it’s name while you will call other libraries using the dollar object.
Everything you need to do is to attach the .noConflict() method on the dollar sign before any use by the other libraries.

1
2
$.noConflict();
// After this you can use the dollar sign for other libraries

Selectors

The browser and every HTML page is loaded in the memory as connected objects with specific properties. It is called a DOM (Document Object Model). Every operation in JavaScript begins by choosing the desired elements that you wish to work with. So, the access to an object is the base of any operation on it.

As we mentioned before, jQuery uses it’s dollar object for forwarding HTML elements, over which it performs it’s functions. This is done by using selectors. By supporting all CSS 1-3 selectors, as by adding his own, jQuery offers a very powerful group of tools used for ’’catching’’ elements in a document.

Let’s start with the basic elements. Everything you need to do to grab a certain element (or more of them) , is to enter it’s name between the quotes inside the dollar $() function as you would do in a CSS document.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// catching elements with id
$(“#test”);
// catching elements with class
$(“.heading”);
// catching elements types
$(“div”);
$(“img”);
// catching more complex elements
$(“div.container ul li.over a”);
// catching multiple elements at the same time
$(“selector1, selector2, selector3, …”);
/* catching elements with certain attributes
(you have to be careful if you are putting selectors between quotes to wrap the attribute value with single quotes, and reverse
) */
$(“form[name=name]”);
// catching all elements in a document $(“*”);

 

So no matter what CSS selector you are using, jQuery will find and select he wanted element. Next to the standard CSS selectors, jQuery has added their selectors for easier working with elements.

 

:CHECKED
Selects all given elements that are checked (those elements can be: checkbox and radio button).

1
$(“input[type=”checkbox”]:checked”);

The stated example will select every first <input> that is checkbox and is checked.

:CONTAINS()
Selects all given elements that contain searched text.

1
$(“div:contains(‘John’)”);

The above stated example will select every <div> element that contains the text John.

:EMPTY
Selects all given elements that don’t have any elements in them, or text.

1
$(“div:empty”);

The above stated example will select every <div> element that doesn’t contain any element or text.

:HAS()
Selects elements that contain at least one element.

1
$(“div:has(p)”);

The above stated example will select every <div> element that have the <p> element in them or any other element they contain not just as child element.

:NOT()
Selects elements that don’t match the given selector.

1
$(“div:not(.myclass)”);

The above stated example will select every <div> element that doesn’t have a .myclass class.

:FIRST-CHILD
Selects elements that are the first child of their parent-a.

1
$(“div span:first-child”);

The above stated example will select every first <span> element inside every <div> element.
:EQ()
Selects given elements in the order they show up (index starts with 0).

1
$(“td:eq(2)”);

The above stated example will select the third <td> element inside a table.
:NTH-CHILD()
Selects an element or elements that are being searched by the given order inside a parent. Index for the search can be a number or the options even or odd, or all even and odd elements in their order

Remark: this is the only case where the indexing starts with 1

1
2
$(“div:nth-child(3)”);
$(“div:nth-child(even)”);

The first example will select all child elements that appear in order inside every <div> element, while the other one will select all pair child elements inside all <div> elements.

It is possible to combine all stated selectors. Example:

1
$(“div.description:has(p:not(.intro))”);

In the given example all <div>elements with the class .description and that contain <p> elements and don’t have a class .intro will be selected.

 

This was the first part of the lesson about jQuery read Learn jQuery – Day 2 tomorrow.