Frontend guide Everything you need to know about HTML, CSS, JavaScript and DOM Dejan V Čančarević
Today frontend is treated as a separate part of Web development and therefore frontend developer jobs are highly wanted. "Frontend guide" is a complete guide for this kind of development with inside look at modern Web technologies and focus on CSS.
Thank you Before we delve into the wonderful world of frontend development, I would like to give thanks to the family, friends and colleagues who helped me in writing this book: My family (Vlado, Mirjana, Milan and Svetlana), Bella and Steve Guzmán, James Koster, Mladjan Antic and Nenad Gligoric. I've tried my best to make this book as bug and typo free as possible, but I'm sure I've missed some things. If you happen across an error, or would like to offer any other suggestions or feedback, please contact me at dejanc at gmail dot com.
Sincerely, Dejan Čančarević
Copyright © 2011 Dejan Čančarević. All rights reserved. No part of this publication may be reproduced or redistributed in any form without the prior written permission of the publishers. ISBN 978-1-257-37903-3
Content 0. Introduction ...........................................................................................1 What is frontend ...........................................................................................1 Who is this book for ......................................................................................1 Goal of the book ...........................................................................................1 Book structure ..............................................................................................2 Using examples .............................................................................................3 1. Frontend ................................................................................................4 1.1. Introduction...................................................................................4 1.2. Technologies in frontend development .........................................6 1.3. World Wide Web Consortium (W3C) .............................................7 1.4. Development software .................................................................7 1.5. Software for testing .......................................................................9 1.6. Additional tools .......................................................................... 10 2. HTML .................................................................................................. 12 2.1. Introduction................................................................................ 12 2.2. HTML tags introduction .............................................................. 14 2.3. HTML attributes introduction ..................................................... 16 2.4. Comments .................................................................................. 17 2.5. Page structure ............................................................................ 17 2.6. General attributes ...................................................................... 19 2.7. Basic tags ................................................................................... 21 2.7.1. Structural tags .................................................................. 21 2.7.2. Meta tags ......................................................................... 22 2.7.3. Example 1 - empty HTML page ......................................... 24 2.7.4. Text .................................................................................. 25 2.7.5. Example 2 - text formatting .............................................. 25 2.7.6. Links................................................................................. 27 2.7.7. Images and objects ........................................................... 27 2.7.8. Lists.................................................................................. 28 2.7.9. Example 3 - multimedia and lists ...................................... 28 2.7.10. Tables ............................................................................. 29
2.8. 2.9. 2.10. 2.11. 2.12.
2.7.11. Forms .............................................................................. 31 2.7.12. Example 4 - form ............................................................. 32 Special characters ....................................................................... 33 HTML 5 ....................................................................................... 34 2.9.1. New stuff .......................................................................... 35 HTML Frameworks ...................................................................... 35 Coding preparations .................................................................... 37 Conclusion................................................................................... 39
3. CSS ........................................................................................................ 40 3.1. Introduction .............................................................................. 40 3.2. History ...................................................................................... 41 3.3. Syntax....................................................................................... 41 3.4. Applying styles to the page ....................................................... 44 3.5. Example 5 - Adding styles to pages ........................................... 45 3.6. Document versioning ................................................................ 46 3.7. CSS selectors ............................................................................ 47 3.7.1. Inheritance ............................................................... 48 3.7.2. Prioritization............................................................. 52 3.7.3. Type selector ............................................................ 55 3.7.4. Universal selector ..................................................... 55 3.7.5. Class selector ............................................................ 55 3.7.6. ID selector ................................................................ 56 3.7.7. Example 6 - ID and class selectors ............................. 56 3.7.8. Attribute selector ..................................................... 59 3.7.9. Pseudo selectors ....................................................... 60 3.7.9.1. Structural pseudo classes .......................... 61 3.7.9.2. Link pseudo classes ................................... 63 3.7.9.3. User action pseudo classes ........................ 63 3.7.9.4. Example 7 - Element states........................ 64 3.7.9.5. UI state pseudo classes .............................. 65 3.7.9.6. Negation pseudo classes ........................... 65 3.7.9.7. Pseudo elements ....................................... 66 3.7.9.8. Example 8 - Pseudo elements .................... 66 3.7.10. Combinators ............................................................. 67 3.7.11. Web browser selectors ............................................. 69 3.8. Conditional comments .............................................................. 70 3.9. Color spaces .............................................................................. 71
3.10. 3.11.
3.12. 3.13. 3.14. 3.15.
3.16. 3.17.
Size units.................................................................................. 72 Properties and values ............................................................... 73 3.11.1. Font ................................................................................ 74 3.11.1.1. Example 9 - Font and basic typography .......... 76 3.11.2. Text ................................................................................ 79 3.11.2.1. Example 10 - Text formatting and align ........... 81 3.11.2.2. Example 11 - Vertical align ............................... 83 3.11.2.3. Example 12 -Text hiding .................................. 84 3.11.3. Colors and backgrounds.................................................. 85 3.11.3.1. Example 13 - Positioning background .............. 87 3.11.3.2. Multiple backgrounds ...................................... 92 3.11.4. Box model ...................................................................... 92 3.11.4.1. Example 14 - Element moving ........................ 98 3.11.5. Positioning and displaying ............................................ 100 3.11.5.1. Example 16 - float and clear ........................... 105 3.11.5.2. Example 17 - Positioning................................ 114 3.11.5.3. Example 18 - Overflow and clip ...................... 117 3.11.5.4. Example 19 - Changing element structure ..... 122 3.11.5.5. Example 20 - Hiding and displaying elements 123 3.11.5.6. Example 21 - Block navigation ....................... 124 3.11.6. Lists .............................................................................. 125 3.11.6.1. Example 22 - Using lists for navigation .......... 126 3.11.7. Tables ........................................................................... 127 3.11.7.1. Example 23 -Table styling .............................. 128 3.11.8. Other .......................................................................... 129 3.11.9. CSS3 properties, moz and webkit ................................. 129 3.11.9.1. Layout engines .............................................. 130 3.11.10. CSS font replacement ................................................. 135 3.11.11. Example 24 - Modern CSS 3 design ............................. 138 CSS sprites ............................................................................. 143 CSS reset................................................................................ 146 !important declaration ........................................................... 149 Fluid, fixed and elastic layout ................................................. 150 3.15.1. Example 25 - Fluid layout ......................................... 152 3.15.2. Example 26 - Combined fluid layout ........................ 153 CSS in modern Web design .................................................... 154 Conclusion ............................................................................. 158
4.
JavaScript ......................................................................................... 159 4.1. History ................................................................................... 159 4.2. Features ................................................................................. 160 4.3. Development tools ................................................................ 161 4.4. JavaScript basics .................................................................... 162 4.4.1. Use in web pages ...................................................... 162 4.4.2. Comments ............................................................... 163 4.4.3. Variables .................................................................. 163 4.4.4. Example 1 - Printing variables ................................... 164 4.4.5. Constants ................................................................. 164 4.4.6. Values ...................................................................... 165 4.4.7. Operators ................................................................. 165 4.4.7.1. Arithmetic operators .................................. 165 4.4.7.2. Assignment operators ................................ 165 4.4.7.3. Example 2 - Dynamic types ......................... 166 4.4.7.4. Comparation operators............................... 167 4.4.7.5. Logical operators ........................................ 167 4.4.7.6. Conditional operators ................................. 168 4.4.8. Special characters .................................................... 168 4.4.9. Statements .............................................................. 169 4.4.9.1. Conditional statements .............................. 169 4.4.9.2. Loops ......................................................... 170 4.4.9.3. Label, break and continue ........................... 171 4.4.9.4. Object manipulation ................................... 172 4.4.10. Exceptions ................................................................. 172 4.4.11. Functions ................................................................... 174 4.4.11.1. Defining and calling functions ..................... 175 4.4.11.2. Functions parameters ................................. 175 4.4.11.3. Parameter domain ...................................... 176 4.4.11.4. Returns statement ...................................... 177 4.4.11.5. Parameter properties.................................. 177 4.4.11.6. Anonymous functions ................................. 178 4.4.11.7. Recursive functions ..................................... 179 4.4.11.8. Core functions ............................................ 179 4.5. JavaScript objects .................................................................. 179 4.5.1. Object properties ......................................................... 180 4.5.2. Object methods ........................................................... 180 4.5.3. Core objects................................................................. 181
4.6.
4.7.
4.8.
4.9.
4.5.3.1. Array ............................................................... 181 4.5.3.2. Boolean........................................................... 185 4.5.3.3. Date ................................................................ 185 4.5.3.4. Function .......................................................... 186 4.5.3.5. Math ............................................................... 187 4.5.3.6. Number........................................................... 187 4.5.3.7. String .............................................................. 187 4.5.3.8. Regular expressions ........................................ 188 4.5.4. Custom objects ........................................................... 190 Web browser objects ............................................................. 193 4.6.1. Window object ............................................................ 193 4.6.2. Navigator object ......................................................... 195 4.6.3. History object ............................................................. 196 4.6.4. Location object ........................................................... 196 HTML DOM objects............................................................... 198 4.7.1. Document object ........................................................ 198 4.7.2. Element object............................................................ 200 4.7.3. Event object ................................................................ 202 JavaScript Frameworks ......................................................... 203 4.8.1. Modern frameworks overview ..................................... 203 4.8.2. jQuery ......................................................................... 204 4.8.2.1. How to use frameworks ................................. 204 4.8.2.2. Syntax ........................................................... 205 4.8.2.3. Selectors ....................................................... 206 4.8.2.4. Events ........................................................... 208 4.8.2.5. Example 3 - jQuery events ............................. 209 4.8.2.6. Effects ........................................................... 211 4.8.2.7. Example 4 - jQuery effects............................. 212 4.8.2.8. Callback ........................................................ 214 4.8.2.9. HTML manipulation ...................................... 214 4.8.2.10. Example 5 - jQuery HTML manipulation ....... 215 4.8.2.11. jQuery CSS manipulation .............................. 218 4.8.2.12. Example 6 - jQuery CSS manipulation ........... 219 Conclusion ............................................................................ 220
Appendix 1 - Graphics editing ................................................................. 221 Appendix 2 - SEO friendly coding............................................................ 228 List of figures ........................................................................................... 231 List of examples ...................................................................................... 234
Introduction What is frontend Frontend is a very important part of Web development because it represents visual part of website available to everyone while other parts of web applications are hidden into layers. In other words it represents everything you see when you open a web page. Who is this book for This book will teach you how to do frontend development by learning various technologies. You can think of it as a complete guide for this area, describing all key technologies, enriched with lot of real world examples and guidelines. In general many of people think of frontend as the less complex part of Web development when comparing it to some other parts (more about those later) because it is much simpler to use and understand. But this doesn’t mean it should be treated differently, after all it is part of every website and visual impression of the user along with rich functionality is most important. The goal of this book is to transform different types of visual design into high quality, optimized and valid frontend code, rich in client functionality. Client functionality is the type of functionality that is being processed on the client side (by the client computer, in Web browser). On the other side server functionality represents all the processes managed by some distant server, usually requested by user. You can learn more about this client-server type of communication in the next chapter. Goal of the book Frontend development includes many technologies and most of them are described in this book. From the user of this book it is expected to know basics of key technologies and those are HTML and CSS. Our goal is you to be able to produce high quality code for any kind of layout (page structure). Therefore every chapter starts with Frontend Guide
1
introduction to basic things and then follows up to more advanced examples. At the end of each chapter we will do couple of complex examples mostly taken from real projects. Along with basic code and basic things you will find advanced tips and snippets which you can use in various examples to break out from the usual coding loop that developers get in after some time of coding. This way you should have more open minded approach to problem solving instead of using the usual ideas and techniques. This book is not a reference for learning HTML or CSS. Instead it is a guide on how to use these technologies to develop modern Web pages. Book structure The book is divided into four chapters and each chapter represents a large whole that you need to learn in order to proceed because all these parts work together. The longest chapter is about CSS, and accent of the book is on CSS because having good knowledge of CSS will allow you to use other parts with less effort. First chapter - Frontend In this chapter you will learn more about frontend, where it is used, how it’s used and the history. You will also learn about development tools, Web standards, W3C and importance of developer community. Second chapter - HTML In the second chapter you will learn HTML language, as HTML is the basic of the Web. This is an important chapter and you need to understand it completely in order to move on. Along with HTML tags and attributes you will read about coding preparations and use of frameworks. Third chapter - CSS This is the longest chapter of the book and it is about learning CSS language, which works together with HTML. Therefore, the HTML chapter is more like an introduction for the CSS chapter. When you complete this part you should be able to build any kind of layout. 2
Introduction
DOM is explained in the same chapter in order to understand how all of this works in the background. Fourth chapter - JavaScript On top of all this you will learn JavaScript, the most popular scripting language. This chapter explains to you the language basics, key functionalities and detailed description of jQuery framework with examples. Appendix 1 - Graphics editing The job of the frontend developer is to convert visual design into code. Therefore, part of this job includes the ability to edit that design. In order to do that you need to know how to use graphic editing tools. You will read about basic Photoshop functionalities required for this kind of job in appendix 1. Appendix 2 - SEO friendly coding Our code influences to SEO results (Search Engine Optimization) and here can you can find tips how to write SEO friendly code in order to improve those results. Using examples When learning new functionality you will be given a real world example of it. There is programming code available for every example so I strongly recommend creating your own examples while reading the book and comparing the results to the images within those examples. This is the most effective way to learn things. In the code I will be using clear English names for naming classes, elements and everything else so I recommend you do that same and always comment your code the way you can see it in the following examples. That way it will be much easier for you or anyone else to get around inside the code.
Frontend Guide
3
1. Frontend 1.1. Introduction Based on introduction chapter you should have basic idea about frontend and what it actually covers. Now we’ll define frontend more in depth as well as its history and find out the importance of frontend today. In order to understand the frontend area better you should be also familiar with other parts of Web development and fundamental Web principals. I am sure that you have heard many times that Web is “stateless” which means that there is no permanent communication between client and server. Instead of that, communication is only active while the client request isn’t processed. Client request is simply a task that client is asking server to do, and when the server does it, it sends back a response most usually in HTML format. Client request can be a click of a button, click of a link, typing new URL in Web browser etc. The most used Web application architecture is multi layer or multi tier architecture where different layers serve for different purposes. The first layer is the presentation layer and this is the layer we are interested it. It’s available to every user and it serves to display information and also to collect information from the user (Web forms). The Web browser is responsible for displaying (rendering) that presentation layer. The second layer is responsible for business logics and functionality and it’s called application layer (or business layer). Third layer is data layer and it’s usually represented by some data storing structures like databases. These layers function in the following way: By doing some action in the first layer user is sending new request to the server, server finds hosted files mapped via domain. Server completes requested tasks usually by communication between second and third layer, and at the end user gets the response (result of those processes) which is rendered by Web browser. Of course this is simplified because it’s not the subject 4
Frontend
of this book, but it’s good to know what happened in background while you are doing some actions. So based on this you should have a basic idea what are we working with. And that is presenting information and not business logics and databases. There is a smaller part of functionality that is being processed on the client side, so besides only rendering the page, user can do some actions using scripting languages and provide a better user experience. Visual impression is one of the key things of every company, and the frontend developer job is to transform visual design into code. That clearly states why frontend developer job is important. When we look back in history we’ll see that frontend became a separate part of Web development not that long ago. Today everyone is aware that user impression is most important and this makes the frontend developer job highly wanted. In 2001, the Yahoo company had 3000 employees and no one was in charge only for frontend. But in the year 2009, same company had 700 frontend developers. When you are doing some classic application programming you know what kind of platforms your application will run at (you are writing it for that platform), but when it comes to frontend, your code will run on various platforms and browsers and still the result has to be the same. Platforms can include various operating systems (OS) like Windows, Macintosh, Linux, mobile editions and also various browsers with different capabilities like Safari, FireFox, Opera, InternetExplorer, Chrome etc. There are also other things you should take care about besides same look. These things include usability, accessibility, performance, visual design, internationalization, localization, security, mobility etc. The first three things (usability, accessibility and performance) are very important. At the and you should pay attention to rules and recommendations because you can write HTML and CSS code in many ways and have the same result but we can learn the right one from standards and recommendations. Your result can visually look alright even if it’s not valid code (based on standards). However this kind of development certainly isn’t a good thing to do because everyone can see your code. Frontend Guide
5
1.2. Technologies in frontend development Results on the client side are always the same - HTML code, no matter what kind of page are we building (dynamic or static). So the basic technology we are using is HTML language. HyperText Markup Language is the most used format type for World Wide Web documents. It’s used for building page structure and because it’s just a markup language it is very limited in styling options. In order to apply look and formatting to the page we need to use CSS. Cascading Style Sheets is style sheet language which we can use for styling and formatting markup documents. These two technologies are key technologies we’ll be using and they allow us to make any kind of Web page. You have probably noticed that we are not mentioning any kind of functionality and that’s explained before. We’re just displaying information; we’re not processing or generating them. By using these two technologies we can create rich pages up to the point where we can simulate some functionality like show or hide some information. Next technology we’ll be using is most popular scripting language today - JavaScript. Since it is a programming language it can have any kind of functionality you want. It is primarily used to make a better user experience by making the client side more interactive. By combining these three technologies, we can make highly interactive Web pages with a rich user experience using any kind of visual design. Also, it is a small size and very search engine friendly unlike some other technologies like Adobe Flash. Another technology that’s definitely worth a mention is AJAX (Asynchronous JavaScript and XML). AJAX is not part of this book, but it’s good to know that it is used on the client side for sending request and making changes to the page without loading it again. It is using combination of JavaScript and XML (Extensible Markup Language). xHTML (Extensible Hypertext Markup Language) is a variation of HTML language and it belongs to XML languages family. But we can simply say it is the same language and the only difference is in more strict writing rules. In this book we’ll use both of them. 6
Frontend
1.3. World Wide Web Consortium (W3C) W3C (http://www.w3.org) is an international organization for WWW standards like HTML, xHTML, CSS, XML, DOM etc. In this kind of development environment where the development community pushes new technologies forward we need to know what is the current standard, version, specification for it etc. And in the case of WWW that’s what W3C is for. Besides specification for HTML, CSS and scripting languages you can also find some other interesting publication on W3C like semantic Web, Web architecture, Web services, XML etc. Along with specifications on W3C we’re going to use official validation services for HTML and CSS. You can find those on the following addresses: http://validator.w3.org, http://jigsaw.w3.org/css-validator. These validators let us check semantic and syntax of our code based on current specification and standards for different options like CSS version or HTML document type. Use of these services is very straight forward and you can do it in one of the following ways: by directly typing the code, uploading the file or entering the file address. After that, validator will show you the result describing errors or warning if any. Valid code is preferred but it’s not always possible. Validator warnings can be tolerated but errors shouldn’t (except in some special cases). I suggest using both services for all the pages and styles because it is very helpful in learning process. For example you can find unclosed tags, nested tags in wrong places and such. It is common case that a page is valid with dummy data while the frontend developer is testing it but, then when it is in production mode with real data it is not valid. So don’t be surprised if you find many of today’s websites are not valid.
1.4. Development software You can use any kind of editor to write frontend code because the code is not compiled it is just interpreted inside Web browsers. So all Frontend Guide
7
we need to do is run it inside the browser locally or on some server. This means that we can use the simplest editor like Notepad and save it as .html, .css or .js files. If you have already tried writing some programming code inside editors like Notepad you must have noticed how difficult that it is to have a clear code view without some styling and formatting helpers. Therefore I recommend using “smarter” editors with text formatting and coloring. There are plenty of them available today, some of them are commercial and some of them are freeware and that will definitely affect our choice as well as your personal preferences and habits. One of the oldest and very well known is Adobe DreamWeaver (DW), available both for Windows and Mac. It is definitely a good choice because it has been on the market for such a long time. One of the newest is Microsoft Expression Web from Expression package. This package includes other tools like Expression Design. I personally couldn’t switch to Expression Web because it behaved differently than I was used to based on DW. For Mac users one of the most popular options is Coda. Awesome product from Panic company which offers more options than writing the code itself like file transferee, version control etc. Unfortunately it’s available only for Mac platform. Most of those editors have a visual area where you can draw layouts instead of writing it and the editor will handle the code in the background for you. This is not a bad option for beginners because they will have clear insight for what is happening and how the elements are visually represented but it is not an option for serious development. If you ever look for frontend developer jobs, you will always find the following requirement: wanted handmade, pixel precise, table-less, valid and semantic cross browser code (and SEO optimized etc), and this can’t be produced by an editor for you. So that’s the reason why the visual part isn’t used at all in production. Along with code editors you will need graphics editor because one part of the work includes editing visual design. Design itself can be in various formats, mostly as Adobe Photoshop file or as Adobe 8
Frontend
Illustrator file. Photoshop is used for editing raster graphics and Illustrator for vector graphics. Since we’re not making any design we’re just using Photoshop for editing it. Besides Photoshop you could use any of similar freeware tools Web or desktop based like Gimp and Paint.NET. Design can also be pure CSS design without any graphic elements, because CSS has become very powerful language with options for shadows, gradients, etc… But usually that’s not the case and you need to know some graphic editing tool and therefore appendix 1 is dedicated to that.
1.5. Software for testing Since your software can be viewed on any kind of operating system and browser you need to test in all the major ones. Operating systems include Macintosh, Windows and sometimes Linux distributions. Web browsers include Chrome, FireFox, Opera, Safari and InternetExplorer with different versions. When you combine all these options you get pretty large list of possible conditions for your software and testing all that would require lot of time. Also it is difficult to have all those operating systems and different browsers versions only for code testing. Regarding the question “why would we test Safari both on Mac and on Widows when they are the same browser just different edition”, there is a simple answer - it’s not, but these differences are very minimal and rare. There are multiple solutions for these testing problems and I will suggest one that doesn’t require additional operating systems. Choose one operating system by your own preference and browser support for it. Because of the InternetExplorer best choice for single OS would be Windows. After that install five most popular browsers with latest versions. As for the previous versions usage statistics say that only InternetExplorer is important from versions 7 and up. This is because it is part of Windows OS and it doesn’t do auto upgrade in older versions. Frontend Guide
9
Unfortunately version 6 is also still used even thought that is very bad version with lot of bugs. Because of that, frontend developers do not like it. For testing older InternetExplorer versions I suggest using the “SuperPreview� tool that comes with Expression Web. It’s an desktop application that let us simultaneously test different InternetExplorer versions and compare results. Because it is a desktop tool we can test local files as well. To test other operating systems I suggest using some of many available online screenshot tools. One of them is Adobe BrowserLab (https://browserlab.adobe.com) and it can generate screenshots for all key browsers and versions. Besides it you can use some of more simple tools like http://browsershots.org, http://www.browsrcamp.com... where you simply select browser set and type in URL. This choice is simply a personal preference because they are all very similar. The only bad thing is that you need to have and online page in order to test it. But on the other hand when you get to that point where you are testing your code for other operating systems, it is 95% correct and valid so if there are any corrections that need to be made they are all minimal and quick.
1.6. Additional tools All Web browsers have plenty of useful addons but at this point we are interested in the addons that can assist us in Web development. It is good practice is to check your code in other Web browsers only at key points or when the page is complete. Therefore we should decide on a primary Web browser and one of the things that are going to affect that decision is the number of addons for it. My suggestion is FireFox because it has a very large number of addons. My second choice is Chrome whose developer network is rapidly growing and so is the number of addons for it. Based on their functionality we could categorize addons into the following groups: for direct code validation Total Validator, HTML 10
Frontend
Validator, CSS Validator...), for inside page view and editing (CSSViewer, SourceEditor...), for generating screenshots (FireShot), finding fonts (Font Finder) etc… The most helpful one is definitely FireBug. It’s an awesome product from Mozilla company and it is available for FireFox in full version and also for other browsers in light version (http://getfirebug.com/). Firebug combines lot of functionalities and here is quick overview of the key ones:
Inspecting code - visualize page fragments and showing its HTML and CSS. Also telling us where that tag is located inside document tree and shows us inherited styles. We can change HTML and CSS values from the FireBug window. This is the option we’ll be primarily using the most and most of the screenshots in this book are from that mode Debug - allows us to debug JavaScript in console, test code fragments etc Visualize CSS units - overview of margins, padding, offset Show us insight into server requests with speed, data size DOM overview - overview into document tree objects and JavaScript functions for them
These are the key features of FireBug addon, I suggest you install it and try out the different options. It is activated by right clicking on the document or clicking on its icon in the lower right corner. In this book we’ll mostly use it for showcasing errors and CSS and HTML outputs.
Frontend Guide
11
2. HTML 2.1. Introduction Most of the Web documents are in HTML format. HyperText Markup Language is most used markup language developed based on SGML standard in 1991. Markup language means a way of text annotation so it is different from regular text in the sense of syntax. Using HTML we can make structured documents by placing regular text inside HTML elements (tags). In that form text becomes semantic parts like paragraphs, headlines, links, lists etc… Besides text we can also use various objects inside document like images, video, styles, scripts and such. Current HTML version is 4.01, which became a standard in 2000. There is lot of talk about new version of it - HTML 5 and you can read about it later on. xHTML (Extensible Hypertext Markup Language) was defined later in 2000. It is a variation of HTML language and it belongs to XML language family. Basic difference between HTML and xHTML is stricter writing rules. For xHTML it’s necessary to be well structured and that way it can be parser by standard XML parser unlike the HTML which need a specific parser. This way xHTML is more similar to XML and content transformation tools can be used on it, for example to use on different devices etc… Current version of xHTML is 2.0 and next version should be xHTML5 (analog with HTML). Main differences between HTML and xHTML are:
All elements have to be nested correctly. The following example illustrates correct nesting order where first opened tag is last closed. HTML:
12
<tag1><tag2>This is content</tag1></tag2>
HTML
xHTML: <tag1><tag2> This is content </tag2></tag1>
All elements have to be closed. Depending on the type of the element there are two cases: tag can have or not have equivalent closing tag. If it doesn’t have it it’s called empty tag. HTML: <tag>Content xHTML: <tag>Content </tag> HTML: Content <empty_tag> xHTML: Content <empty_tag />
All elements have to be in lowercase. For example <tag> instead of <TAG> or <Tag>
Document has to have root element - it has to start with <html> and end with </html>
According to the W3C announcements xHTML will become part of HTML 5, which basically means that HTML 5 will be upgrade to HTML 4 with new elements but also with rules from xHTML. This way HTML won’t be SGML based any more, instead of that it will be XML based. This is totally reasonable since XML has huge part in Web development today. HTML 5 isn’t out officially, but we’ll use it in this book for several reasons:
Already supported by 4 out of 5 key browsers. Basics are the same, some of the elements are removed and some are added so switching to new version is very easy and it just takes short time to learn new elements (more about those later). Most of the examples in this book are compatible both with HTML 5 and HTML 4 because accent is on CSS and minimal use of HTML.
Frontend Guide
13
Examples which use elements only for HTML 5 are not crucial for understanding basic layout building principles. This means that if W3C has defined new tag with a name “tag1” and previously we’ve have used “tag2” for that, that doesn’t really make much of a difference for us in order to style it and format it from CSS. New elements are mostly things from community network requests and current development trends. For instance <header>, <footer>, <article> are result of blogging popularity, where every blog has those parts. New input formats like datetime, email and range are part of every medium size Web application so now W3C has made new elements for them. These facts are very important for us so we know that W3C listens and sees what we are doing as a developer community and this way language stays up to date with current trends.
Once again, the version of HTML is not crucial in this book because focus is on learning layout construction with right CSS use. Because of that you can use any version of HTML you like.
2.2. HTML tags introduction HTML tag is predefined part of the document that contains some keyword surrounded with “<” and “>”. There are two types of HTML tags: ones with content inside and the empty ones (without equivalent closing tag and content). In this form “<tag>content</tag>” it represents it’s content as a semantic part of document. To put it simply, it tells us “This part of the text is bold”, “This part of the text is italic” etc… Every tag is defined by its own look, structure and behavior. Following example demonstrates use of different tag types:
14
<strong>I am bold text in paired tag</strong> <br /> I am line brake after empty tag (unpaired tag) HTML
<em>I am italic text in paired tag</em> <hr /> I am text after empty horizontal rule tag
The list of HTML tags is pretty long and knowing them all isn’t crucial. The tags that we are going to use most often are explained later on as well as new HTML 5 tags. The only thing that you need to understand at this point is when you place text inside a tag, that text will get predefined functionality and styling of that tag. Functionality is editable up to the some point, but styling is completely editable via CSS. Before we explain the most important tags, you should know two very important things for understanding HTML. Those are element relationship and element structure. These two things are crucial in order to understand how tags will be rendered on the page or accessed from CSS or JavaScript.
Web pages are built by nesting HTML elements and element relationship is based their position inside document tree. Document tree is hierarchical representation of that element nesting. If one element contains another one, it is called a parent element and the other one is called child. If elements are in the same level they are called siblings. There are also ancestors and descendants of an element. For instance: <p><strong>frontend</strong> guide</p> Tag p is parent for tag strong, therefore, tag strong is child for tag p.
Based on their structure elements can be inline or block. Both of them are represented as rectangle areas. Block elements are used for building page structure and they can have height different from their content height. Their width by default is 100% of
Frontend Guide
15
available area. Block elements can contain any other elements and text of course. For instance block elements are paragraphs <p>, tables <table>, div <div> and such. Inline elements don’t have height so they can’t be used in building page structure. Visual representation of inline elements is also rectangular and it has height of content but that height can’t be changed and doesn’t affect other elements. They are mostly used as helper elements in line with the rest of the content. Inline elements can’t nest block elements. Some examples of inline elements are <span>, <em>, <img>... With CSS we can change the structure of elements for example change div tag from inline to block, but that shouldn’t be done especially in this case. We’ll talk more about that later.
2.3. HTML attributes introduction Besides the opening tag, closing tag and the content (for paired tags) tags can also have predefined attributes. Attributes can define the functionality of a tag or give it a specific look or other additional information. The following line illustrates the syntax of these attributes: <tag first_attribute="value" second_attribute="value"> Content </tag>
All attributes are predefined for each tag and we can’t add new ones. We need to be familiar with most of them in order to know the kind of things we are able to do with elements. This results in very large list of tags and attributes for each tag, but most of the attributes are the same for all tags and modern editors help with coding by offering a list of tags and their exclusive attributes. The following example represents the use of attributes to define functionality of anchor tag:
16
HTML
<a href="http://www.google.com" target="_blank"> Open Google in new window </a>
The first attribute href tell us where this link will go based on its value and the second one tells us how this link is going to be opened. Its value _blank is a predefined attribute value and in this case a link will be opened in new window.
2.4. Comments Along with tags and attributes you can use comments inside your code. Comments in HTML start with <!-- and end with -->. Everything inside of that tag is a comment and it is disregarded by the Web browser. This allows for a multiline type of comment which means that you can start the comment in one line and end it in another line. I recommend using them in order to have clearer code so you can get around easier.
2.5. Page structure HTML page structure is simple and it contains following parts: document type (line 1), the root element <html> with document content (lines 2-5) as the “head” part (line 3) and “body” part (line 4). Here is an example of an empty HTML document: 1. <!doctype html> 2. <html> 3.
<head><!-- Head part --></head>
4.
<body>Body part</body>
5. </html>
Frontend Guide
17
Document type has a different syntax comparing to the other tags. It starts with exclamation sign (!) and a doctype keyword and then the document type itself. This tag doesn’t have closing pair. Document type tells the Web browser what kind of document that it is and allows it to render its content correctly. If you exclude this tag the Web browser will switch to “quirks mode” and most probably won’t render the page as it should. In HTML 4 document type has the following syntax: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1strict.dtd"> It is still required in HTML 5 but it has much simpler look: <!doctype html> The head of the document can contain document title (<title>), meta information about the document (<meta>) and external files like scripts (<script>) and styles (<link>, <style>). Meta information is important and it describes the document in more depth with information like document description, author, keywords and such. The webpage’s head part can’t contain formatting tags or content. If you place any of them in the head they won’t be rendered and the document won’t be valid. <title>Frontend guide</title> <link rel="stylesheet" href="screen.css" type="text/css" media="screen" /> <script src="functions.js" type="text/javascript"></script> <meta name="keywords" content="html, css, javascript" />
18
HTML
On the other hand the body part contains everything that will be rendered on the screen. That includes formatting tags, structural tags, text and everything else. In body part you cannot use tags from head part (there are few exceptions).
2.6. General attributes
id This is one of the basic attributes and it provides additional unique identifier for the tag. With this way we can select only that specific tag from the CSS or JavaScript. It can also be used for navigation within the page. You have probably seen this many times with a link taking you to the top of the page (#top). In one document you can’t have more than one id with the same name. Here’s an example of good use of the id attribute: <ul id="navigation"> <li>Item</li> </ul> This is an example of the bad use where you see same id twice: <p id="author">Author</p> <div id="author">Content</div>
class It is similar to id attribute but with one very significant difference. It can be used multiple times with one name within document. This is very important for us to have a uniform look for all the pages. <span class="highlight">Name</span> <strong class="highlight">Content</strong>
Frontend Guide
19
style Assigns set of styles to the element. This is the internal way of assigning styles since styles are defined inside the document and shouldn’t be used often. Instead you should use external styles as separate documents in order to have centralized and reusable styles. Those are two main CSS properties and the third one is inheritance of the styles. What you should know at this point is that inline styles have priority to external styles and that is the main reason why to use them. Oftentimes in development process we’ll use different external resources and might not be able to edit everything and in that case inline styles are good option.
title Adds descriptive information to the tag.
Internationalization attributes
dir – Content direction. It can be ltr (left to right) and rtl (right to left)
lang, xml:lang – Content language like Serbian and English
Event attributes
20
Shouldn’t be used as part of HTML functionality. Instead it should be replaced with some scripting language functionality giving us a whole new set of options. Some of them include: onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmouseout, onkeydown...
HTML
2.7. Basic tags We have already mentioned that there are a lot of tags but since we’re not going to use all of them in development. Therefore we’ll explain just the most relevant ones. Based on their purpose we can categorize tags into the following groups: structural, meta information, text, link, objects (and images), lists, tables, forms and scripts. Tags exclusive for new HTML version are described separately.
2.7.1. Structural tags Used for building large parts of the layout.
html Represents root page element and has to contain body and head tags. It is always first open and last closed. <html></html>
head The head part of the page that contains all page information and external styles and scripts. It has to be opened immediately after html tag and closed before body tag. It can contain only the following tags: title, meta, style, script and link. <html> <head></head> </html>
body Main document body with all the content. It has to be opened immediately after head and closed before html. It can have general attributes. <html>
Frontend Guide
21
<head></head> <body></body> </html>
div (division) Represents a large block of HTML code. For example that can be site header, navigation, comments part etc… It can have general attributes. <html> <head></head> <body> <div> </div> </body> </html>
span This is the only inline element in the category. It doesn’t have any effects or formatting by default so if you use it without any styling it won’t show any result. It can contain general attributes. <html> <head></head> <body> <div> <span></span> </div> </body> </html>
2.7.2. Meta tags Additional information about the document or links to external resources. 22
HTML
DOCTYPE – Document type, explained earlier. <!doctype html>
title – Document title, has no attributes. <head><title>Title here</title></head>
link Link for external resources. Usually it’s used for assigning CSS styles to the page. Along with general attributes it can have: o o o o
href – Resource location. type – Resource MIME type. rel – Resource relationship for the document. charset, hreflang, rev, media
<link href="style.css" rel="stylesheet" type="text/css" />
meta Additional page information which only requires the attribute content, other optional attributes are: o name – Tells what is that meta information like: keywords, description, author… o http-equiv, scheme. <meta name="author" content="Dejan C" />
style Assigns internal CSS style exclusive for that page, while external styles can be applied to multiple pages, the only required attribute is type and it defines style type. Optional attributes are media and title. <style type="text/css"> * { margin:0; } </style>
Frontend Guide
23
2.7.3. Example 1 â&#x20AC;&#x201C; Empty HTML page Using elements learned so far we can make empty HTML page with correctly defined header, document type and loaded external documents. <!doctype html> <html> <head> <title>Frontend guide</title> <link href="style.css" type="text/css" rel="stylesheet" /> <script src="functions.js" type="text/javascript"></script> <meta name="keywords" content="html, css" /> <meta name="author" content="Dejan C" /> </head> <body> <div> Simple <span>HTML</span> page! </div><!-- div --> </body> </html>
Figure 2.0: Simple HTML page
We can create this page in one of the following ways: Selecting create new HTML page in any code editor. That way editor will create a file for us with the correct extension which can be run immediately. Or we 24
HTML
can use any text editor and save our code as an .html file. The result will be the same and to view it simply open it in any Web browser. 2.7.4. Text Elements for styling and formatting text.
p – Text paragraph with block structure. Can have general attributes h1, h1, h3, h4, h5, h6 Headlines with different priority. H1 has highest priority and h6 has the lowest one. Can have general attributes strong – Bold text with inline structure. Can have general attributes em – Italic text with inline structure. Can have general attributes blockquote Large quotation with block structure. Can have general attributes, optional attribute is cite cite – Small quotation with inline structure pre Preformatted text with block structure. Usually used for displaying code blocks code – Similar as pre, just it has inline structure br – Line brake. This is an empty tag, it can have general attributes
2.7.5. Example 2 – Text formatting Now to edit first example with some text and text formatting tags add the following code to the body tag. <div id="top"> <h1>FrontEnd guide</h1> <strong>Complete guide for HTML, CSS…</strong>
Frontend Guide
25
</div><!-- top --> <div id="content"> <h2>Headline here</h2> <p>Paragraph here with long text<br/> in two lines and also <em>italic letters</em></p> <h3>Nikola Tesla</h3> <blockquote> The scientists of today think deeply instead of clearly. One must be sane to think clearly, but one can think deeply and be quite insane. </blockquote> Simple text and <span>inline element</span> </div><!-- content -->
If you open up this example in the Web browser you will get simple HTML page with line brakes for the text using block structure tags.
Figure 2.1: Default styling for text elements
As explained before block elements take full width of its container and it doesnâ&#x20AC;&#x2122;t matter how much content it has. So if we use for example h2 tag everything that we write after that will be placed 26
HTML
under it and not next to it. You will also notice that most of the elements already have some predefined looks like font size, line height etc. This is the default styling and it is a bit different in every browser. In order to change this we’ll use CSS reset later on.
2.7.6. Links The most common way of navigation between the pages.
a Anchor tag, represents the link to another page, any Web location or part of the page inside the same page. It can have general attributes as well as the optional ones like: href – address of another page type, rel, rev, charset…
2.7.7. Images and objects Using multimedia content inside of Web pages.
img Represents an image inside the Web page. Required attributes are src (source of the image) and alt (alternative text to be shown if the image is not available). It can also contain general attributes. For building the page layout we’ll rarely use images from HTML. Instead we’ll use backgrounds from CSS and images in HTML should only be there as part of the content. object, param – Used for adding multimedia objects into the pages and setting them up map, area – Used for mapping a specific area of the Web page
Frontend Guide
27
2.7.8. Lists Ordered and unordered data sets.
ul – Container for the unordered list. Items inside of the ul set have to be contained by li tags and that’s the only tag that can be in it. It can have general attributes ol – Same rules as unordered list just this is an ordered one with numbers li – List element with block structure. Can have general attributes dl – Definition list, it contains dt as definition title and dd as definition description
2.7.9. Example 3 – Multimedia and lists After the </div><!-- content --> in the previous example add this code: <div id="bottom"> <dl> <dt>HTML</dt> <dd>HTML is markup language for building web pages</dd> <dt>CSS</dt> <dd>CSS is stylesheet language for styling web pages</dd> </dl> <img src="image.gif" alt="Alternative text"/> <ul> <li><a href="#">Dummy link</a></li> <li><a href="http://google.com"> Link to Google</a></li> </ul> <ol> <li><a href="#top">Top of the page #top</a></li> <li><a href="#content">Middle of the
28
HTML
page #content</a></li> <li><a href="#bottom">Bottom of the page #bottom</a></li> </ol> </div><!-- bottom -->
If the page doesn’t have vertical scroll yet, you can test the navigation by zooming the page with CTRL + SCROLL and then by clicking on the links. Id attributes are accessed by # sign.
Figure 2.2: Multimedia and the lists
Exercise: Run this file in HTML validator (select HTML 5 as document version). After that add some random text between ul and li and run it again. Analyze the result. 2.7.10. Tables Representation of tabular like data structures.
table - opening and closing tag tr - table row td - table data. Interception of the row and column
Frontend Guide
29
th - header of the column thead, tbody, tfoot - header, body and footer of the table caption - table caption that describes the table colgroup, col - groups of columns
Before the Web 2.0 revolution most of the Web pages where built using the tables. This means that tables where used for building page structure like header, footer, sidebar and everything else. To build a single table it takes plenty of tags and attributes and that resulted to large pages sizes, bad code and even more tags than content. We had to have lot of tags just to format small parts of content. It wasn’t until around 2002 when Web 2.0 revolution eliminated many bad practices, including using tables for building page structure. That’s where CSS came in. Sure, tables remained but now they are used for their original purpose, which is displaying tabular data resulting in cleaner code with more styling and formatting options. The following example illustrates the difference between table structure and div structure (the result won’t be the same because the CSS is missing, this is just HTML demonstration). Table example: <table width="500" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="245" height="250" valign="top"> <table width="100%" cellpadding="0" cellspacing="0"> <tr> <td width="250" height="250">Column 1</td> </tr> </table> </td> <td width="250" valign="top">
30
HTML
<table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="250" height="250"> Column 2</td> </tr> </table> </td> </tr> </table>
Div example: <div id="content"> <div id="left"> Column 1 </div> <div id="right"> Column 2 </div> </div><!-- content -->
The difference is obvious and you should avoid doing it as much as possible.
2.7.11. Forms Forms are a very important part of HTML and they let us send different information to other Web pages. ď&#x201A;ˇ
ď&#x201A;ˇ
form - start and the end tag for the form. Required attribute is the action attribute which tells the form where to send its data after the submit action. It can also have general attributes and a very important one is method which defines the way how is the data sent (post, get, put and delete) input - Element of the form that holds some value. Can have general attributes and the optional ones are checked, src, alt, disabled, readonly, typeâ&#x20AC;Ś Type attribute defines how this element will look like and what kind of
Frontend Guide
31
information can user place in it. It can be text field, password field, checkbox, radio button etc textarea - textual field in multiple rows. Required attributes are row and cols select, option, optiongroup - Drop-down list with select options. Can have general attributes and optional ones: size, multiple, selected button - button with content value label - Label for one of the form elements. Its attribute for should be the same as the element id attribute fieldset - part of the form with grouped options legend - Explanation for the fieldset
2.7.12. Example 4 - form
We’ll add a simple form to the page we built so far (example 3). Based on the value of action attribute the form will send its data to the made up page script.php. Add the following code at the end of </div><!-- bottom -->. <form action="script.php" method="post"> <fieldset> <legend>Personal data</legend> <div> <label for="name">Name: </label> <input type="text" id="name" name="name" /> </div> <div> <label>Gender: </label> <input type="radio" name="g" value="M" /> M <input type="radio" name="g" value="F" /> F </div> <div> <label for="address">Address: </label> <textarea rows="4" cols="6" name="address"> </textarea>
32
HTML
</div> <div> <input type="submit" value="Send" name="send" /> <input type="reset" value="Reset" name="res" /> </div> </fieldset> </form>
Figure 2.3: Form
At the moment this example has pretty bad styling and that’s the default look. Later on we’ll use CSS in order to style it better.
2.8. Special characters Inside HTML code we can use special characters to show some special letters, signs etc… These characters are used only inside the content part with the following sytax: &character_name; Name of the character is predefined value and most of the code editors will offer us a list when we start typing it. Here is the list of couple of characters used a lot: Frontend Guide
33
&raquo; - » &laquo; - « &copy; - © &gt; - > &lt; - <
Special characters are also used as a part of the design like extra details to the text and such. We can also use them if we want to show the user some HTML tags and not to render them. For example if we want to show span tag we can’t write <span> since Web browser will interpret that. Instead we’ll write : &lt;span&gt;
2.9. HTML 5 By the time of this book HTML 5 wasn’t released officially but we are going to use it for several reasons as explained earlier. Scripting languages provide us an opportunity to create a better user experience and more interactive Web pages. HTML 5 will bring that to a whole new level and it is good to know all of its new features so we can be aware of all the new cool stuff we can do with it. There are lots of new elements added and also a lot of old elements that have been removed. With the new ones we can do things like manipulate audio, video, graphics etc… The final specification of HTML5 is still a work in progress, but we have a good idea of what new tools will be included. With that advanced knowledge Web browser companies have already implemented some of those new features. In all, one thing is for certain; when W3C finalizes the HTML 5 specification web pages will feel much richer in functionality and the WWW (World Wide Web) will be very different from what we use today. It is very important for us developers that the W3C continues to monitor what we are doing since we are the ones who are creating the next trend in Web development. It is our input that is building the specification for the next version of HTML today. Another important 34
HTML
thing has occurred during this time, in the long period from the release of HTML 4 to the announcement of HTML 5, the markup language didn’t change much and in order for the web to move forward users were looking for alternative ways to enrich a web browsing experience that didn’t include things like watching videos and listening to music, that required browser plugins like Adobe Flash and later Microsoft Siverlight, but now HTML is going to become independent by offering built in solutions for all kind of things, including enhancing the multimedia browsing experience.
2.9.1. New stuff
Not SGML based anymore and new parsing rules Using SVG format for displaying vectors Using MathML language for displaying mathematical notations New elements like: article, aside, audio, canvas, figure, footer, header, nav, progress, ruby, video… New form controls like: date i time, email, url, search, color New attributes New form methods: PUT and DELETE Removed elements: acronym, applet, basefont, big, center, dir, font, frame, frameset, noframes, s, strike, tt, u Lots of new stuff from DOM, JavaScript API and CSS (more about that later)
2.10.
HTML Frameworks
When writing HTML you can use various frameworks the same way as any other programming language. However, in this case it is a bit different sense. When writing HTML and CSS code we will write the Frontend Guide
35
same things many times (same list type, layout, form etc…). HTML frameworks usually combine this list of common elements and make a good starting point for building new pages. Most of them have CSS reset in order to set all default elements to the same value so they look the same in every browser. This provides a good starting point where everything is setup for us and we can use one of many predefined sets of elements or styles and this can really speed up our development process. By having all of this ready we can make two column, three columns layouts etc; and not to be concerned if it is going to work correctly in every browser (since they are all well tested). There are both good and bad sides to HTML frameworks:
On the bad side, we need to learn them first. The framework author is responsible for naming things like classes and elements and we need to use them as defined. Frameworks can limit things up to their level and we may not be able to use them for some non-standard layouts. As a beginner you won’t learn much by using these “ready to go” elements. Instead you should write your own from the scratch.
On the good side, when you get to know them you will make new pages much faster. For beginners they provide a level of safety and by using them your code will probably look good everywhere. By working with a designer you can pick a framework and tell him or her to build their design based on the framework. Most of the frameworks usually come with popular JavaScript dependencies so you won’t have to worry about that as well.
Some of the popular frameworks include BluePrint (http://www.blueprintcss.org/), 960 GS (http://960.gs/) and YUI 2: Grid CSS (http://developer.yahoo.com/yui/grids/)… Over the time you may find frameworks to be uninspiring or unnecessary. To decide on a particular one you will need to download it and test it for a while. All of them provide nearly the same thing - a ready to go document 36
HTML
where you wonâ&#x20AC;&#x2122;t need to create any startup settings; chock full of reusable elements. When you spend some time coding you will probably make some kind of mini framework for your personal use. Within this book we wonâ&#x20AC;&#x2122;t use any frameworks because we want you to learn it. In the end, you should be able to build any kind of layout without any assistance. You will realize at that point it is irrelevant if you are going to use some framework later on or not. Exercise: Download a BluePrint framework, unpack it and apply its styles (screen.css, print.css, ie.css) to our previous example. Analyze the result, compare your page in different Web browsers and take a look at BluePrint demo files.
2.11.
Coding preparations
Based on my experience I would like to give you few preparation tips before you start the coding process. At this point I suggest just reading over them and when you get to work on a real job you might get back on this chapter and read it in more depth. First of all you would need to check if all the design files are in the suitable format with all of the necessary information. Most suitable formats are the ones where you can edit parts of the design separately by using layers. Some of the popular design application files include Photoshop and Illustrator. Less suitable formats are flatfile images like JPG or GIF, where we have all of the design but we canâ&#x20AC;&#x2122;t select the text size, font or any other part of the design independently. This makes our job more difficult and time consuming. When it is possible you should always work with the more suitable formats. Sometimes even if design is in the suitable format it might not have all of the information we need. For instance, your designer may not have created alternative designs for situations like link hover or click states, typography rules for things like headings, lists and other common HTML elements. All of this is the designers part of the Frontend Guide
37
job and you should make sure they deliver everything you need so you can complete your part of the job. The second thing you need is a simple work plan. This includes planning how to code different part of the design, what kind of images to use etc. I think of this as a fairly short part of the process and not required in all of the situations; however, it often results in better code quality. Making a work plan means you need to have all of the pages outlined. Now you will have the complete image of what needs to be done. All of the pages can be grouped by their functionality. For example, if there is a blog part or forum part, both of these parts will have similar page structure. For each of the groups, we are interested in the following: identifying repeating element groups and single elements. Element groups are the groups of the single elements and that whole group is usually repeated on several pages. For instance, groups of elements can be site header or footer. Element group contains single elements inside. Single elements inside header can be headline, search etc… For both of these groups (element groups and single elements) you should identify the following things:
38
Elements that repeat. There are usually lots of repeating elements because uniformity of design looks good. Single elements from this category mostly are things like: headlines, links, lists, forms, buttons… and element groups like: header, footer, sidebar. Similar elements. There are lots of these elements as well for the same reason; creating uniformity. It is easier for the designer to adjust part of the design instead of giving it a completely new look. An example of similar elements could be things like normal articles and featured articles. Specific elements. There are few of them and they are mostly used to make some part of the design stand out. An example of a specific element might be the RSS subscribe part, Twitter part, some special offers, or promotions. HTML
Repeating elements speed up our coding process big time, because when we finish the first page and if the code is good and reusable we can just copy it into the proceeding pages because one page usually contains up to 70% of the same or very similar elements; so coding additional pages takes less time.
2.12.
Conclusion
Up at this point you have finished the HTML chapter where you learned language basics and got to know tags and attributes. Since the goal of this book isn’t learning HTML language I haven’t mentioned all of the elements and I haven’t described everything about each of them. Instead only the key ones have been mentioned and that is all you need in order to understand how Web pages are built. On the internet you can find very good references about HTML with lot of details so if you are not very good at it I suggest reading some of those resources. For you it is important to understand what HTML tags are, what are attributes learn basic HTML tags (explained in this book) and understand how they can be based on their structure and element relationship. That way we’ll know how they will behave and what can we do with them. After that learning a new tag is a piece of a cake. At the end of this chapter, I have defined what HTML frameworks are and gave you a couple of coding preparations tips. The next chapter is about CSS and you will learn how this unorganized set of elements that make HTML page can become well structured page simply by applying CSS rules.
Frontend Guide
39
3. CSS 3.1. Introduction Cascading Style Sheets (CSS) is a language for styling and formatting markup documents like HTML, XML, SVG, by adding style rules to the document semantics. This means that when we create a semantic part of the document, like making some part of the text a paragraph, we can later access it via selectors and change its looks or structure. Basic CSS functionality includes:
Separation of the content from the styling where the markup document will have only elements for representing content and no styling elements. This way we get more structured documents Using this idea we can apply the same style to multiple pages to give us a uniformed look and style and control where we need to edit just one file in order to change styling for all the pages A markup document can be represented in various ways and we can have separate styles for all of them. For example we can have different styles for printing document, displaying it on mobile platforms and so on
You can get a pretty good idea how CSS works just from its name. Where the CSS rules will be applied is based on priority and the priority is determined based on element DOM position and used selectors. The word “cascading” can describe this idea pretty well. One element style will inherit all of the previously defined styles for it and it can use all of them and define new ones just for him and his descendants. We’ll talk more about this later. As for HTML, W3C is responsible for CSS specification. CSS Internet media type (MIME) is text/css.
40
CSS
3.2. History Style Sheet languages are designed to give web pages a uniform appearance. In the early days of HTML, designers styled the page, at great cost of their HTML, by defining everything inside the page. That resulted unsightly page complexity, difficult maintenance and poor user control. On the top of all this, different web browsers rendered these pages differently and there wasn’t much that users could do about it. It wasn’t until CSS was born when concept of separating the content layer, which displays all the data, and the presentation layer, which defines how that data is displayed, was put into play. In order to expand the presentation layer’s possibilities, in 1994, the W3C had chosen two out of nine Style Sheet language propositions. Those two became the foundation of CSS language; Cascading HTML Style Sheets (CHSS) and Stream-based Style Sheet Proposal (SSP). CHSS was proposed by Hakon Wium Lie and SPP was proposed by Bert Bos. They ended up creating a new standard together called CSS. Lie and Bos presented the finalized CSS standard during a conference in 1995 and that’s when the W3C came in. In 1996 CSS was officially out as well as the first specification for it. Until then the W3C is in charge for CSS and the current version is version 3.
3.3. Syntax CSS language has simple syntax and it uses grouped English words with additional characters to make statements. A statement can be presented as two types, an “at” rule or a rule set. Along with statements a CSS document can also have comments. Let’s take a look at the following code fragment: /* This is ”at” statement */ @import url(reset.css); /* This is rule set */ Frontend Guide
41
p { color: red; } We can identify the following things inside that code fragment:
Comments start with /* and end with */ and everything inside of that is comment which Web browser disregards. This is the multiline comment type and it can be opened in one row and closed in another one. A good rule of thumb is to group similar set rules and mark them with comments; this way, in CSS, you will usually have typography definition, column definition etc.
“At” rules are called such because of the @ sign which dictates sending instructions directly to the CSS parser. After @ sign there’s an identifier like import and media are based on it and “at” rule can have declaration block after it, containing declarations or just line ending with semicolon (;) character. “At” rule in our example demonstrates import command which will add some styles to the existing style @import url(reset.css); This is very useful thing and this way we can use multiple styles inside one style like most usually CSS reset. The following example is also “at” rule but now it has declaration block and rule set in it only used for printing pages. @media print { body { font-size: 12px; } }
42
CSS
Inside of this “at” rule we have one rule set. That rule set has identifier (body) and declaration block with some declarations. Each declaration has property and value separated by colon and every line is finished by semicolon. body { font-size: 12px; } In this rule set (or just set) we have one selector for the body tag and everything inside declaration block will be applied to that selector - tag. In this case all the text inside of body will be 12px large. So selector tells us where to apply the styles inside declaration block. Selector can be tag name, id, class etc… In order to control where is that style going to be applied, selectors can also have a pseudo class. Pseudo classes can be :hover, :first-line, :first-letter etc… Here’s the complete rule set syntax. selector [,selector, ...][:pseudo-class] { property: value; [property: value; ... ] } blockquote, p:first-line { font-size: 120%; font-style: italic; }
There will be more about selectors, properties and value later on. For now it is important for you to know these statement types and everything inside of declaration block, is applied to the selector. Frontend Guide
43
White spaces don’t affect CSS syntax. It is only important to have start and the end of declaration block (or just block), end of the line etc… The following two examples are the same, just written differently. form { padding: 10px; } form { padding: 10px; }
3.4. Applying styles to the page There are three ways to apply CSS style to the page and based on the situation we’ll choose one of them:
Externally - The most common method where case styles are in a separate document and one style can be loaded into multiple HTML files. This allows you to change the look on every page when editing one style document. <link href="style.css" type="text/css" rel="stylesheet" />
Internally - You can define a style inside of the head part of the document. In that case that style will be for that page only. This is mostly used within some page plugins, scripts etc… where the author wants to style just couple of elements.
In line - We can assign an inline style for every element inside body tag by defining style attribute. This is the rarest type of adding styles and it should be avoided. At the same time it has one important advantage over to other ways of adding styles and that is priority. Styles defined this way will have top priority and
44
CSS
will overwrite other styles. So the only reason to use it would be just that; situations where we don’t have control over something and we have to do it this way. <p style="color:red;">In line style</p>
3.5. Example 5 - Adding styles to pages Before we continue with CSS, let’s add a basic CSS style to our HTML page and the other elements. If you have competed last exercise from the HTML chapter you know how to apply a style to the HTML page. Now let’s create new style named style.css and load it into the document head like this: <link href="style.css?v=1" type="text/css" rel="stylesheet" /> That style will have the following code: /* Name: Example 5 Author: Dejan Version: 1.0 */ body { color:black; font-size:12px; } /* Typography */ h1 { font-size:26px; color:gray; } Frontend Guide
45
h2 { font-size:20px; color:gray; } /* Forms */ form { font-size:14px; color:red; } The result is obvious and the CSS code is very simple. We have changed colors and font sizes for several elements.
Figure 3.1: Applying style to the page
Exercise: Add style for the rest of the page elements.
3.6. Document versioning In example 5 you will notice that in the style location value we have added a part that represents file version href="style.css?v=1". This is very handy options and it is easy to use. As Web browsers cache styles, scripts, images and the rest we 46
CSS
can use this additional parameter to add something unique to the style. That way we can be sure that Web browser will re-load our file instead of using the cached version. Web server will ignore that parameter and just return style.css <link href="style.css?d=15062011" type="text/css" rel="stylesheet" />
In previous example I have used version as additional parameter but basically it can be anything like a date etc…
3.7. CSS selectors As CSS adds some properties to HTML elements by giving those properties values, we need a way to tell the Web browser where exactly to apply it. That’s what the selectors do, they select an element or group of elements where the style should be applied. Selectors can be categorized in the following way:
Type selector Universal selector Class selector ID selector Attribute selector Pseudo selector Combinators Web browser selectors
By combining different selector types you can access any kind of element or group of elements. For instance let’s take the situation where we want all the text to be colored red. We can make that definition simple by taking color as property and red as value. That way we get the following peace of code. Frontend Guide
47
selector { color: red; } In order this to work we need to define that selector and for that we need to know HTML tags, described in HTML chapter. If some property should be applied to the whole document usually we’ll assign it to the body tag because that is the root tag for the content. Changing that we get the following code: body { color: red; } Based on this example you should realize that every tag inside the body can be selector. That type of selectors is called “type selector” because we are applying style to the specific element type.
3.7.1. Inheritance Previously we have discussed how to access any element with the type selector and explained that the selector domain is based on the fact where is that element located inside the DOM tree. If we apply a style to each element we would end up with a huge CSS file and a lot of repeated styles for the same element types. To avoid that mess we can use one of CSS’s most powerful properties, inheritance. Elements of the same type inherit all the styles of their ancestors. In order to make this clearer we’ll revise element relationship from the HTML chapter. Based on its position inside the DOM element it can be in one of the following forms (root element is an exception):
48
Parent - if element A contains element B then element A is the parent of element B. Root element has no parent Child - If element A contains element B the element B is the child of element A CSS
Descendant - Element B is the descendant of element A if element B is the child of the element A or element B is the child of some element C which is descendent of element A Ancestor - Element A is ancestor of element B if element B is descendant of element A
It is very important to notice the difference between a child and descendant. In a hierarchy model (DOM tree) a child can only be in the second level below while the descendant can be in any level below.
Figure 3.2: Partial document tree for the example 4
In order to understand this better let’s take a look at the document tree of our page from example 4 (figure 3.2). A document tree is an effective way to illustrate an HTML page’s structure. Frontend Guide
49
Exercise: This document tree doesnâ&#x20AC;&#x2122;t include all of the example 4 elements; therefore you should add the missing ones. Now when we know element relationships we can define inheritance functionality. If an element has the same ancestor type it will inherit all of their styles. Take a look at the following page structure:
Figure 3.3: Inheritance document tree
Here we have div type elements. If we assign the red content color only to the last one (on the right) it will affect only its content and not the previous div content. If we assign italic text style to the second div it will affect its content and the content of the next div, so now the last div will be both red and italic. Finally if we assign bold text style to the first div then its content will be bold, second div content will be bold and italic and the last div content will be bold, italic and red. Here is HTML and CSS of this example: <body> <div> Content 1 <form> <div> Content 2 <blockquote> <div>Content 3</div> </blockquote> </div> </form> </div> </body>
50
CSS
body div { font-weight:bold; } body div form div { font-style:italic; } body div form div blockquote div{ color:red; }
Figure 3.4: Style inheritance result
To see the result open it in the Web browser and to see which properties are inherited inspect it with FireBug. FireBug will strike over inherited properties and show you where they are inherited from (inherited from [element name]). So the last div will have the same style as if we added those three properties just for it. Frontend Guide
51
3.7.2. Prioritization In the previous example you have seen how inheritance works and that it is pretty simple, all inherited styles are combined. This is very useful functionality that helps us write better code and reuse it. But what happens if you inherit the same property, which value will be used? That is where prioritization comes in. In the previous example letâ&#x20AC;&#x2122;s say that first div content color will be green, second will be blue and third can stay red. Our code will look like this: body div { font-weight:bold; color: green; } body div form div { font-style:italic; color: blue; } body div form div blockquote div { color:red; }
Figure 3.5: Overwriting same inherited values
52
CSS
If we open this in the Web browser we’ll get the expected result; every div content will have different color and the FireBug will strike trough overwritten values. As you can see on this example we ended up with the desired result by naming all selectors in full path, from the first element to the last one. Now we’ll remove some of them and see the result:
If we remove the form selector from the second set (form div), the first and second div color will be green and the third one will stay the same. body div form div { font-style:italic; color: blue; } Replace with: div { font-style: italic; color: blue; }
Figure 3.6: Selector priority by the “strength”
Frontend Guide
53
This is happening because CSS will use better defined selectors. Single selector (div) will be replaced with selector combination (body div) because that combination defines that selector better and it doesnâ&#x20AC;&#x2122;t matter if that selector was defined later in CSS document. ď&#x201A;ˇ
If we continue to edit our example and remove body from the first set, weâ&#x20AC;&#x2122;ll get two sets only using the div selector but with different values. In this case, when selector are the same browser will use the one later defined in the CSS document (the document goes from top to bottom). div { font-weight:bold; color: green; }
Figure 3.7: Selector priority by position inside the CSS document
A common mistake made by the beginners is trying to change some value and accessing it using just by one selector. As you 54
CSS
have seen in the previous examples that value won’t be applied and you have to better define the selector by naming all the key elements before it.
3.7.3. Type selector We have seen this selector before and this is the simplest selector type where we name just the HTML element type. input { /* this rule will be applied to the all input type elements */ }
3.7.4. Universal selector This selector is marked with “*” sign and it selects all of the descendant elements. It is very useful for things like resetting all of elements, etc. * { /* Selects all of the elements */ }
3.7.5. Class selector This selector is for all HTML elements with that class. For example if we have <span class="highlight"> we can select it with the class selector and it won’t select all of the span elements, instead it will just select those with that class. .highlight { /* Elements with this class */ }
Frontend Guide
55
As you can see class selector starts with a dot followed by the class name. Since you can use one class name multiple times within the document, we can access different element types this way. For example <span class="highlight"> and <div class="highlight"> can both be selected with this class selector.
3.7.6. ID selector This is the selector for HTML elements with an ID attribute. Unlike the class selector which can select multiple elements, the ID selector can select just one element because the ID is a unique identifier. It starts with a “#” sign followed by the id name. #header { /* Selects single element with id attribute */ }
3.7.7. Example 6 - ID and class selectors ID and class selectors are the most used selectors alone or in some combination. Previously we have defined their differences now we’ll see an example how to use them and which one takes precedence if they both define the same property; which one has the priority. Let’s make new HTML page with the following HTML and CSS code: <div id="header" class="red"> headline <span class="red big"> goes here</span> </div><!-- header --> #header { color:green; } 56
CSS
.red { color:red; } .big { font-size:120%; } For one div (header) we have assigned an id and class selector and in its content we have added a span with two classes.
Figure 3.8: ID selector priority to class selector
In this example you should notice the following: ď&#x201A;ˇ ď&#x201A;ˇ ď&#x201A;ˇ
We can use the same classes for different elements Multiple classes are listed one after other with an empty space between them When an element has id and class with the same property (in this case color), id will have the priority over the class. You can see this in the previous example where not all text is in the red color although it has class red. Notice that FireBug strike trough the value red and tells us that the Web browser will use value green
Frontend Guide
57
Let us take a look at another example: <div id="content"> <h2 class="blue">headline h2</h2> <h3 class="blue">headline h3</h3> <span class="one two three"> Text one here</span> <span class="one three"> Text two here</span> </div><!-- content --> h2.blue { color:blue; } span.one.two { font-size:150%; } We have assigned class blue both for h2 and h3, but it wonâ&#x20AC;&#x2122;t be applied on h3 because we defined blue selector exclusively for h2 elements (h2.blue).
Figure 3.9: Multiple classes
58
CSS
The next thing what should be noticed is how we access multiple classes. If we want to access element which has classes .one and .two we will write both of them without spaces (.one.two) and this is totally different from case when we write .one .two - with space, because in that situation we would access only class .two which is the child of the class .one.
3.7.8. Attribute selector This selector finds all elements with attributes and/or its values equal to the ones we are looking for. This way we can select elements if they have a specific attribute or not and if they do we can compare its value to a defined string.
element[attribute] This is the simplest kind of attribute selector where we test only if an element has a specific attribute or not. For example if we want to select only h1 headlines with title attribute we’ll use: : h1[title], or if we want to select any element that has title attribute we’ll use just: [title]
element[attribute="value"] Similar to the previous example we can select elements with specific attribute and we can also check that attributes value. This can be applied to the all attributes including the general ones like id and class, so here is an alternative way to select a class or id. span[class="blue"] div[id="header"] But since id and class selection is the most often selection they have unique short selectors as we have seen before:
Frontend Guide
59
span.blue and div#header
element[attribute~=value] Selects an element whose attribute value is a list of the words separated by space and one of those values is equal to the one we are looking for.
element[attribute |= value] Selects an element whose value starts with a string we are looking for or starts with that string followed by “-“
element [attribute ^= value] Selects an element whose attribute value starts with a string we are looking for.
element [attribute $= value] Selects an element whose attribute value ends with the string we are looking for.
element [attribute *= value] Selects an element whose attribute value contains the string we are looking for.
Exercise: select the following elements based on their attributes:
All links going to the URL www.google.com All paragraphs whose title contains the word “guide” All links whose hreflang attribute can be “en” and “en-US”
3.7.9. Pseudo selectors With pseudo selectors we can select elements with more precision based on various parameters like their DOM position or their actions etc. We can group them as: 60
CSS
Pseudo classes They include: structure pseudo classes, link, user action pseudo classes, UI state pseudo classes and negation pseudo classes. They are called pseudo classes because by using them we can select groups of elements based on their position, property, value similar as assigning them specific classes.
Pseudo elements Unlike the pseudo classes, pseudo elements select only precisely defined content values and access them as a separate elements even if that is all part of one element content.
3.7.9.1. Structure pseudo classes This selector type allows us to access different elements based on their DOM position, something we usually cannot access using just simple selectors. While calculating element position, for example inside of a parent, element content doesn’t count, nor do some other things that are not part of DOM tree. Structure pseudo classes include: element:root Represents the first element inside the document, usually that is html tag. element:nth-child(an + b) Very useful pseudo class which allows us to select a specific child/children by following some rule or using predefined values like odd and even for every second element (for example row in the table…). Let us take a look at the following examples:
Select only one element tr:nth-child(0n + 5) /* fifth table row */
Frontend Guide
61
tr:nth-child(5) /* same */ ď&#x201A;ˇ
Select every second element tr:nth-child(2n+0) /* even table rows */ tr:nth-child(even) /* same */ tr:nth-child(2n+1) /* odd table rows */ tr:nth-child(odd) /* same */
ď&#x201A;ˇ
Select any group of elements tr:nth-child(10n) /* 10., 20., 30. row... */ tr:nth-child(10n - 1) /* 9.,19., 29. row... */
element:nth-last-child(an + b) The same as the previous example but in this one starts counting from the last element. It can also use predefined values like odd and even. element:nth-of-type(an + b) Same as :nth-child() but this way only same type children are selected. For example if we want to select every second image we can write: img:nth-of-type(2n) element:nth-last-of-type(an + b) The same as the previous example but in this one counting starts from the last element. element:firts-child(), element:last-child(), element:first-of-type(), element:last-of-type() Equivalent to the previous selectors with the value 1, these are just new names in order to remember and write them easier. element:only-child() Element that contains only one child.
62
CSS
element:only-of-type () Element that contains only one specific child type. element:empty() Empty element, no text or children.
3.7.9.2. Link pseudo classes element:link and element:visited Represents the link states - visited and not yet visited. This depends on the Web browser what the Web browser thinks of as a visited link. For example we can color all of the visited links into the color gray: a:visited { color: gray; }
3.7.9.3. User action pseudo classes Depending on the user actions elements can be in one of the following states: hover, active and focus. With CSS we have the possibility to style all those states. Also one element can be in multiple states. ď&#x201A;ˇ
element:hover Element state activated on the mouse hover. Mostly used for links, form controls etc
ď&#x201A;ˇ
element:active Element state activated by the user and their action on that element like click of a button
ď&#x201A;ˇ
elemenat:focus Focused element like an active form field for typing
Frontend Guide
63
3.7.9.4. Example 7 - Element states In order to understand element states better weâ&#x20AC;&#x2122;ll make a example with a button and text field and style them differently according the their states. This is just the code fragment that would go inside the actual form because form elements canâ&#x20AC;&#x2122;t be outside the form tag. <input type="text" value="Text here" /> <button>Button</button>
input { border:1px solid green; } input:hover { border:1px solid blue; } input:focus { border:1px solid red; } button { background:red; } button:hover { background:green; } button:active { background:blue; } Notice: In order to see active and hover states inside the FireBug you need to select them from the style tab options (as on the image).
64
CSS
Figure 3.10: Element states
3.7.9.5. UI state pseudo classes This includes the following pseudo classes elemenat:enabled, elemenat:disabled and elemenat:checked and every element can be assigned with this state if it can be in that state and if there was an action for it. Exercise: Edit the previous example (number 7) with new elements which can have disabled and checked states. Take a look at HTML chapter to see which elements those are. Finish it off by styling those states using pseudo selectors.
3.7.9.6. Negation pseudo class This selector is combined with the other selectors and simply represents their negation. For example we can select all elements except div element: *:not(div)or select every button element that is not in the disabled state: button:not([DISABLED])
Frontend Guide
65
3.7.9.7. Pseudo elements With this selector we can treat parts of the content as separate elements and style them differently that way.
element::first-line Selects the first formatted text line. For example inside of the paragraph we can say that the first line is in larger font and bold.
element::first-letter Selects the first letter of the content, it is mostly styled as much larger than the rest of the letters.
element::before i element::after Used for appending new content before or after the content.
3.7.9.8. Example 8 - Pseudo elements Let’s create a short example to see how CSS affects the typography. Let us say that first line of the paragraph should be uppercase and the first letter has the larger font size. This is the very popular way of styling text on the Web.
<p>This is paragraph in<br /> multiple rows, with some<br /> pseudo selectors applied on it.</p> p::first-line { text-transform:uppercase; } p::first-letter { font-size:200%; }
66
CSS
Figure 3.11: Pseudo elements
3.7.10. Combinators Last selector type you should know is actually a combination of the selectors we have already learned (with some special characters). There are two types of combinators: ď&#x201A;ˇ
element-1 element -2 This is the most common combinator type and it is called descendant combinator because it affects all of the descendants. By naming one element after another as a single selector we are actually describing what kind of DOM path are we looking for. For example if we want to access every paragraph that is inside the div element we can write: div p. This means that all of the descendants of that type (p) will be selected in any hierarchy level below the div. Let us take a look at the following example: <p>This is <span>blue</span> text</p> <div> But this is <span>red</span> text <div> <p>And so is <span>this</span> one</p> </div> </div> span { color:blue;
Frontend Guide
67
} div span { color:red; } As a result weâ&#x20AC;&#x2122;ll see the first span in blue color and the other one in red color because we have defined all the span elements inside of a div to be in red color.
Figure 3.12: Combinators
ď&#x201A;ˇ
element-1 > element -2 This is the child combinator and unlike the descendant combinator it selects only children and not the descendants. Weâ&#x20AC;&#x2122;ll add the following like to the previous example: div > span { color:green; }
68
CSS
Figure 3.13: Child combinator
As a result we will get the only second span in green color and not the third one because he is a descendant and not the child.
3.7.11. Web browser selectors As mentioned before one of the key problems is having the same look in different Web browsers. If we run into a problem with a specific Web browser we might end up creating an even bigger problem by fixing the issue with that specific browser and then making the other browsers look bad. For example letâ&#x20AC;&#x2122;s say that an element distance is 100px but in IE6 it doesnâ&#x20AC;&#x2122;t look good and it has to be changed to 110px. By editing that attribute we will change that distance for all Web browsers and not just for that one. Lucky for us there are selectors exclusively for those bad browser versions and that way we can make these small adjustments.
Frontend Guide
69
IE 6 and older version * html selector { property: value; }
IE 7 and older version *:first-child+html {} * html {}
Only IE 7 *:first-child+html selector { property: value; }
IE 7 and modern versions html>body html selector { property: value; }
Modern versions without IE7 html>/**/body selector { property: value; }
Opera 9 and older versions html:first-child selector { property: value; }
Therefore the solution for our problem would look like this div { padding:100px; } /* all Web browsers */ * html div { padding:110px; } /* Only IE 6 */
3.8. Conditional comments Similar to Web browser selectors, conditional comments allow us the possibility to apply some styles exclusively to a specific browser or even browser versions. Conditional comments are more precise and safer way to do this but they only exist for Internet Explorer. Of course, ideally, it would be great if we didn’t need to do this sort of thing and in most of the cases we won’t. But in some cases it is required mostly to satisfy Internet Explorer’s imperfections. 70
CSS
Here is the conditional comments syntax:
Positive <!--[if condition]> HTML <![endif]-->
Negative <!--[if ! condition]> <![IGNORE[--><![IGNORE[]]> HTML <!--<![ condition]-->
Condition can have one of the following versions:
IE - Any IE version lt IE version lte IE version IE version gte IE version gt IE version
- Less than IE version - Less or equal than IE version - Only that IE version - Greater or equal then IE version - Greater than IE version
The word “version” we’ll simply replace with the version number like 5, 5.5, 6, 7… The word HTML we’ll replace with the link to the CSS file, like: <!--[if IE 6]> <link href="ie6only.css" rel="stylesheet" type="text/css"> <![endif]-->
3.9. Color spaces So far in the all examples we have used English words to assign color values (green, blue, red). This gives us a possibility to use one of many color values. Besides this we can also define colors in few other ways like RGB or hexadecimal values, allowing us a range of almost 17.000 colors to use.
Frontend Guide
71
Color name - red Using English words like: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, orange, purple, red, silver, teal, white, and yellow
RGB value - rgb(255, 0, 0) Using RGB value as red, green and blue channel. Values can be from 0 to 255 or in presents from 0 to 100%.
RGBa value - rgba(255, 0, 0, 1) Same as RGB just the last value represents alpha channel which is the transparency value. This is the part of CSS3 and without additional filters it works only for: FireFox, Safari and Chrome.
Hexadecimal value - #ff0000 Starts with the “#” sign following by 6 characters in the range from 0 to f. This is the full version but can also be written in the short version with just 3 characters. For example to get the red color we need to write #ff0000 but if we write #f00 we’ll get the same result. As well as the #ffffff- #fff, #9966CC - #96C…
3.10.
Size units
Along with the text size we will always define various element dimensions like width and height and those blocks will make the page structure. All of those dimensions can be in one of the following units:
px - font-size: 12px; Pixel size, this is the static unit and it doesn’t change based on the other elements.
em - font-size: 2em; This is the calculated size based on the current size. In this case 2em would be twice as big as the current size. This way we can
72
CSS
have dynamic dimensions that change based on the other elements.
pt - font-size: 12pt; Point size, static value similar to pixels.
% - font-size: 80%; Dynamic value same as em. It gives as an opportunity to define the dimensions based on the other elements. For example we can adjust the font size based on the screen size.
3.11.
Properties and values
Now that we know everything about selectors, how CSS works and CSS syntax we’ll get to know available properties and their values. In the chapter on HTML we learned the basic tags and attributes, now we will learn how to apply CSS properties to style and format HTML elements. In the previous examples we have already used some CSS properties and values and I think they were all straightforward and don’t require any additional explanation. Those included color:red, fontsize:14px etc. And that’s the great thing about CSS, all of the properties and values are intuitive and written in plain English so it doesn’t take much effort to learn them. Our code editor helps us in selecting properties and values as well, by offering a complete list of the available attributes. It is not crucial to know all of them at once especially at this point but it is important to know what is available and how are they applied.
Frontend Guide
73
Figure 3.14: Code editor help when writing HTML and CSS
We can group CSS properties in the following way:
Font Text Colors and backgrounds Box model - dimensions, padding, margin, border Positioning and displaying Lists Tables Other CSS3 properties, moz and web-kit
3.11.1. Font This group includes properties for changing font family, size type etc.
74
font-family Defines a font family. Can have one or more font families separated by a comma and the first one listed will be used. In order for it to be available, the user has to have it on their computer. It is important to limit font use to the standard ones CSS
that are part of every operating system. If the font name has multiple words it has to be contained by quotation characters. font-family: Arial, Helvetica, sans-serif; font-family: "Times New Roman", Times, serif; There are different ways to use a non-standard fonts and we’ll talk about that in the separate part called font replacement. Exercise: Try to find the list of the Web safe fonts online so that you know which ones are going to be displayed on every platform.
font-size Size of the font presented in one of the units format, explained previously. font-size:14px;
font-weight Weight of the font presented by a value from 100 to 900 (100, 200, 300…900) or using the words normal and bold where the first one is equal to 400 and the second one is equal to 700. Bold and normal are the safe values and the rest of them depend on things like font type and Web browser. font-weight: bold;
font-style Style of the font which can be italic or normal. font-style:italic;
font-variant With this attribute you can display the font in small caps by using
Frontend Guide
75
small-caps or normal values. font-variant:small-caps;
font All these font-something properties can be defined using only one attribute. This way we’ll just list all of the values one after another. The following two examples are functionally the same. h2 { font: italic small-caps bold 14px Arial; } h2 { font-family: Arial; font-size:14px; font-weight: bold; font-style: italic; font-variant: small-caps; }
3.11.1.1. Example 9 - Font, basic typography One of the things you are always going to do when you are creating a new Web site is defining fonts for all of the elements. Typography is the process of designing content (headlines, paragraphs, lists and other textual elements) in the way of defining fonts, sizes, spaces, colors etc. Now we’ll create an example of basic typography in order to better understand font properties. We’ll define a font property for basic elements and make a simple layout that will inherit content size. <div id="header"> <h2>Heading two</h2>
76
CSS
<h3>Heading three</h3> <h4>Heading four</h4> <p>At vero eos et <strong>accusamus</strong> et iusto odio <em>dignissimos</em> ducimus qui blanditiis praesentium</p> </div><!-- header --> <div id="content"> <h2>Heading two</h2> <h3>Heading three</h3> <h4>Heading four</h4> <p>At vero eos et <strong>accusamus</strong> et iusto odio <em>dignissimos</em> ducimus qui blanditiis praesentium</p> </div><!-- content --> <div id="footer">Footer info </div><!-- footer -->
We have made three div elements and placed the same elements into the first two in order to see the difference. Weâ&#x20AC;&#x2122;ll write CSS now: * { font-size:100%; } html { font-size:62.5%; } body { font-family:Arial, Helvetica, sans-serif; font-size:1.2em; } strong, b { font-weight:bold; } em, i { font-style:italic; } h2, h3, h4 { font-family:Georgia, "Times New Roman", Times; font-weight:normal; } h2 { font-size:1.6em; } h3 { font-size:1.5em; } h4 { font-size:1.2em; } h4 { font-variant:small-caps; }
Frontend Guide
77
#header { font-size:1em; } #content { font-size:1.5em; } #footer {font-size:0.8em; }
In this example we will test em units as relative units to the other elements. As a result you should get something similar to the image 3-15. Pixels are very simple units and when they are used to define spacing we can be sure that things will be spaced as expected. For this reason pixels will usually be our primary choice for building fixed layouts. On the other hand em and % units give us an opportunity to set not only the font size but the whole layout size dynamically.
Figure 3.15: Em unit inheritance
In this example we can see how to set font size in em unites. First of all we have set the font size of everything to the 100% (* { fontsize:100%; }). The starting font size in most Web browsers is 16px. After that we have set all the text inside of html to 62.5% of the starting size which is 16px. This way we get all text in html to be 10px 78
CSS
and this is an easy size to work with. At this point 1em is the current text size which is 10px. So 1em = 10px now. In the body part we have set the new font size to 1.2em which then is 10x1.2 = 12px. Now for everything inside the body 1em is 12px. Later on we have defined the basic look of strong and italic elements and the font family for the headlines. Now we get to the part where we set element font size based on the current em value (previously defined in the body tag; 1em is 12px). So the headline sizes are: h2 is 1.6em (12x1.6), h3 is 1.5em (12x1.5) and h4 is 1.2em (12x1.2). At the end we change all of the sized by the following formula: current size multiplied by size inside of that div. Which means that if our h3 in the body is 12x1.5 = 18px and div content has relationship of 1.5em our h3 inside of that div will be larger by the half if itâ&#x20AC;&#x2122;s size (= 27px). This might be a bit complicated at the moment so I will use pixels in the rest of the examples. For now it is important just to understand how the em unites work and to keep it in mind if you ever need dynamic size definitions (very useful for adjusting content for different platforms, and resolutions).
3.11.2. Text This group includes properties for text formatting and formatting its presentation based on the other elements. ď&#x201A;ˇ
line-height Height of the line or in other words, spacing between two text lines. It can be in pixels or in percentages. p { line-height: 14px; }
ď&#x201A;ˇ
letter-spacing Spacing between the text letters.
Frontend Guide
79
p { letter-spacing: 1em; }
word-spacing Similar as the previous property just this one is for whole word spacing and not the letters. p { word-spacing: 1em; }
text-align Alignment of the content inside the block element. Inline elements cannot have this property (it won’t do anything). You can choose one out of four predefined values for it: left, right, center and justify. p { text-align: right; } This property will affect all of the content including inline elements. For example we can align images this way, we’ll see that in the next examples.
text-decoration Defines if the text is underline, overline or strikethrough with one of the following values: none, underline, overline, linethrough. a:hover { text-decoration: none }
text-indent Defines the text beginning distance from its top left corner. It can be used only for block elements and usually for hiding the content but keeping the block structure and position. a { text-indent: 10em; }
80
CSS
text-transform Text transformation to the lowercase or uppercase using the following values: uppercase, lowercase and capitalize. p::first-line { text-transform: uppercase; }
vertical-align Vertical alignment for the inline elements and its value can be: in pixels, in percentages, baseline (bottom line of the parent), sub (below the baseline), super (above top line), top (top line), text-top (font top line), middle (font middle), bottom (bottom line), text-bottom (text bottom). sub { vertical-align: sub; }
white-space Defines how will the content action within the white spaces (new lines, single spaces). Using this we can force text break (or not break) in a specified location. Safe values are: normal (lines will break at the end of the line), pre (lines won’t break and they will keep the formatting), nowrap (lines won’t break but they won’t keep the formatting). #code { white-space: pre; }
3.11.2.1. Example 10 - Text formatting and alignment Try to recreate the following example using the previous properties. There is small fragment of HTML and CSS as help.
Frontend Guide
81
Figure 3.16: Various text formatting
body { font:12px Arial, Helvetica, sans-serif; } sup { vertical-align: super; font-size:10px; } sub { vertical-align: sub; font-size:10px; } ::first-letter {
text-transform:lowercase; }
Most of these formatting options won’t be shown in different Web browsers so don’t get too carried away with it. Instead we’ll see some alternative and same options to do these kind of things. 82
CSS
3.11.2.2. Example 11 - Content vertical align Horizontal content align is simple to do, just using the text-align: center; property, there is also another way to do it but we’ll explain it later on. Based on how simple this is you will probably assume that we can position the content vertically in the similar way using the vertical-align property. But in most of the cases it is unusable and provides no result whatsoever. I suggest only to use it with super and sub values. Let’s take a look at the following code example: <div id="box"> content </div> #box { height:300px; background:#eee; vertical-align:middle; } We have a div with some height and background color to illustrate its dimensions. The most logical option for vertical centering would be using vertical-align:middle; but that won’t work because vertical-align can only used for inline elements and div is block by default. There is one trick I suggest using in this kind of situations; using the line-height property where we know the exact content height; We’ll change our code to this: #box { height:300px; background:#eee; line-height:300px; } Now if we take a look at the result we’ll see that it is correctly displayed. Unfortunately this works only for the content and we can’t Frontend Guide
83
vertically align block elements with it. For example if we want to position whole div vertically based on the screen height we’ll have to use some other solutions. Exercise: We can get the click effect on the links by changing their line-height property. Try to create a link that on hover has no text decoration and on click changes its line height (for some small value).
Figure 3.17: Content vertical align
3.11.2.3. Example 12 - Text hiding Here’s another useful tip. We’ll demonstrate how to hide the content of an element but maintain its dimensions, position and formatting. For example if we have a designed button with text as the part of the image and then we place it as a background of our HTML button we’ll end up with having two texts on it. In this situation we’ll want to hide HTML content but still have the button that is clickable. We can achieve this using text-indent property. In the previous example for out #box we’ll assign the following CSS code and the content will move to the desired directions. If we want to hide is we’ll use a large negative value like this: text-indent:-9999px;
84
CSS
3.11.3. Colors and backgrounds A couple of other properties that we are going to use very often are for defining color and element background. This allows us to use an image as element background in various ways as well as combine it with a desired color.
color Defines the content color by using a color space as value. You can read about the color spaces earlier in this chapter.
background-color Defines the element background as the solid color or as a transparent area. Transparent is the default value. body { background-color: red; }
background-image Defines a image to be used as the background. body { background-image: url(image.jpg); }
background-repeat Defines how is the background image will be repeated inside of an element. It can have the following values: repeat (default value, repeats on x and y axis), repeat-x (repeats only by x axis), repeat-y (repeats only by y axis), no-repeat (doesn’t repeat). body { background-repeat: repeat-x; }
background-attachment Defines if the background image is going to move along with the rest of the content while the Web page is scrolled. This is an interesting option and you can see it a lot on the pages where the
Frontend Guide
85
content scrolls and the background doesn’t. It can have the following values: scroll (default value, it will scroll along with the content) and fixed (it won’t scroll). body { background-attachment: fixed; } Exercise: Take any image and add it as the document background. Then fix it and analyze the result (the page has to have a larger height, so you can define the body height for example, in order to see the result).
background-position Defines the position of the background inside of the element. The default position is in the upper left corner. It can have the following values: top, bottom, left, center, right. In addition, these values can be combined (separated by space), to look something like this: top right. body { background-position: top right; } If we have to position our background more precisely we can use numeric values in the following format: x distance and y distance: body { background-position: 50px -100px; } Or if we need a dynamic value we can use percentage with the same format: x distance and y distance, where 100% is the width of that element. So if we assume that the element has width of 500px and use the following code: body { background-position: 50% 10%; } Our background will be moved 250px (50%) by the y axis and 50px (10%) by the x axis.
86
CSS
3.11.3.1. Example 13 - Background positioning Let’s apply the things learned about backgrounds and colors to the real examples you’ll probably use many times. 1. Repeat everywhere If we want to have a solid color for all the background we’ll just use background-color property. But, instead of that, let’s see an example where we can recognize one shape that is being repeated on the whole page. As an example I will take the background of the http://cavica.com/ Website. Its body content is gray with noise texture so if we use solid gray color it won’t be the same.
Figure 3.18: Repeating one pattern on x and y axis
For this example I have reduced the lightening so you can see the background more clearly. This is the simplest situation where you just need to cut a clear square shape which will repeat on the whole page. Square dimensions will be determined by the pattern shape, size etc… When you are working with backgrounds it is Frontend Guide
87
always important to have that image as small as possible, because the Web browser will always load everything else first and then the backgrounds last. Because of that we get a delay effect for it. Take a look at the following code fragment: body { background-color:#eee; background-image:url(bg.jpg); background-position:left top; background-repeat:repeat; } So we have defined the image path, position, repeat options and the color. We know that color is going to be displayed until the background is loaded or it will at least fill in the missing places. In this case there won’t be any missing places because the background is repeated everywhere. We can write this same example in the following way: body { background:url(bg.jpg) left top repeat #eee; } Since we’re using the default values for repeat options and positioning we can remove those and then our code will look like this: body { background:url(bg.jpg) #eee; }
2. Repeating by the y axis Let’s take a look at example where we have recognized the background as a vertical repeating shape. On the 88
CSS
http://enviramedia.com/ Website we see the same shape repeating while we scroll the page down. We can apply the same principal and cut the part of the clear area:
Figure 3.19: Repeating one pattern on the y axis
You will notice that we didn’t select the full width and there is why: This example is positioned to the left and depending on the screen resolution blue color should fill the right part. We don’t know what resolution will be used so usually we’ll cut the largest possible image. But there is no need to do that in this example since the empty space should be filled with the solid color and CSS has the solution for it: background:url(bg.jpg) repeat-y left top #abc6d9; In order to see how does the color fill in the missing parts we’ll change that blue color with the green color and get the result as the following image. It is important to mention that the background goes underneath the content and don’t affect any element sizes. This means that if it is smaller than the content area there will be blank space left and if it is larger some parts will be hidden.
Frontend Guide
89
Figure 3.20: Filling the missing background with the solid color
3. Repeating by the x axis Similar to the previous example just oriented differently. Of course this is on the designer’s choice and you will choose a technique based on the design. In this example the background will fill in the full page width by repeating one shape. But we can’t predict the page height so once again we’ll fill it with the solid color. Let’s take a look at the ThemeGalaxy Website:
Figure 3.21: Repeating one pattern on the x axis
90
CSS
Once again dimensions of the background image depend on the design. And in this case there is no texture so we can choose 1px as the width and repeat it horizontally. body { background:url(bg.jpg) repeat-x left top #eee; } 4. No repeat The last example you might run into is the background that doesnâ&#x20AC;&#x2122;t repeat. Mostly these are large images ending with gradient transition to some solid color that will fill the rest of the page. As an example take a look at the http://www.studio7designs.com/ Website:
Figure 3.22: No background repeat
This is good example where you can see nice gradient between the edges of the image and page solid color. So we can use very simple CSS style in order to do this: body { background:url(bg.jpg) no-repeat center top Frontend Guide
91
#000; } These were some of the more common examples of using backgrounds. You should know that all these demonstrations were for the body element but you can apply them in the same way to any block element.
3.11.3.2. Multiple backgrounds In CSS 3 we have an option to use multiple backgrounds for one element but this isnâ&#x20AC;&#x2122;t yet supported by all Web browsers. Since this affects the visuals it is obviously important to the client for their design to be visibly consistent, so at the moment we wonâ&#x20AC;&#x2122;t use this option. But it is good to know it is available and it can be used safely in the future. You might ask yourself if there is actual need for using multiple backgrounds and I think there is since I personally have been in this situation. In most of the cases you can avoid using it by planning your code better and using some extra elements. Syntax of the multiple backgrounds looks like this: background-image: url(one.png), url(two.png), url(three.png); background-position: center center, 20% 80%, top left; background-origin: border-box, content-box, border-box; background-repeat: no-repeat, no-repeat, norepeat;
3.11.4. Box model Box model is a way to visualize Webpage elements. Every element we use and style we apply in any way will always have the look of a box (rectangular area). In HTML chapter we mentioned the FireBug tool 92
CSS
for element inspection. It is an indispensible tool for visualizing our elements to see how much space they take up on the page. We have also categorized all of the elements as block or inline. Block elements have the default width of 100% and they push all other elements beneath them. On the other hand inline elements have only the width of its content and they can be in the same line with the rest of the elements. Along with these two types elements can also be used as inline-block elements which we will talk about later. In any case an element will be always shown as a rectangular area.
Figure 3.23: Element box model
With CSS we can change various properties of the box model for each element including its default structure. Let us take a look at the following example that represents a div element without any style:
Figure 3.24: Default look of block elements
Frontend Guide
93
By inspecting this div we’ll see its dimensions illustrated as the blue rectangle. By default it has 100% width and the height of its content. Let’s add the following styles:
padding Inside distance from the box edge. You can use any of the numeric values in the following way: o o o o o
padding: 10px - same distance for all sides padding: 10px 20px - up and down 10px, left and right 20px padding 10px 5px 20px - top 10px, left and right 5px, down 20px padding: 10px 5px 15px 20px - top, right, down, left padding-left, padding-right, padding-top, padding-bottom
By adding padding to our div we’ll get the following result:
Figure 3.25: Padding
So we have added a top and bottom padding of 30px and left and right padding of 20px. FireBug illustrates padding by highlighting it in purple. The most important thing to remember about this 94
CSS
property is that while the total height of the div is increased by the size of the padding the content height remains the same and the total width of the content is reduced by the size of padding. ď&#x201A;ˇ
border Defines the style, color and thickness of the box border: o o o
border-width - Width of the border in pixels border-color - Color of the border in one of the color spaces border-style - Style of the border as: none, dotted, solid, double, dashed...
We can define these properties as separate ones or as one long property with all values separated by white space. border: 1px solid red; border-top: 3px dashed green; Letâ&#x20AC;&#x2122;s add the following code to our example and see how it is visualized within the box model:
Figure 3.26: Border
Frontend Guide
95
As you can see this property will be shown as a border of whole box and not just content so that is why it is on top of the padding.
margin Defines the outside distance of the box to the other elements. It can have any numeric value or predefined auto value. o o o o o
margin: 10px - Same distance for all of the pages margin: 10px 20px - top and bottom 10px, and right 20px margin 10px 5px 20px - top 10px, left and right 5px, down 20px margin: 10px 5px 15px 20px - top, right, down, bottom margin-left, margin-right, margin-top, margin-bottom
Earlier we have mentioned that using text-align property we can center the box content and said that we can’t use it to center the whole box. But we can do it simply by setting auto value for margin property. So if we have a div (that doesn’t have width of 100%) and we want to center it horizontally we can use the following CSS: margin:0px auto; This means that it won’t have margins and the web browser will automatically set left and right distance based on the screen size. Now we’ll define some margins for our previous box example: margin:20px 30px;
96
CSS
Figure 3.27: Margin
FireBug highlights the margin in yellow and now, clearly, you can see the difference between the margin, border and padding property. It is important to know that margin doesnâ&#x20AC;&#x2122;t change the element dimensions like padding. We can illustrate this difference with another image taken from the W3C Website where you can see their description of these properties.
Figure 3.28: W3C box model
Frontend Guide
97
We already know that block elements have 100% width and the height of the content, but we can change that using the following properties:
width Defines the width of the content as a numeric value without any margin, padding or border. When the content reaches the end of the box it will break into the new line and the box will not change its width. div { width:500px; }
height Defines the height of the content as a numeric value without any margin, padding or border. Usually it is not set, allowing the box to expand with the content. But we can use height if we want something to have an exact height. div { height:300px; }
min-width, min-height, max-width, max-height Limitations for the minimum and maximum height and width values.
Notice: You can’t add an explicit height or width to the inline elements and table columns and rows.
3.11.4.1. Example 14 - Element sizes and movement Now we’ll use these new properties to make something called a wrapper. The wrapper is the main holding area which contains all other elements. Let us assume that in design all of the content is inside of a green bordered box with 500px width (from one green edge to the other) and that all of the content inside of it has 50px distance from the green edges. Since it isn’t full width wrapper we’ll 98
CSS
usually position it on the center of the screen. HTML code for this example is very simple: <div id="wrapper"> Content goes here </div><!-- wrapper --> And it should be since we are doing all of the adjustments inside of CSS: #wrapper { margin:0px auto; width:500px; padding:50px; border:1px solid green; } First we have set all the margins to zero and gave them auto value so it is positioned to the center of the page. After that we have set width, padding and the border. But this doesnâ&#x20AC;&#x2122;t turn out as we wanted it to be since weâ&#x20AC;&#x2122;ll get the full width of 600px and not 500px. We have explained this before by saying that padding adds up to the total box size (500 + 2*50). So to get the desired result we have to change the original width by the size of the padding. This also counts for other units like percentage. So if we write width:100%; again the total width will be larger due the the padding size. Letâ&#x20AC;&#x2122;s change our code to this now: #wrapper { margin:0px auto; width:400px; padding:50px; border:1px solid green; }
Frontend Guide
99
Now we can check this in FireBugâ&#x20AC;&#x2122;s layout mode where we can see the measurements of our element. Exercise: In the same document try to add usual Website parts: header, content and footer where the header and footer will have fixed height and the content will have auto height.
Figure 3.29: FireBug layout option
3.11.5. Example 15 - Positioning and displaying If you have completed the previous exercise than you have created a typical page with wrapper, header, content and footer. These are typical names for these parts of the Website and each of them represents one large area. Of course you can use any name you like, but the names should be descriptive in order to get around in the code easier. You code should look something like this: <div id="wrapper"> <div id="header"> <h1>Headline</h1> </div><!-- header --> <div id="sidebar"> sidebar </div>><!-- sidebar --> 100
CSS
<div id="content"> <p>Content <span>goes</span> here</p> </div><!-- content--> <div id="footer"> Footer info </div><!-- footer --> </div><!-- wrapper --> We have already explained when to use id and when to use class attribute and in this example we assume that we won’t have any other headers or footers; so, we have assigned them unique identifiers. We’ll write simple CSS now: #wrapper { margin:0px auto; width:810px; padding:50px; border:1px solid green; } #header { height:200px; border:1px solid } #sidebar { border:1px solid } #content { border:1px solid } #footer { height:100px; border:1px solid }
red;
orange;
blue;
gray;
If we take a look at this example, in our Web browser, we’ll get the expected result. Every element goes under the previous element. We have added colored borders in order to see the dimensions better. Frontend Guide
101
If we want to have two block elements one next to other then we are faced with a problem. Inline elements can be in the same line with other elements but canâ&#x20AC;&#x2122;t contain any other elements inside of them (block ones). On the other hand, block elements can have other elements inside but their width is 100% by default and they are pushing everything below them. Previously we have seen that we can change the width of the block elements so letâ&#x20AC;&#x2122;s try it. Weâ&#x20AC;&#x2122;ll change the width of the content div and the sidebar div to 500px and 300px so both of them can fit inside of the wrapper in one line (810px). #sidebar { width:300px; border:1px solid orange; } #content { border:1px solid blue; width:500px; }
Figure 3.30: Default block element behavior
102
CSS
But this is not going to work because of the way block elements interact. Even when both can fit inside of the wrapper they will still go one below another. We’ll explain why and how to change in just a bit. Notice: If we don’t explicitly set the width, the block elements will take 100% of the parent element. But if we set the width larger than the parent width, the element will fall outside of the box of the parent element.
Figure 3.31: Block element width
float This is the key property for building layouts. It allows us to position our box on the left or right side and keep the rest of the content (or boxes) in line with it. When you apply this property to the element it loses its height definition. It will still visually have the height of the content and the content will act as the inside of the normal box but it won’t affect the positioning of the other elements (unless they also have this property). In the previous example you’ve seen that by adding height to some boxes all other boxes after it are pushed down. This won’t happen for the float elements and its content. Instead of pushing other elements down it will float over them as if they it doesn’t exist. That is their
Frontend Guide
103
default behavior and we can change that using couple of tricks. We’ll do that in the following examples to make things more clear. Predefined values for this property are: left, right and none (default value). #sidebar { float:left; width:300px; }
104
clear This is the property for fixing float element problems (no height). It tells the Web browser how to display the next element after the float element. Float elements let us have multiple block elements in one line and the clear property let us control whether to show them like that or to show them one after another like typical block elements. We need it in situations where we have to be sure that a specific element will fall under float element. We can use one of these predefined values: o
none - default value and the float elements will be in line with that element clear:none;
o
left - doesn’t allow any float elements on the left side of that element. If they are on the left it will be moved under them so the left side is “clear” clear:left;
o
right - doesn’t let any float elements on the right side of that element. If they are on the right it will be moved under them so the right side is “clear” clear:right;
o
both - doesn’t let any float elements on the left or right side. If they are on the left or right it will be moved under them so CSS
the right side is “clear” clear:both;
By the way, you can think of this property as the reason for the default block element behavior. We have seen earlier that even if we change the width of block elements to allow more of them to fit inside of one line, they will still be pushed one under the other.
3.11.5.1. Example 16 - float and clear Now we see on couple of examples how to build layouts using float and clear properties. First we’ll do couple of static layout options and then we’ll talk about dynamic layouts separately in just a little bit.
1. Not all float elements. With this approach we can have many elements in one line but just one of them can be without the float property. Because without the float, two block elements will go one under the other no matter what. If we decide to go with this approach we have to assign one element without the float property. That element should be the one we think is going to be the largest. In our previous example, where we want #sidebar and #content in the same line, we should choose the #content because that one will hold all of our content. We are making lot of assumptions here but 80% of today layouts are similar to this. It is the principal that we are trying to demonstrate. #sidebar { width:300px; border:1px solid orange; float:left; }
Frontend Guide
105
Figure 3.32: Default float behavior
Figure 3.33: Text formatting to the float elements
We have added the float:left; property for the sidebar and got what we expected. The sidebar is now in the line with the content but it has lost its height and now youâ&#x20AC;&#x2122;ll see it over the content and it donâ&#x20AC;&#x2122;t affect other elements formatting (it isnâ&#x20AC;&#x2122;t pushing them down). On the other hand, the content inside of #content div has formatted 106
CSS
around the #sidebar element, an effect we see commonly, with images that have an assigned float value. But this isnâ&#x20AC;&#x2122;t the result we are looking for because we want for #content to start where the #sidebar ends. Weâ&#x20AC;&#x2122;ll add the following CSS code: #content { border:1px solid blue; margin:0 0 0 302px; } So for the #content we have added a margin with the size of the #sidebar (plus the border size because of the demonstration); this way the #content is moved to the right. You will notice that we havenâ&#x20AC;&#x2122;t defined the width for the #content, that is because it will be dynamically set in order to keep the maximum available space.
Figure 3.34: Float layout example
Frontend Guide
107
This way of building layouts is used less than our next example and it should be used in the cases where we don’t/can’t set the width for all of the elements. Exercise: Add an 80% width to the #wrapper resize the browser window and analyze the result. Please note, when you want multiple elements in one line the one without the float needs to be the last one in the code. Therefore if we want to add something like another sidebar for the right side we’ll add it before the #content. #right { width:100px; float:right; border:1px solid }
lime;
Figure 3.35: Order of the float elements
108
CSS
Even if we add #right before the #sidebar that would be ok since they have the different float values. If they had the same then the code order would matter. Finally, let’s take a look what happens if the sidebar has larger content size than the #content div. We’ll add some additional text to the #sidebar and remove it from the #content.
Figure 3.36: Float element height
On the previous figure when can see what we mentioned earlier and that that is: float elements don’t have an assigned height, so the footer div starts where the content div ends. We can fix this using the clear property. We’ll add the clear:right; to the #footer element.
Figure 3.37: Clear left and right
The #footer has moved down for the sight sidebar height. Let’s change the clear: right; to the clear:both;
Frontend Guide
109
Figure 3.38: Clear both
As you can see by using the clear property we can force elements to be placed under the float elements while insuring that the left and the right sides are “clear”. So using clear we can pick any element to be without float but I suggest picking the one with the largest content. 2. All elements are float This is a simpler and more flexible way to build layouts than the previous one we discussed. It is also used more often. Again we can have as many in line elements as we want and the idea is for them all to have the float property. After that we’ll add the clear property to the next element that we want in the new line. Only bad side is that you need to set the width of every element that has float. #content { border:1px solid blue; float:left; width:400px; } So for the content we have removed the margin and added a width (so it can fit inside of that line). Depending on the situation (and personal preference) you will use one of these two methods to build layouts. As an example we can take a look at the test page of an HTML or CSS framework. Notice that all of 110
CSS
them use the second method to build and test grids.
Figure 3.39: All elements are float
Figure 3.40: Blueprint grid system
Frontend Guide
111
112
position Defines the element positioning with one of the following values: o
static (default value) - Normal positioning for that type of element. div { position: static; }
o
absolute - positions the element in an exact spot on the page making the element independent from the rest of the elements. We can set that position as a distance from the top, bottom, left or right side of the first relative element. By default the first relative element is the body element and if you don’t set it differently all of the absolute elements will be positioned based on the body. When an element is set to be absolute it loses its default behavior and will not push or format other elements. Block elements with the absolute value no longer have a 100% width. div { position: absolute; }
o
relative - absolute elements are positioned by the relative elements. A page’s body is the first relative element and we can define any block element as relative. All of the containing elements defined as absolute will be positioned based on that. div { position: relative; }
o
fixed - same as absolute except in this case element it will be fixed and will not scroll with the rest of the page. This isn’t supported by the earlier version of Internet Explorer. Everything we say about the absolute will be the same for fixed value. div { position: fixed; }
CSS
ď&#x201A;ˇ
top, bottom, left, right Defines the distance for the absolute and relative elements from the edges. o
Absolute elements will move from the first relative parent. div { position: absolute; left: 25%; /* same as right: 75%; */ top: 50px; }
o
Relative elements will move as normal elements from the parent. We can think of this as the same thing as a margin but when you are using the margin element it can auto resize to stay inside the box. When you use top, bottom, left and right it wonâ&#x20AC;&#x2122;t resize and it can fall outside of the parent box. div { position:relative; right:50px; /* not same as margin-right:50px; */ }
ď&#x201A;ˇ
z-index Defines the position for the absolute and relative elements on the z axis. Since these elements can lie on top of one another some parts may not be visible. By adding natural numbers for the zindex property we can control their position. We can think of this as a set of cards where the one on the top has the highest z-index value and the one on the bottom the lowest. div { position:absolute; z-index:10; }
Frontend Guide
113
3.11.5.2. Example 17 - Positioning The position property is very useful, but not for creating our layout. Since it doesn’t affect the other element’s positioning, which is what we need (content to push other elements etc.) it should only be used just in the following cases: when an element is independent from the rest of the elements, when we know the exact dimensions of an element and when we know that it is not going to move (and neither will the other elements). To our previous example we’ll add a new div #advertise after the body tag and we’ll style it on the following way. <body> <div id="advertise">Advertise here</div> <div id="wrapper"> #advertise { width:468px; height:60px; line-height:60px; text-align:center; background:#eee; } So now we have one div that simulates an advertise area. This is a good example for absolute element since we know its dimensions and position and we also know that it shouldn’t have anything to do with the rest of the content. Now we’ll add an absolute value for it and position it to the upper right corner. #advertise { width:468px; height:60px; line-height:60px; text-align:center; background:#eee; 114
CSS
position:absolute; top:20px; right:20px; } If you take a look at this example you will see that it doesn’t affect the rest of the page and it sits above everything else.
Figure 3.41: Absolute positioning
Let’s say that we want that advertise div inside of the header div. We can place it there by changing top and right values and the advertise div will move from the body edges. But this is not good since, by changing the screen size, the #advertise div positioning will change as well. That is why we’ll place the advertise div inside of the header div. <body> <div id="wrapper"> <div id="header"> <div id="advertise">Advertise here</div> <h1>Headline</h1> If we take a look at the result now, we’ll get the same appearance. This is because the absolute element will be positioned with regard to the first relative element and it doesn’t matter where it is located in the code. Since we want to position it inside of the header we’ll add position: relative; to the header (be sure you have moved #advertise div inside of the #header div).
Frontend Guide
115
Figure 3.42: Position: relative
On the other hand if we don’t set top, left, right and bottom properties for the absolute elements then it is important to control where they are located in the code - they will show up where you write them. Exercise: Try to do the same thing with the fixed element, scroll the page and analyze the result. After that, make multiple absolute and fixed elements on the same position and change their z-index values then analyze the result.
clip Defines the visible area of the absolute elements using the four values like: div { position: absolute; clip(10px 20px 30px 40px); }
overflow Defines the way that content is going to be treated if it doesn’t fit inside of the box using the one of the following values: o
visible - Default value, content will be visible out of the box div { width: 400px;
116
CSS
height: 300px; overflow: visible; } o
hidden - Everything outside of the box will be hidden div { width: 400px; height: 300px; overflow: hidden; }
o
scroll - Web browser will show the scroll bars in order to present all of the content. div { width: 400px; height: 300px; overflow: scroll; }
3.11.5.3. Example 18 - Overflow and clip Now we’ll see how we can apply these properties for keeping our box structure intact and see how we can use styling as the trick to simulate image cropping. The basic idea is that we can take one image with any dimensions and place it inside of the smaller box with predefined dimensions. Normally the image should be resized while being certain to keep its original aspect ratio and taking the maximum size of the box. The only bad thing about the CSS resize is that the image is not as good as one you resize using a image editing tool. Yes, it looks totally acceptable, but it’s just not as sharp. Let’s say that we have one vertical image which is 300x400px, and that we also have a div horizontally oriented with a 200x150px dimension. Let’s write the following CSS code for the div and place an image inside. Frontend Guide
117
<div class="thumb"> <img src="image1.jpg" alt="" /> </div> .thumb { width:200px; height:150px; border:3px solid #333; background:#eee; padding:5px; } If we take a look at this inside of the Web browser we’ll see that the image has “dropped out” from the box:
Figure 3.43: Overflow: visible
Next thing we want to do is to change image dimensions. We can simply do that by setting its width and height properties. If we want to keep its aspect ratio one of those values has to be set to auto.
118
CSS
.thumb img { width:200px; // or width:100%; height:auto; } CSS has changed our image to the new dimensions and saved the aspect ratio.
Figure 3.44: CSS resize
The last thing we want to do is to add overflow property for our div to prevent the image of going out of the box. .thumb { width:200px; height:150px; border:3px solid #333; background:#eee; padding:5px; overflow:hidden; }
Frontend Guide
119
This way we see the desired result. You should notice one more thing here and that is simulation of double borders. One of them is regular border colored in black and the second one is a combination of the padding and background color. Exercise: Try to apply a clip property for the absolute element in the same way we discussed using overflow for the regular box.
Figure 3.45: Overflow: hidden
display Once again, display is a very useful property. It lets us change the default element stricture. We can use one of the following values: o
none - doesn’t show the element like it doesn’t exist in HTML. It has no dimensions or positions so it doesn’t affect other elements positioning. div { display: none; }
o
120
inline - displayed the element inline
CSS
div { display: inline; } o
block - displayed the element as a block span { display: block; }
o
inline-block - displays the element inline but with all block properties. It is interpreted differently in different browsers and mostly it can be used just for some tags so because of that we won’t use it
o
list-item - treats the element same as the list element (we’ll talk more about the lists in a bit)
o
table, inline-table, table-cell, table-caption… Other values you can use but they are not well supported so we won’t use them
visibility Defines if the element is visible or not. We can use it with the following values: o
visible - default value, it will be visible div { visibility: visible; }
o
hidden - it won’t be visible but unlike the display: none; this element will keep its dimensions and positioning
Frontend Guide
121
div { visibility: hidden; } o
collapse - Same as hidden, just when you apply it to the table it has the same effect as display: none;
3.11.5.1. Example 19 - Changing element structure Letâ&#x20AC;&#x2122;s take a look at one simple example where we need to use block element behavior on an inline element (for example to place it in the new row). Weâ&#x20AC;&#x2122;ll make one headline and one sub headline which should be in a new row. <h1>Headline here <span>sub headline here</span></h1> h1 { font-size:20px; color:red; } h1 span { display:block; font-size:10px; }
Figure 3.46: Channing element structure
122
CSS
This way sub headline will keep all of the h1 properties and will just be smaller and forced to go into the new line.
3.11.5.2. Example 20 - Hiding and showing element on hover Now weâ&#x20AC;&#x2122;ll make an interesting example of how to show and hide elements with a hover action by using display: block, display: none and display: inline properties. <a href="#"><strong>&raquo;</strong>Some text here</a> a { color:blue; text-decoration:none; display:block; width:200px; } a:hover { color:red; } a strong { float:right; display:none; } a:hover strong { display:inline; } We have defined our link as a block element and we have hidden the strong element which has the float property. On the hover action we are changing the display property from none to inline and showing it that way.
Frontend Guide
123
Figure 3.47: CSS show and hide
3.11.5.3. Example 21 - Block navigation Generally weâ&#x20AC;&#x2122;re going to use display:block; for the links because, along with the other things, we can set width, height, padding, margin and everything else. In order to use multiple block elements in one line weâ&#x20AC;&#x2122;ll give them a float property as discussed earlier. <div id="nav"> <a href="#">Link here</a> <a href="#">Link here</a> <a href="#">Link here</a> </div> #nav a{ display:block; line-height:50px; float:left; background:#eee; padding:15px 25px; text-decoration:none; border-bottom:5px solid #ccc; } #nav a:hover{ background:#ccc; 124
CSS
border-color:#333; }
Figure 3.48: Block navigation
3.11.6. Lists We have already learned about lists in the chapter on HTML. They are used a lot in the content formatting and page building so theyâ&#x20AC;&#x2122;ve became a standard for many things including navigation. We recommend using lists anywhere you have a navigation like structure. ď&#x201A;ˇ
list-style-type Defines the style of the list, ordered lists are used for numbers or letters and for the unordered are for the various bulleted lists. o o o o o o o o
none - no mark disc - full circle circle - empty circle square - full square decimal - natural numbers lower-roman - i, ii, iii, iv... upper-roman - I, II, III, IV.... lower-greek, upper-roman, lower-latin, upper-latin - They are not supported by the earlier versions of Internet Explorer
ol { list-style-type: lower-roman; }
Frontend Guide
125
list-style-image Image can be used instead of predefined list style options. li
{
list-style-image: url(dot.jpg); }
list-style-position List position can be inside or outside of the ul box. li { list-style-position: inside; }
list-style Combines the previous list attributes in one line ul { list-style: square inside; }
3.11.6.1. Example 22 - Using lists as navigation We’ll make a typical navigation example using the lists and style it in a simple way. Again we’ll use the page made in the previous examples. List of links: <div id="header"> <div id="advertise">Advertise here</div> <h1>Headline</h1> <ul> <li><a href="#">Menu item</a></li> <li><a href="#">Menu item</a></li> <li><a href="#">Menu item</a></li> <li><a href="#">Menu item</a></li> </ul> </div><!-- header -->
126
CSS
If we open this page in our web browser we’ll get the default vertical styling of the list. Let’s add the following CSS code: #header ul { list-style:none; margin:0px; padding:0px; } #header ul li { display:inline; }
So we have changed the default values for the list box and its items. Each list item has lots of default values like padding and margins so in order to ensure the same look we need to reset those values. We’ll talk about that in the separate part “CSS reset”.
Figure 3.49: List style navigation
3.11.7. Tables Tables are used for displaying tabular data. Originally they were used for building page layouts, something that is taboo today. CSS table attribute are:
table-layout border-collapse border-spacing
Frontend Guide
127
empty-cells caption-side
But they are not supported by the earlier versions of Internet Explorer so we won’t use them. We can style the tables using other CSS properties instead.
3.11.7.1. Example 23 - Table styling We’ll make a simple HTML table with two rows and columns with table header. <table> <tr> <th>Standard</th> <th>Pro</th> </tr> <tr> <td>$45</td> <td>$75</td> </tr> </table> And we’ll apply a simple CSS style: table{ width:250px; } table th{ border:1px solid #bce7fd; width:50%; padding:5px 10px; font-weight:bold; color:#444; background:# eaf9fd; } table td{ 128
CSS
border:1px solid #ebebeb; width:50%; padding:10px 0 20px 0; text-align:center; font:32px georgia; font-weight:bold; color:#009abe; } If we open this example weâ&#x20AC;&#x2122;ll see how we can style anything using the basic properties and get the expected result in all web browsers.
Figure 3.50: Styling tables
3.11.8. Other ď&#x201A;ˇ
cursor Defines the cursor look. It can have an URL value as the image or one of the following values: crosshair, help, move, text, pointer, default, wait... .wrap { cursor: default; } a.help { cursor: help; }
3.11.9. CSS 3 properties, moz and webkit So far, all of the properties we have learned are from CSS2. The latest version, CSS3 has yet to be finalized but we can use some of the new Frontend Guide
129
options today. Most of the popular Web browsers already support lots of these features. Internet Explorer is the only one that isn’t on this list (at least at the time of writing this book). But IE also doesn’t support lots of CSS2 properties either, so there is no reason why we shouldn’t use CSS3 right now.
3.11.9.1. Layout engines Since the CSS3 specification is a work in progress, some of the web browser companies have decided to test some of the new features as their own implementations. These implementations have specific prefixes for the properties and they will work only for those specific browsers. In order to know exactly where they will work we need to know what layout engine is being used for the particular web browser. The layout engine, web browser engine, or rendering engine is the part of the Web browser that renderers our page based on the markup document and stylesheet document for it. Because of the use of various layout engines we’ll get different results in different web browsers. Here is the list of the most popular layout engines and their implementations:
Gecko - Kamino, Netscape, SeaMonkey, Mozilla Firefox Presto - Opera Trident - InternetExplorer WebKit - Safari, Chrome, Arora, Midori, and most of the mobile platforms like iOS, Android, Symbian and the like
Mozilla specific properties have -moz prefix and they support CSS3 properties within the browser (FireFox). You can see the complete list of the supported properties here: https://developer.mozilla.org/en/CSS_Reference/Mozilla_Extensions WebKit based browsers have their own set of properties with the webkit prefix. We can use CSS3 properties in WebKit based browser 130
CSS
like Safari, and Chrome. You can find the complete list of webkit properties here: http://css-infos.net/properties/webkit.php Therefore, in order for us to use some of the new, experimental CSS3 properties we’ll mostly write the following code to get the maximum available use: -moz-property: value; /* For FireFox */ -webkit- property: value; /* For Chrome, Safari etc… */ property: value; /* Mostly for Opera and the future ones */ You have to remember that these are experimental properties. With that in mind they are well supported and useful for applicable browsers. I suggest using them only as small details and not as the important parts of Website since you won’t even get the close result in the CSS3 unsupported browsers. Here are the most popular CSS3 features and list of the supported browsers (during the time of writing this book):
text-shadow Very useful option we can use for additional text styling and making it easier to read. It is mostly used for headlines or some parts of the Website that you want to stand out. Also it is very useful for the text on dynamic backgrounds with multiple colors. Shadow color is usually the light version of the text color. For example black text should have light gray shadow. We can add the text shadow on the following way: text-shadow: 1px 1px 0px #eee; First value is the x axis distance from the text, second value is y distance, third value is the shadow blur and the fourth value is the shadow color. So this example will make a text shadow in the
Frontend Guide
131
lower right corner with the light gray color. Browsers: Safari, FireFox, Chrome, Opera, IE9
box-shadow Similar to the previous option just in this case we can add the shadow to any box in the following way: box-shadow: 6px 6px 8px 8px #eee; First two values are x and y distance, third value is blur, fourth value is the radius and the fifth is the shadow color. Browsers: Safari, FireFox, Chrome, IE9
border-radius Box border radius. A very popular feature in modern design. We can set it for all corners as the same value or independently for each of them. -moz-border-radius: 5px; /* FireFox */ /* Safari and Chrome */ -webkit-border-radius: 5px; /* Rest of the browsers in the future */ border-radius: 5px; /* Only lower left corner */ -moz-border-radius-bottomleft: 5px; -webkit-border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; Browsers: FireFox, Chrome, Safari, IE9
132
border-image Defines a image to be used as the border. We can set it up in the CSS
various ways as stretched or repeated image. -webkit-border-image: url(border.png) 0 5 0 5 stretch stretch; -moz-border-image: url(border.png) 0 5 0 5 stretch stretch; In this code fragment we’ve set an image left and right 5px and stretched from one corner to another. Browsers: FireFox, Chrome and Safari
gradient Another interesting property that allows us to create any kind of gradient (linear, radial etc…) with any set of colors. For example if we want to create vertical linear gradient from white (#ffffff) to gray (#f5f5f5) we can use the following code. background-image: -moz-linear-gradient(top, #ffffff, #f5f5f5); /* FireFox */ background-image: -webkitgradient(linear,left top,left bottom,colorstop(0, #f5f5f5),color-stop(1, #ffffff)); /* Safari4+, Chrome */ filter: progid:DXImageTransform.Microsoft.gradient (startColorstr='#ffffff', endColorstr='#f5f5f5'); /* IE6,IE7 */ -ms-filter: "progid:DXImageTransform.Microsoft.gradient (startColorstr='#ffffff',
Frontend Guide
133
endColorstr='#f5f5f5')"; /* IE8 */ Syntax is different for every browser so we won’t go into great details about it. It is just important to know that there is an option for it and using the filters it can be done even in InternetExplorer. Along with this filter Internet Explorer has couple more filters but all of them are rarely used. This should change with Internet Explorer 9, which is supposed to offer full support for CSS3. Browsers: FireFox, Safari, Chrome, IE6, IE7, IE8
opacity Element opacity, mostly used for backgrounds and hover effects. I suggest using JavaScript to handle opacity, but CSS property for it is also good. Value 0 is full opacity and 1 is no opacity. opacity: 0.7; /* Mostly every browser except IE */ -ms-filter:"progid:DXImage Transform.Microsoft.Alpha(Opacity=70)"; /* IE8 */ filter: alpha(opacity=70); /* IE6, 7 */ Browsers: FireFox, Opera, Safari, Chrome, IE6, IE7, IE8, IE9
columns An interesting new feature that allow us to have content in multiple columns. We can make those columns and style them in a very simple way: -moz-column-count: 3; /* FireFox */ -webkit-column-count: 3; /* Safari and Chrome */
134
CSS
column-count: 3; /* For the future ones */ -moz-column-width: 200px; /* FireFox */ -webkit-column-width: 200px; /* Safari and Chrome */ column-width: 200px; /* For the future ones */ This way we have created 3 columns with a 200px width. We can also make some space between them as well as the divider line. column-gap: 20px; column-rule: 1px solid #333; -moz-column-gap: 20px; -moz-column-rule: 1px solid #333; -webkit-column-gap: 20px; -webkit-column-rule: 1px solid #333; Browsers: FireFox, Safari, Chrome
Along with these properties there are couple more like @font-face (more about this one later), box-sizing, transition, text-overflow for example. You should always stay abreast of the new stuff and browsers version announcements.
3.11.10.
CSS font replacement
One of the most important new features of CSS is font replacement. This way we can use any font on our page and not worry if the client has it or not. We could do a font replacement previously, but in a different way, where the text was replace with flash files, images and such. Those techniques include Cufon, sIFR etc. Frontend Guide
135
Now we can use any font using the @font-face rule. This way the text will stay text, offering us more options for styling as well as better SEO results. Using this property is very simple. At the beginning of the CSS file we load the font files and give them a name for the future use inside our code. @font-face { font-family: 'Museo 500'; src: url('museo500.eot'); } This way we have created a new font family and we can call on it in the usual way: h1, h2 { font-family: 'Museo 500'; } The use of Museo 500 is arbitrary. In this example it is the name of the font and its weight. EOT is a specific font type for the specific Web browser. In order to have this technique working in every browser we have to use different font types them. The following image represents that font-browser relationship. OTF & TTF IE FIREFOX CHROME SAFARI OPERA
IE9 FF3.5 Chrome 4 3.1 Opera 10.00
IOS ANDROID
SVG
FF3.5 Chrome 0.3 3.1 Opera 9 iOS 1
WOFF
EOT
IE9 FF3.6 Chrome 5
IE5+
2.2 Figure 3.51: Web fonts for browsers
136
CSS
So based on that if we want to have maximum browser support we have to use other font files as well: @font-face { font-family: 'Museo 500'; src: url(museo500.eot'); /* IE 5-9 */ src: local('museo500'), /* FF 3.6, Chrome 5, IE9 */ url(museo500.woff') format('woff'), /* Opera, Safari */ url(museo500.ttf') format('truetype'), /* iOS */ url(museo500.svg#font') format('svg'); } This way we can be sure that our font will show in the 99% of the Web browsers. As for the finding font files, there are lots of generators made exclusively for the @font-face property and with them we can download the whole font set and the demo page with the HTML and CSS code that we can just copy into our files. Those generators include Websites like : http://www.fontsquirrel.com/, http://www.fontslive.com/, http://typekit.com/... Some of the fonts are commercial and some of them are free. Also using the generators you can have just one font file and based on it the generator will make the other ones. So this makes using @font-face property very simple and you will see this more and more. There is another thing that makes this kind of font replacement even easier and that is using one of the font hosting websites. This way you donâ&#x20AC;&#x2122;t have to worry about the font files or CSS setup. One of the is Google Fonts API (http://code.google.com/apis/webfonts/) which host for you various Web fonts and the only thing you need to include is their CSS and then you donâ&#x20AC;&#x2122;t even need @font-face declaration. Frontend Guide
137
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Ta ngerine"> ... font-family: 'Tangerine', serif
3.11.11.
Example 24 - Modern CSS3 design
To learn more about CSS3 weâ&#x20AC;&#x2122;ll make one modern form design that represents the login page:
<div id="login"> <form action="#"> <h2>User Login</h2> <label for="user">Username</label> <input type="text" name="user" /> <label for="pass">Password</label> <input type="password" /> <input type="submit" class="submit" /> <a href="#">Reset Password</a> </form> </div> This is a typical form area with headline, fields for login data, submit button and link for passwords reset. These are all usual form elements. If we open this form weâ&#x20AC;&#x2122;ll get the following result:
Figure 3.52: Default form elements look
138
CSS
In this example we can see that all elements except h2 are inline elements. Now weâ&#x20AC;&#x2122;ll use some basic CSS2 properties in order to style it. The idea is to have all of them under one another except the reset link and submit button. body { font:12px Arial, Helvetica, sans-serif; color:#333; } h2 { font-size:20px; margin:0px 0 15px 0; padding:0px; font-weight:normal; } #login { width:250px; border:1px solid #ccc; padding:15px 20px 30px 20px; margin:0 auto; } label { display:block; padding:2px 0; } input { display:block; width:95%; margin:0 0 10px 0; padding:0px; padding:3px 5px; border:1px solid #333; } input.submit { float:right; width:100px; Frontend Guide
139
height:30px; } We have written the simple CSS for this form using just basic CSS2 properties. Now our form looks like figure 3-53. Now weâ&#x20AC;&#x2122;ll add some CSS3 properties to style it better. First we will style the login div:
Figure 3.53: Form styling with basic CSS2 properties
#login { width:250px; border:1px solid #ccc; padding:15px 20px 30px 20px; margin:0 auto; border:2px solid #fff; background-image: -moz-linear-gradient(top, #ffffff, #f5f5f5); background-image: -webkitgradient(linear,left top,left bottom,color-stop(0, #f5f5f5), 140
CSS
color-stop(1, #ffffff)); filter: progid:DXImageTransform. Microsoft.gradient(startColorstr ='#ffffff', endColorstr='#f5f5f5'); -ms-filter: "progid:DXImageTransform. Microsoft.gradient(startColorstr= '#ffffff', endColorstr='#f5f5f5')"; -moz-box-shadow:0 1px 2px rgba(0,0,0,0.3); box-shadow:0 1px 2px rgba(0,0,0,0.3); -moz-border-radius:10px; -webkit-border-radius:10px; border-radius:10px; } So we have added the border, rounded corners, gradient and the shadow for that box. Now weâ&#x20AC;&#x2122;ll do a simple font replacement using Google Fonts API. <link href='http://fonts.googleapis.com/css?family=Dr oid+Sans&subset=latin' rel='stylesheet' type='text/css'> We have to load the previous ling to the document head and added the new font family for the body tag: body { font-size:12px; font-family: 'Droid Sans', arial, serif; color:#333; text-shadow:1px 1px #fff; } Now weâ&#x20AC;&#x2122;ll style the input elements with different states: input { display:block; Frontend Guide
141
width:95%; margin:0 0 10px 0; padding:3px 5px; border:1px solid #112932; -moz-border-radius:5px; -webkit-border-top:5px; border-radius:5px; font:14px Arial, Helvetica, sans-serif; background:#031821; color:#f9e19a; } input:focus{ border:1px solid #0a6184; -moz-box-shadow:0px 0px 5px #1f353e; -webkit-box-shadow:0px 0px 5px #1f353e; box-shadow:0px 0px 5px #1f353e; } At the end if we take a look at this example weâ&#x20AC;&#x2122;ll get the following result:
Figure 3.54: Styling form with CSS3
142
CSS
Later on we can style this for more, but this is enough to see how much influence CSS3 properties have on the modern design. It just takes a little bit more code to have it working in every browser. Exercise: Style submit button in the following way: add gradient background which will change to 180 degrees on click and on hover change opacity to 0.7.
3.12. CSS Sprites This is the most popular technique for changing images in different states (like hover or active). It is also used in other programming areas like gaming. We can present the basic idea with a simple example. Let’s take a button that can be in three different states: normal, hover and active, and we want to have different image for each of those states. Instead of having three different images we’ll have just one image containing those three. On the different states we’ll just show different part of one image. The implementation is very simple. Without this technique we would end up getting a delay during the state change, as witness with the code:
a { display:block; width:100px; height:50px; background:url(image1.jpg) top no-repeat; } a:hover { background:url(image2.jpg) top no-repeat; } So we would use one image for one state and another for different state. This way we’ll get the white space for a second while the other image isn’t loaded. This is happening because the Web browser is Frontend Guide
143
sending a new request for different image. This delay effect is unacceptable today. It can be solved in two ways: preloading images (loading them before they are used) and CSS sprites. In order to demonstrate this technique weâ&#x20AC;&#x2122;ll create a small example with the button mentioned before. I have created a simple button with three states in a graphic editing tool. The three different states are vertically oriented in this example.
Figure 3.55: CSS Sprites image
Each button has a width of 100px and a height of 50px. Therefore our sprites image is 100x150px. Weâ&#x20AC;&#x2122;ll write the following CSS code:
a { display:block; width:100px; height:50px; text-align:center; font:16px Arial, Helvetica, sans-serif; color:#fff; text-shadow:1px 1px #3399CC; line-height:50px; text-decoration:none; background:url(sprites.png) 0px 0px no-repeat; } 144
CSS
a:hover { background:url(sprites.png) 0px -50px no-repeat; } a:active { background:url(sprites.png) 0px -100px no-repeat; } Weâ&#x20AC;&#x2122;ll disregard the usual styling for now and focus on states CSS. The key thing is to move the background based on the way how we oriented it. In this example sprite is vertically oriented so every state will move the background upward by additional 50px. If the sprite was horizontally oriented weâ&#x20AC;&#x2122;d move the x coordinate.
Figure 3.56: CSS Sprites demo
This way we are sending fewer requests to the server and the user gets an instant result instead of waiting for the new image to load. We can refractor this code by removing the things that repeat: a { ... background-image:url(sprites.png); background-repeat:no-repeat; } a:hover { background-position:0 -50px; } a:active { background-position:0 -100px; } Frontend Guide
145
As I said before, this technique is used a lot and anywhere you see background changing it’s probably being done with sprites. We can also use sprites for the text that is image. Usually we can see this in the navigations and a good example is the www.apple.com website which handles its navigation states using this technique.
Figure 3.57: CSS Sprites as navigation
3.13.
CSS Reset
CSS reset is another tool we will make good use of. We’ve discussed how different browsers have different default values for elements so we would want to reset them and then start from the same values, this way it is more likely that we’ll get the same result everywhere. CSS reset is nothing more than simple CSS code using all element selectors and values. It should be in the beginning of CSS file, or if it is loaded separately then it should be loaded first. There are lots of different resets that you could use and every CSS framework has its own CSS reset. All of them are very similar and you can use any one of them. I recommend searching the internet for different versions and doing a comparison. I am using a modified version where I have added some generic classes like left, right etc. this sort of building your own predefined styles is the first step to making your own framework so I am sure at some point you will do the same. Here’s the code for my CSS reset:
146
CSS
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, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { border:0pt none; font-family:inherit; font-size:100%; font-style:inherit; font-weight:inherit; margin:0pt; outline-color:invert; outline-style:none; outline-width:0pt; padding:0pt; vertical-align:baseline; } table { border-collapse:separate; border-spacing:0pt; } caption, th, td { font-weight:normal; text-align:left; } blockquote:before, blockquote:after, q:before, q:after { content:""; } blockquote, q { font-size:16px; font-style:italic; margin:20px; quotes:"" ""; } strong, b { font-weight:bold; } em, i {
Frontend Guide
147
font-style:italic; } * { margin:0pt; padding:0pt; } .right { float:right; } .left { float:left } .clear { clear:both; height:1px; } .wrap { width:950px; margin:0px auto; } .noright { margin-right:0px !important; padding-right:0px !important; } .noleft { margin-left:0px !important; padding-left:0px !important; } body { font-size:12px; font-family: Arial, Helvetica, sans-serif; } sub { vertical-align: sub; font-size:60%; } sup { vertical-align: super; font-size:60%; } a { text-decoration:none; }
148
CSS
a:hover { } a:active { }
As you can see all of the elements have been reset and some of the generic elements have been defined.
3.14. !important declaration In the section on inheritance we saw the rules for using property values. Inheritance is one of the most powerful CSS options and using it along with good code planning will open up lots of possibilities. In some situations we would want to disregard prioritization rules and use a specific value instead. We can achieve that by using the !important declaration. Letâ&#x20AC;&#x2122;s write a simple example in order to see how this declaration works. Weâ&#x20AC;&#x2122;ll make one paragraph and one div that will contain another paragraph. <p>Text goes here</p> <div><p>Text goes here as well inside a div</p></div> p {color:blue; } div p { color:red; } So, as you can see every paragraph will have its content highlighted in blue, but the one inside of a div will have its content in red. If we add the !important declaration for the blue items, then that value will be used everywhere and prioritization rules will be disregarded. p { color:blue !important; }
Frontend Guide
149
This is very useful option, but with the right code planning you will rarely need to use it. The situations where you might use it are the ones where you don’t have full control over the page style, for example if a script has loaded its own style or something like that.
Figure 3.58: !important declaration
3.15. Fluid, fixed and elastic layout In the previous examples along with the other things we have seen couple of layout options and different techniques for building them. In each of those situations we’ve used a fixed width wrapper class so all of the inner elements were the same size. This is the most common layout and it is called a fixed layout because all of the user settings like screen resolution, window size and everything else won’t affect our layout. On the other hand, fluid layout is adjusted to the screen size by expanding or contracting each element and its content. The primarily unit size for fluid layouts is percentage to allow elements to have dynamic dimensions. It is not necessary for all of them to be in percentages but the ones that should expand and contract have to be. In order to make a good fluid layout we should also set min-width and max-width to the wrapper as its minimum and maximum size. 150
CSS
If we don’t use these properties things can become absurd in some very large or very small resolutions. As an example you might see a whole paragraph on screen as one text line. There are both good and bad sides for both of these layout types:
Fixed layouts are mostly used in the situations where you need a complete control over the design and all elements need placement in an exact spot In order to avoid horizontal scroll bar and to match most display resolutions the wrapper is usually set to 960px or 760px and positioned to the center of the screen Fluid layout gives more user-friendly impression by adjusting itself to the screen size and filling the missing space with content Fluid layout is mostly used for situations with lot of page content to allow content to arrange itself in the nice way Older versions of Internet Explorer don’t support max-width and mix-width
Along with these two layout types there is another one that is actually a mix of these two types. It is called elastic layout. In this case em unites are used for all content. This way the design can keep its original element/content proportions, including text size, images size etc. The bad thing about elastic layouts is that it is very difficult to make and to look good in every browser. So we won’t cover it in this book. In any case the design type will be the key factor for our layout choice and we don’t have to strictly use all of the properties for that type. In other words we can combine layouts to suit our needs. The most used combination is a fluid content part and a fixed sidebar. Now let’s build two examples to get the better idea on how this works. Our first one will be a pure fluid layout and the second one will be combined with fixed values.
Frontend Guide
151
3.15.1. Example 25 - Fluid layout We’ll use our previous layout example with three columns where we have one left and one right sidebar and the main content in the middle. In HTML we’ll move the right div after the content div. First thing to do in CSS is to set maximum and minimum values for our wrapper. Sure, you could go on without it but as we had explained earlier, it helps us avoid absurd contraction or expansion and therefore a bad layout. Most commonly these values are 780px and 1260px to suit the most resolutions. We’ll change our wrapper to this: #wrapper { margin:20px auto; min-width:780px; max-height:1280px; border:1px solid green; padding:10px; } margin property moves the wrapper from the screen edges so that it displays nicely. #content { border:1px solid blue; float:left; width:60%; } #sidebar { width:20%; border:1px solid orange; float:left; } #right { width:20%; float:right; border:1px solid lime; } 152
CSS
We have added some arbitrary widths for these elements that should be in one line. Notice that their sum has to be 100% in order to fit the container.
Figure 3.59: Fluid layout
3.15.2. Example 26 - Combined fluid layout As mentioned before this layout type uses a fluid approach to the parts with lot of content and fixed approach for the rest. <div id="sidebar">sidebar</div><!-- sidebar --> <div id="right">Right sidebar goes here</div> <div id="content">â&#x20AC;Ś</div><!-- content--> #sidebar { width:200px; border:1px solid orange; float:left; } #right { width:200px; float:right; border:1px solid lime; } #content { Frontend Guide
153
border:1px solid blue; margin:0 0 0 200px; } Now our left and right sidebar have fixed widths but our content doesn’t have a width definition and it will change according to the screen size.
Figure 3.60: Combined fluid layout
3.16. CSS in modern design This chapter “CSS in modern design” has been written by good friend and business partner James Koster. James is brilliant and award winning Web designer, who is known amongst his peers as an HTML and CSS legend. He has made a huge impact on the Web 2.0 revolution. In this chapter James explains how important CSS is in modern Web design; so much so, that we are reaching a point where graphic editing tools are no longer necessary.
A little History With the advent of HTML, after the image format war, the web design industry began to take shape people were unsure as to how to tackle 154
CSS
it. An exciting period was ahead, a transition from web pages being purely text to including tables, images, different typefaces and colors. HTML code was restrictive in its infancy so web site designs were primitive. There was also the browser war between Netscape and Microsofts Internet Explorer to cause more havoc. Web design didn't really take off until the early 00's when CSS was adopted across modern (of the time) browsers and the community as a whole began to take notice of web standards. But old habits die hard and while we evolved hastily the design process remained mostly unchanged. 1. Produce a flat design visual in an image editing application 2. Code the flat design in HTML upon approval Despite the rapidity of which code could now be written, plus the speed that styles could be applied to content via CSS, designers still used this tried and tested format when designing web sites. Now, however, with the ever-increasing popularity of javascript not the mention HTML5's introduction and the possibilities that CSS3 have granted us, that age-old design protocol has changed. Modern Times Fast forward to 2011 and we see a much more stable industry. Browsers have settled around a set of standards and designers no longer have to choose one to focus on. Javascript libraries have established themselves and web sites not utilizing javascript in some form are probably more rare than ones that do. Code is cleaner, more semantic and this has created some wonderful opportunities for web designers to produce beautiful work.
Frontend Guide
155
Thanks to these progressions the classic, reliable format for designing web pages has finally begun to change. Designers and clients alike have come to understand that "content is king" and a web sites usability is far more important than having a flashy two minute animated introduction video. We are also aware that users are surfing the web from not only a multitude of browsers but a wide range of devices too. Considering these facts, sending a client a flat visual of a web site design seems rather silly. It will look pretty, but it won't communicate how the site will look in Webkit browsers compared to Mozilla or Internet Explorer. It won't illustrate the sites performance on mobile devices like iPhone or iPad and the client will not be able to interact with any of the javascript powered functionality. Even dropdown menus - a constant fixture in modern web design are difficult to demonstrate in a flat design visual, particularly if they are animated in some way. These realizations, coupled with the efficiency of modern code have garnered a revolution. Web sites are no longer designed in Photoshop. They are designed in the medium which they are to be displayed- the web browser. When you think about it, it makes perfect sense. The client gets to see exactly what will be delivered. They can even begin user testing at the concept stage. The design can also be trialed across the spectrum of devices and web browsers in a fraction of the time it would take to create flat visuals for every single medium; not to mention the fact that it will help speed up the development process. This format has produced a breakdown in web designer roles and job titles. There are becoming more and more layers in the design process. In the past, a "web designer" would be able to build an entire web site from scratch. Now however, the intricacies of building a web
156
CSS
site are much more delicate and new roles have been created from that. If you're reading this book the chances are you will be a front end designer / developer. Your role is to take the UX specialists wireframe, create the design and code a HTML template which is then passed on the development team to build the actual product. If you're reading this book the chances are you will be a front end designer / developer. Your role is to take the UX (User Experience) specialistâ&#x20AC;&#x2122;s wireframe, create the design and code an HTML template, which is then passed on the development team to build the actual product. It's important that your code, at this point, be strong because the majority of it is going to be used on the finished, live web site. You're responsible for which version of HTML you use, which javascript library is included, how much CSS3 is used etc. Needless to say it's vital that research is done before making these choices but there are staple best practices to which we should adhere, regardless of the technology we choose to use. Code should always be clean, semantic and consistent. It may be tiresome placing comments throughout your documents, but it will potentially save you (or someone else) a lot of time in the future. You should also endeavor to minify and consolidate javascript and CSS files once the template has been signed off. Little things like that can have a massive impact on the performance of the finished article. Making the choice as to whether to utilize HTML5 or CSS3, for example, can only be done with the necessary knowledge. While you might not be using it immediately, I would always recommend staying closely in-touch with bleeding edge code and techniques so when the opportunity presents itself, you have a strong argument to use it. Frontend Guide
157
There are always a lot of instances where new code can be added as a progressive enhancement. It's a great feeling when a client comes to you and says, "Hey, my web site's changed, there's loads of lovely soft rounded corners and drop shadows! When did you do that?".
3.17. Conclusion CSS is a powerful language and you have been presented with its main functionalities and principles along with the real use examples. Today, a good CSS knowledge is absolutely necessary for any Web development area. HTML 4 and CSS 2 have shaped the Web you can see today and no matter what kind of business logic is “under” the frontend part it is all limited to how the frontend can show it. Because of that, Web development has reached a place where the things were just rearranging shapes and nothing major had been done before the HTML5 and CSS3 announcement. HTML 5 is rich with new options and CSS3 is there to back it up. That way in some time we’ll get the new standards for the global Web.
158
CSS
4. JavaScript We have seen how HTML is used for displaying information and CSS for styling that information. Using these two technologies we can’t generate any information, we can just display them in a static way and once the page is loaded it won’t change. In order to make the page more dynamic static pages are usually combined with some scripting language on the client side. Today the most popular one is JavaScript. It is supported by every Web browser and it is run on the client side. With JavaScript we have lot of DOM manipulation options and that way we can enrich our pages with various effects. Therefore its primary use is to enhance user experience, user interactivity, make AJAX requests etc… JavaScript uses lot of names and conventions from Java language and most of the things Java has inherited from C language. But besides that these languages have no other similarities and actually they are very different. JavaScript is dynamic, weakly typed language with modest object oriented possibilities. On the other hand, JavaScript gives us flexibility so we can use it as a procedural language, object oriented language and such.
4.1. History JavaScript was developed by Brendan Eich and its original name was Mocha. After that it was called LiveScript and eventually JavaScript. It was first implemented into Netscape in 1995 and that was a huge success. Based on that Microsoft made JScript, corrected some of the JavaScript problems and implemented JScript into InternetExplorer 3.0 in 1996. Today JavaScript is supported by every browser and it is part of the ECMAScript standard along with some other languages like JScript Frontend Guide
159
and ActiveScript. There are a lot of popular frameworks for it like jQuery and MooTools as well as the technologies depending on JavaScript like AJAX. We’ll talk more about all of this later. JavaScript engine is the software inside of the Web browser that interprets JavaScript. First engine was called SpiderMonkey and was written by Brendan Eich in C language. After that most of the Web browser companies have written their own engines like V8 for Chrome, Rhino for FireFox in Java, Chakra for InternetExplorer, Nitro for Safari, Futhark for Opera etc… Mozilla foundation is officially in charge for development and “JavaScript” trademark belongs to Oracle Corporation.
4.2. Features
160
JavaScript is a dynamic typing language where types are associated with values, not variables. This means that at one point a variable can be one type and later on change to another JavaScript objects are actually associative arrays and mostly everything is object based. This means that if we write object.a = 10; and obj object["a"] = 10; that is the same thing. This way we can add new properties and values as we like Functions are the first-class functions and they represent objects as well. For this reason they have their properties and values and they can be treated as every other object. For example you can assign a function to a variable etc For some functionality like inheritance and creating object JavaScript used prototype based approach which clones the existing objects instead of using them again like in other object oriented languages There is no difference between methods and functions and functions can have a random number of parameters JavaScript
JavaScript supports regular expressions for text manipulation Different JavaScript engines provide different possibilities but mostly it is all standardized
4.3. Development tools In order to use JavaScript we only need the Web browser and there is no setup required. Unlike other programming languages, JavaScript doesn’t have an option for displaying content on the standard output so in order to test different values and results mostly alert option is used; but I suggest the better one and that is using console log inside of the FireBug, web development tool. So instead of writing: alert("test"); You should write: console.log("test"); And instead of alert window we’ll get that result inside of the FireBug console.
Figure 4.1: FireBug JavaScript console
You would also need some code editor, usually that is the same one used for HTML and CSS code so you can use the tools described at the beginning of the book.
Frontend Guide
161
4.4. JavaScript basics In this part you will get to know the JavaScript basics. For the ones who have never done programming I recommend reading this part carefully and for the ones who have done some programming and know the basic things of any programming language like: what are variables, objects, control structures, operators, functions etc… feel free to skip this part.
4.4.1. Use in Web pages In order to use JavaScript on some page you have to load it as we loaded CSS code. There are two options for that:
As external file usually loaded inside of the head part (of HTML): <script type="text/javascript" src="script.js"></script> this way we can use one script on multiple pages. JavaScript files have .js extension.
Inside of the page. If we want to define some functions that will be either at the beginning or at the end of the document or if we want to output something then on the place we want to show that output. <head> <script type="text/javascript"> // JavaScript here </script> </head> … <script type="text/javascript"> // JavaScript here as well
162
JavaScript
</script> </body> </html> Notice: If some of the functionalities require that the document is fully loaded before that function can be run then mostly we’ll have to load JavaScript at the end of the page.
4.4.2. Comments There are two types of comments:
Single line <script type="text/javascript"> // This is comment </script>
Multiline <script type="text/javascript"> /* this is comment */ </script>
4.4.3. Variables Variables are defined by the use in order to keep some values, expressions or operations. In JavaScript variables are created by writing the keyword var at the beginning followed by the variable name. var x; var title; If we want to assign it a value while defining it we’ll use the “=” operator: Frontend Guide
163
var x = 5; var title = "Frontend guide"; Keyword var is not required and if you don’t use it you will get the same result. But I suggest using it when creating new variables so that you know when and where are they created. Once it is created it can be called only using the variable name (so without var). Variable name has to start with a letter, underscore or dollar sign and it can contain alphanumeric values, numbers and underscore. It cannot have empty spaces.
4.4.4. Example 1 - Printing variables In HTML body part add the following JavaScript code. It is a very simple example and it doesn’t require an explanation. <script type="text/javascript"> var x = 5; document.write(x); // 5 x = 7; document.write(x); // 7 var y = 10; x = y; document.write(x); // 10 </script>
4.4.5. Constants Unlike the variables, constants can’t change their value and they are created using the const keyword. const pi = 3.14;
164
JavaScript
4.4.6. Values In JavaScript variable values can be:
number (numeric): 15, 3.14... boolean (logic): true or false string: “Some text” null: special type without a value undefined: default type if there is no value object like: function, array, date, RegExp
4.4.7. Operators Like in the any other programming language we can use various operators in JavaScript. These are the most common ones.
4.4.7.1. Arithmetic operators. If y = 10 then we get the following values: Operator + * / % ++ --
Description Addition Subtraction Multiplication Division Modulus Increment Decrement Negation
Example x=y+5 x=y-5 x=y*5 x=y/5 x=y%5 x=++y x=--y -y
Result x=15 x=5 x=50 x=2 x=0 x=11 x=9 y = -10
Figure 4.2: Arithmetic operators
4.4.7.2. Assignment operators If x = 6 and y = 2: Frontend Guide
165
Operator = += -= *= /= %=
Example x=y x+=y x-=y x*=y x/=y x%=y
Same as x=x+y x=x-y x=x*y x=x/y x=x%y
Result x=2 x=8 x=6 x=12 x=3 x=0
Figure 4.3: Assignment operators
There are also operators for working with bits but at this point they are not important for us.
4.4.7.3. Example 2 - Dynamic typing Weâ&#x20AC;&#x2122;ll create one example to see how one variable can be one type and then later on different type and how we can use operators on the different variable types. Add the following code to the body part: <script type="text/javascript"> var x = 5; // 5 x = "number five"; // number five var y = "the number is " + x; // the number is number five y = "5" + 5; // 55 </script> As you can see we can change variable types as we want and when we are performing an addition with different types JavaScript will change one of them so that operation can be completed. The rule is if we are trying to add a string to the number then the number will become a string.
166
JavaScript
4.4.7.4. Comparison operators These operators are used to check whether something is true or false and also to check if some variables and values are equal or not. If we set x = 10 we get the following results:
Operator Description == Is equal === Is equal (type and value) != !==
Is not equal Is not equal (type and value)
> < >= <=
Is greater than Is less then is greater than or equal to is less than or equal to
Example x==5 is false x===10 is true x==="10" is false x!=6 is true X!==10 is false x!=="10" is true x>6 is true x<6 is false x>=6 is true x<=6 is false
Figure 4.4: Comparison operators
The result of these operators is always the same: true or false, so we will use them as conditions and based on their result perform different actions.
4.4.7.5. Logical operators If x = 5 and y = 10. Operator && || !
Description Logical and Logical or Negation
Example (x < 10 && y > 5) is true (x==7 || y==7) is false !(x==y) is true
Figure 4.5: Logical operators
Frontend Guide
167
4.4.7.6. Conditional operator This is the special operator type and along with it there are other special operators which will be mentioned later. condition ? value1 : value2; If condition is true operator will use value1 if it’s not it will use value2.
4.4.8. Special characters While working we can use some of existing special characters to get different values inside of a string. They are used in the combination with the escape character marked with “\” followed by the value we want to print. For example if we want to use quotations inside of a string we would write this: document.write ("This is \"some \" text"); // This is "some" text Here are the other values which can we use:
Code \' \" \& \\ \n \r \t \b \f
Result single quote double quote ampersand backslash new line carriage return tab backspace form feed Figure 4.6: Special characters
168
JavaScript
4.4.9. Statements JavaScript file is actually a set of statements which are executed from top to bottom or on some user action. If we want to write a simple statement for printing some text on the screen we can use the following code: document.write("Frontend guide"); Semicolon at the end of the statement isn’t required but I recommend it. That way you can write multiple statements in one row and have clearer code. You should also notice that JavaScript is case sensitive language which means that it makes a distinction between letter cases.
4.4.9.1. Conditional statements These statements are executed if condition is true:
if … else Check whether some condition is true or false: if(condition) { // do this } else if (second condition) { // do something else } else { // if first and second conditions are false do this }
switch Check whether the expression matches to some of our cases: switch (expression) {
Frontend Guide
169
case "value1" : // do this break; case "value2" : // do something else break; default: // do this eventually } 4.4.9.2. Loops Loop is the set of statement that are repeated while some condition is true: ď&#x201A;ˇ
for Basically same as in every other language: for (var i = 0; i < 10; i++) { // this will be executed 10 times }
ď&#x201A;ˇ
while and do â&#x20AC;Ś while These two loops are similar just the first one is checked at the start and the second one is checked at the end of it: while (true) { // infinite loop } do { // first do something and then check for condition } while (condition)
170
JavaScript
4.4.9.3. label, break and continue Along with the conditional statements we can use label, break and continue to get more control over their execution. Label marks a part of the program on which we can redirect our program execution. For example we can mark a loop with label and then use break and continue to tell the program where to stop or proceed. label :
statement
So if we want to label a loop we can use the following code: loopName: while(true) { // do something } Break statement is used for stopping execution of the loop, switch or label statement. If you use break without the label (break;) then the current statement is terminated and skipped to the next one. If it is used with the label (break label;) then it stops the execution of the statement marked by that label; for (i = 0; i < 5; i++) { // do something if (i == 3) { break; } } On the other hand continue is used for starting the loop again or label statement. It can be also used in combination with label to start a specific statement or without it to start a next statement.
Frontend Guide
171
for (i = 0; i < 5; i++) { // do something if (i == 3) { continue secondLoop; } }
4.4.9.4. Object manipulation JavaScript provides us also with an easy way for object iteration:
for ... in Makes an internal variable that holds a current iteration value and executes the statement block for each value. for (variable in object) { // do something } In other words for each property inside of that object is accessed as the current variable for that iteration. Since array is the same things as object in JavaScript we can access the array elements like this. We’ll talk more about this later.
for each ... in Similar as for...in just in this case it iterates through property values and not the names.
4.4.10. Exceptions In order to better control program execution JavaScript provides us with a option for handling exceptions. If we know that some part of the code can cause an error we can put it inside the try - catch block and not brake our program. 172
JavaScript
Try - catch block tests the code part inside of try part and if it causes an error then catch block will be executed instead of it. Catch block usually tries to describe that error and provide information why code block couldn’t be run. try { //this can cause an error }catch(e){ // handling errors } There can be also a finally block that will be executed in any case. try { //this can cause an error }catch(e){ // handling errors } finally { // do this no matter what } Default “catchable” error types are:
Error EvalError RangeError ReferenceError SyntaxError TypeError URIError
These are all JavaScript errors and we can also catch DOM errors like DOMException. In order to get a better error definition we can also set multiple catch blocks for different error types. catch (e if e == "URIError") { ... }
Frontend Guide
173
Eventually we can define our own exception types using the throw statement: if (condition) { throw "error_name"; } Since errors are also objects we can access their attributes like name and message: try { … } catch (e) { console.log(e.name);// 'Error' console.log(e.message); // Error message }
4.4.11. Functions Function is the set of statements that performs some task for us. When we define a function inside of JavaScript code it won’t be executed until it is called by us or some event, other function etc… Function syntax is: function functionName (parametar1, parametar2, …., parametarN) { // function body } Functions are defined with a function keyword following by the function name and brackets with optional parameters. Parameters are values sent to the function when calling it and they can be used only inside of the function body.
174
JavaScript
In order to call a function we have to write its name and brackets with optional parameters. functionName(); // call a function to be executed
4.4.11.1. Defining and calling functions Here is an example of the simplest function used only for writing some text. This function has no parameters or return statements. In head part we’ll write the following code: <script type="text/javascript"> function printText() { document.write("Number 5"); } </script> Now if we open that page nothing will happen since we’ve just made a function and haven’t called it yet. Now we’ll add the following code to the body part: <script type="text/javascript"> printText(); </script>
4.4.11.2. Function parameters In order to make the previous example more interesting we’ll add a parameter that represents a number to be printed. <script type="text/javascript"> function printText(a) { document.write("Number " + } </script> Frontend Guide
a);
175
Parameter name is arbitrary and you can use whatever you like (in this case it was “a”). We can access parameters values inside of the function block using their names. <script type="text/javascript"> printText (10); </script> We have used an integer as parameter type in this example, but we also could have used a string. At this point that doesn’t matter since JavaScript will change the type for us, but sometimes we’ll need to take care of that by ourselves. If we want to send multiple parameters to the function we will separate them by comma.
4.4.11.3. Parameter domain Parameter domain is the part of the code that a parameter exists. Function parameters only exist inside of the function body and they are called local variables. This means if we send a parameter to some function we can’t access it outside of the function. Instead for example we can use global variables available in the whole code. Let’s take a look at the following example: <script type="text/javascript"> function printText(a) { document.write("Number " + } document.write("Number " + a); // Here “a” doesn’t exist </script>
a);
Exercise: This example where we know the error will be reported try to put into the try - catch block.
176
JavaScript
So far all parameter that we have used where primitive type but if we send an array or some other objects to the function and change its value inside of the function, then that object will be change globally and not just inside of the function. We will talk more about this in the objects part.
4.4.11.4. Return statement If we want to use a function to do something for us, calculate something or similar and we want to use a result of its work later in the code we will use the return statement. This statement returns some value to the one who have called that function. If we want to write a function that will add two numbers for us we can do it in the following way: function addNumbers(a, b) { return a+b; } Now we can assign the result of that function to some variable and later use it in our code: var result = addNumbers(5, 10); document.write(result); Or we can print it as we call it, without using a variable for the result: document.write(addNumbers(5, 10));
4.4.11.5. Parameter properties In JavaScript we can access function parameters via parameter (argument) object and use its properties. This object is actually an array of the all received parameters. Array count starts from 0 and ends with a number which we can get using the length property. Frontend Guide
177
This way JavaScript doesn’t have to know the total parameters number or if the function has any parameters at all, it is just their order that matters. Now we’ll change our example for adding numbers so that you can send as many numbers as you want and they all will be added and result will be returned. function addNumbers() { var result = 0; for (var i = 0; i < arguments.length; i++) { result += arguments[i]; } return result; } So now we can call this function with a random number of parameters: document.write(addNumbers(5, 10, 2, 3)); // 20
4.4.11.6. Anonymous functions We can add a function definition to the variable and that function is anonymous function since it doesn’t have a name and it is called each time that variable is called. var square = function(number) {return number * number}; Now we can call that variable and function will be executed: square(2);
178
JavaScript
4.4.11.7. Recursive functions Recursive functions are functions that call themselves inside of the function body. When using recursive functions it is important to make a condition that will stop the function at one point otherwise function will run endlessly. For example if we want to calculate factorial of some number we can easily do it with a recursive function like this: function factorial(n) { if ((n == 0) || (n == 1)) { return 1; } else { return (n * factorial(n - 1)); } }
4.4.11.8. Core functions JavaScript has couple of core functions that we can use for converting data types, checking the content etc.
eval isFinite isNaN parseInt and parseFloat Number and String encodeURI, decodeURI, encodeURIComponent, and decodeURIComponent
4.5. JavaScript objects JavaScript is object oriented language which means that along with the core data types we can define our own data types that will have properties, methods etc. Frontend Guide
179
Unlike the other programming languages, JavaScript objects are actually “name-value” pairs which really makes them hash maps, hash tables and associative arrays. Because of that JavaScript is “simple object oriented” language but on the other hand very fast one.
4.5.1. Object properties We can add a random number of properties to the object. Object properties are accessed in the following way: objectName.objectProperty We have already seen how this works for example to get the total number of parameters for some function we can use: arguments.length Where arguments is a core object and length is its property.
4.5.2. Object methods Object methods are actions associated with that object. For core objects we have also core methods but we can make our own methods for our objects. In order to call an object method we’ll use the following syntax. objectName.methodName(arguments); For example we can transform the letter case of some string using the following method: var headline = "Frontend guide"; document.write(headline.toUpperCase()); // FRONTEND GUIDE
180
JavaScript
4.5.3. Core objects JavaScript core objects include:
Array Boolean Date Function Math Number String RegExp
Some of them are already mentioned in the previous example and now here is more details about every one of them.
4.5.3.1. Array Array is the set of values accessed by its name and element index. Elements start from 0 and end with n-1. Arrays are usually used in the situations where we want to assign multiple values to one variable. For example array can be set of: car manufactures, people names etc. We can create an array on one of the following ways:
Creating a new Array object var arrayName = new Array(element0, elemen1, … elementN); var arrayName = new Array(length); There are two options you can use. First one is not to define array length and optionally define array values. Second one is not to define values, instead of that define its length. Let’s take a look at couple of examples:
Frontend Guide
181
var cars = new Array(); cars[0] = "audi"; cars[1] = "bmw"; cars[2] = "opel"; var cars = new Array("audi", "bmw", "opel"); var cars = new Array(3); cars[0] = "audi"; cars[1] = "bmw"; cars[2] = "opel";
Array of literals. In JavaScript array of literals can also be array of objects so we can create a new array like this as well: var things = ["audi", 1, 1.5]; Notice that array elements don’t have to be same type.
No matter what way we create an array we still access its elements via index numbers. The index of the first element is 0 and the last one is array length - 1. We can get the array length by calling the length property which will return us the index of the last element. For example for our car array we’ll get the following result: cars.lenght; // 3 But if we make a new array member with a random index we get the following result: cars[30] = "volvo"; cars.length; // 31 One of the most common things that we are going to do is array iteration and usually some loop type is used for this: 182
JavaScript
for (var i = 0; i < cars.length; i++) { document.write(cars[i] + ", "); } for (var i in cars) { document.write(cars[i] + ", "); } Array methods JavaScript provides us with the following core array methods. Assuming that we have an cars array with the elements: audi, bmw and opel for every example, we will get the following results:
concat() - Merges two arrays and returns the new one cars.concat("1", "2", "3"); ["audi", "bmw", "opel", "1", "2", "3"]
join(separator) - Merges all array elements into the string cars.join(" - "); // audi - bmw - opel
push() - Adds one or more elements to the end of the array and returns new size cars.push("volvo"); // ["audi", "bmw", "opel", "volvo"]
pop() - Removes the last array element and returns its value var last = cars.pop(); // last = opel
shift() - Removes the firs array elements and returns its value
Frontend Guide
183
var first = cars.shift(); // first = audi
unshift() - Adds one or more elements to the array beginning cars.unshift("lexus"); // ["lexus"...]
slice(start, end) - Makes a new array from the existing array part cars.slice(0, 2); // ["audi", "bmw"]
reverse() - Reverse element order cars.reverse(); // ["opel", "bmw", "audi"]
sort() - Sorts array elements cars.sort(); // ["audi", "bmw", "opel"]
indexOf(searchElement [, from]) Searches array for a value and returns its index cars.indexOf('bmw'); // 1
lastIndexOf(searchElement [, from]) Similar as the previous one just the search starts from the end
map(callback[, thisObject]) Returns a new array as a result of action performed on the every array member cars.map(function(item) { return item.toUpperCase();
184
JavaScript
}); ď&#x201A;ˇ
//["AUDI", "BMW", "OPEL"]
filter(callback[, thisObject]) every(callback[, thisObject]) some(callback[, thisObject]) Returns a new array with those elements whose condition result is true.
You should also notice that some JavaScript objects can use some of the array properties and functionalities like length or forEach(). In order to use more array properties and methods we can use an Array generic on the following way: Array.forEach("Frontend guide", function(a) { document.write(a + ", "); });
4.5.3.2. Boolean This is a logical object type, similar to simple logical type. In order to make a new Boolan object you need to use the following syntax: var objectName = new Boolean(value); We can use Boolean object to convert non-boolean values to the Boolean type. var name = new Boolean("guide") ; // true
4.5.3.3. Date With Date object we can easily work with date and time. We can create it on one of the following ways and most of the parameters are optional: Frontend Guide
185
new Date() // current time and date new Date(milliseconds) new Date(dateString) new Date(year, month, day, hours, minutes, seconds, milliseconds) Date and time are calculated on the following way:
Minutes and seconds: 0 to 59 Hours: 0 to 23 Day: 0 (Sunday) - 6 (Saturday) Day: 1 - 31 (day in month) Month: 0 (January) - 11 (December) Year from 1900
var today = new Date(); var date1 = new Date("June 15, 1989 13:30:00"); var date2 = new Date(89, 5, 15, 13, 30);
Date methods We can use the methods from the following categories when working with dates:
“set” methods for setting date and time “get” methods for getting date and time “to” methods for returning string values UTC methods for parsing Date strings
4.5.3.4. Function Functions are explained earlier.
186
JavaScript
4.5.3.5. Math With Math object we can do various mathematical tasks and use mathematical constants. We don’t need to make a instance on Math object in order to use it (no new keyword). In JavaScript we can use the following math constants: Math.E, Math.PI, Math.SQRT2, Math.SQRT1_2, Math.LN2, Math.LN10, Math.LOG2E, Math.LOG10E. For example if we want to use Pi number we’ll write: var x = Math.PI; // 3.14… As for the methods we can also use usual methods like: abs, sin, cos, tan, acos, asin, atan, atan2, exp, log, sqrt itd...
4.5.3.6. Number Number object has basic numeric constants like smallest and largest numbers that we can use.
Number.MAX_VALUE // largest number Number.MIN_VALUE // smallest number Number.NaN // special type Number.NEGATIVE_INFINITY // negative infinity Number.POSITIVE_INFINITY // positive infinity
4.5.3.7. String String object is similar to the simply string type. On both of them we can use string properties and methods and JavaScript will convert simple type to the object for us (temporarily). You can make a new string on the following ways: Frontend Guide
187
var text = "some text"; // string literal var text = new String("some text"); // string object There is lot of methods available for us in order to do things like search, text replacement, cutting etc… Here are the most common ones:
charAt, charCodeAt Returns a character or characters on a specific position
indexOf, lastIndexOf Returns a position for some sub-string as the first or last position respectively
concat - Combines two values to the new string
fromCharCode - Makes a string from the special Unicode characters
split - Splits string into array of sub-strings
slice - copies part of the string
match, replace, search Used with regular expressions, more about those later
toLowerCase, toUpperCase Transforms string to the lower case or uppercase
4.5.3.8. Regular expressions Regular expression object represents a pattern of characters. With RegExp objects we can look for a specific pattern in text and later do 188
JavaScript
some actions over it. You can create a new RegExp object on one of the following ways: var text = new RegExp(pattern, modificator); var text = /pattern/modificator; Modificators are used to control the search better:
modificator i - difference between lowercase and uppercase doesn’t matter modificator g - does a global search by searching for more matches modificator m - multiline search
Pattern can be simple set of characters like /frontend/ or combination with special characters like /frontend (\d+)\.\d*/. Simple patterns look for a direct match with a text sub-string while the complex patterns can search more than that. There is a lot of special characters for regular expressions and I leave that for you to read since there is a good documentation online for it. For example if we want to check if the word frontend exists in the following text we can write this: var text="Frontend guide"; var pattern=/frontend/i; document.write(text.match(pattern)); // Frontend If we want to find all “o” letters or check how many are there we can use this: var text="Frontend guide"; var pattern=/o/g; document.write(tekst.match(pattern)); // o, o
Frontend Guide
189
As you see match method is a string method and along with it we can use couple of other string methods like: replace, search i split and all of them work with regular expressions. Methods exclusively for RexExp object are exec and test. The first one searches the string for some value and if it finds it that value is returned otherwise null is returned. The second one also searches for some value and it returns true or false depending on the search result. var pattern=new RegExp("e"); document.write(pattern.exec("Frontend")); // e document.write(pattern.test("Frontend")); // true
4.5.4. Custom objects Besides the core objects we can also create our own objects. Custom object can be made in two ways. The first one is using object initialization and the second one is using constructor function. We are going to demonstrate the second one. Constructor is the function with the same name as the object type. In order to create a new object we have to call constructor using the new keyword. We have already seen this in the previous examples. Along with the name object can have properties and methods. Now that we know what we need to create a new object weâ&#x20AC;&#x2122;ll write a simple example. First let us write a construction function that will set random properties. function person(name, surname, id) { this.name = name; this.surname = surname; this.id = id; } 190
JavaScript
Keyword this is very important and basically it tells the program that those properties are for the current object we are working for. Now we can create several objects whose type is person. var jane = new person("Jane", "Doe", 12345); var john = new person("John", "Doe", 67890); And now access their attributes: jane.name //Jane john.surname // Doe As a constructor parameter we can use objects and not only simple data types. We will create a new object type that will represent a company. function company(name, address) { this.name = name; this.address = address; } var google = new company("Google Dublin", "Ireland"); var sony = new company("Sony distribution", "Japan"); Now weâ&#x20AC;&#x2122;ll change the persons constructor in order to have a new parameter: function person(name, surname, id, company) { this.name = name; this.surname = surname; this.id = id; this.company = company; } And create new objects, now with company as a new parameter:
Frontend Guide
191
var jane = new person("Jane", "Doe", 12345, google); var john = new person("John", "Doe", 67890, sony); Now we can access the new values on the following way: jane.company.address // Ireland john.company.name // Sony distribution Or change one of the values: john.company.name = "Sony headquarters"; Objects can also have custom methods. All we need to do is to tell an object which function to use like this: object.methodName = functionName; Weâ&#x20AC;&#x2122;ll create a new function that will display name and surname of a person object and assign that function as a method for the person type: function showPerson() { var result = this.name + " " + this.surname; document.write(result); } Now weâ&#x20AC;&#x2122;ll change our person constructor to this: function person(name, surname, id, company) { this.name = name; this.surname = surname; this.id = id; this.company = company; this.showPerson = showPerson; } 192
JavaScript
jane.showPerson(); // Jane Doe john.showPerson(); // John Doe These where the JavaScript basics and I think that this is more than enough that you need to know in order to do frontend development. Your part will mostly be handling DOM elements but it is good to know other things presented here especially if you are not familiar with some other programming language.
4.6. Browser objects So far you have mostly seen all of the JavaScript functionality and you should have a good idea about the markup -stylesheet languages and now this programming language. But everything we have done with JavaScript has resulted in text ouput. But the true power of JavaScript is DOM manipulation. JavaScript can access and change html elements, properties, CSS rules, values, page methods and much more. With these options we can make highly interactive Web pages that can react on users’ actions and change static HTML and CSS. Before we actually see how JavaScript can change DOM we’ll see another interesting functionality and that is use of Web browser objects. They don’t have anything to do with the page content; they are used for accessing application (Web browser), current windows, screen etc.
4.6.1. Window object This object represents the current active window. If there are frame or iframe elements on the page there will be different window objects for each of them. Window object properties and methods are not equally supported in different Web browsers so here is the list of the safe things to use. Frontend Guide
193
You should also know that other objects like: document, navigator, screen, history and location are part of the window object so they are accessed through it and we’ll talk about those later.
closed Since JavaScript can close and open windows for us this property tells us whether the windows is opened or not with Boolean value. newWindow = window.open(…); newWindow.closed; // false
frames Returns an array of active frames and iframes for(frame in frames) { … }
name Returns or sets frame name window.name;
pageXOffset, pageYOffset Represents vertical and horizontal page offset from the left top cornet. I am sure that you have seen lot of times effect of loading new content when you scroll at the bottom of the page. This property could be used for it.
parent Returns the parent of the current window object. This way we could for example change the parent from the frame or iframe.
self Returns active window
Window object properties include: 194
JavaScript
alert("message") Displays alert window with message
close() Closes active window object
focus() Sets focus on the active window object
window.open(URL,name,specs,replace) Opens new window with set of parameters
print() Prints the content of the active window
scrollBy() i scrollTo() Scrolls the content for a random number of pixels
Full list of properties and methods is available online but at this point it is not relevant for us, since you are rarely going to use it. Instead we are going to use more modern way of creating dialogs, windows and everything else, by using some JavaScript framework.
4.6.2. Navigator object This object contains all of the information about Web browser.
appCodeName Code application name like mozilla
appName Browser name like Netscape
Frontend Guide
195
appVersion Browser version like 5.0 (Windows; en-US)
cookieEnabled Boolean value of cookie support
platform Platform for witch Web browser is compiled like Win32
userAgent Header value that Web browser is sending to the server
4.6.3. History object Holds information about visited addresses within the current window. Because of that it is accessed through the window object.
history.length Number of visited pages
window.history.back() Loads the previous page
window.history.forward() Loads the next page
window.history.go(parameter) Loads the specific page, number or URL
4.6.4. Location object Contains information about the current address. It is also accessed through the window object. If we assume that the
196
JavaScript
http://frontendguide.com/admin/test.html#top is loaded we will get the following results:
hash Page position #top
host Hostname and port www.frontendguide.com
hostname Just hostname www.frontendguide.com
href Complete page URL http://www.frontendguide.com/admin/test.html# top
pathname URL path /admin/test.html
port Port number - default is 80
protocol Protocol used - http:
search Set of parameters sent to the page (query) - ?subscribe=yes
assign(URL) Loads new document
reload() Reloads the current document
Frontend Guide
197
replace(URL) Replaces the current document with the new one
4.7. HTML DOM objects So far with the objects learned so far we can change the things about Web browser and page but not the content. That is where we have to use DOM objects. These objects include document objects, element objects and event objects, used for accessing all elements, changing all elements and handling user actions respectively. It is important to know that this is the basic of element manipulation but mostly we are not going to use it this way. Instead we’ll use some framework built on top of this. Since that way we get more options and simpler code.
4.7.1. Document object Every loaded page represents a document object and that way we can access its content. Safe properties of this object are:
cookie Returns all the cookies for the active document document.cookie;
domain Returns the domain name for the active document document.domain; // www.frontendguide.com
title Returns or sets document title
198
JavaScript
document.title = "new title";
URL Returns URL for the active document document.URL; // http://www.frontendguide.com/test.html
With JavaScript we can access various object collections. In this case these collections are sets of elements of the same type. We can use one of the following collections:
anchors[] Returns an array of all the anchor tags
forms[] Returns an array of all the forms
images[] Returns an array of all the images
links[] Returns an array of all the links
Since all of these collections are actually arrays we can use array properties and methods on them as we learned before. Document object methods include:
open(), write(), writeln(), close() Used for opening writing stream, writing content into the open stream, writing content line into the open stream and closing the stream, respectively. For instance if we want to create a new document we can use the following code:
Frontend Guide
199
var newDoc = document.open("text/html","replace"); var text = "<html><body>content</body></html>"; newDoc.write(text); newDoc.close();
getElementById("id") Accesses the element with a specific Id. If there are more results the first one will be used. document.getElementById("header");
getElementsByName("name") Accesses all elements that matches with name attribute value. document.getElementsByName("x").length;
getElementsByTagName("tagName") Accesses all elements that are specific tag type. getElementsByTagName("span");
4.7.2. Element object For each page element we can use various properties and methods. Previously with the document object we have seen how to access elements and now here is how to change them. Once again we can use core collections like:
200
attributes[] All attributes of an element
JavaScript
document.getElementById("first").attributes
childNodes[] Children array of an element document.getElementById("first").childNodes
As for the properties and methods, element object has many so here is the list of the most interesting ones:
className, id, style, title Returns or sets values for the genera attributes document.getElementById("myid").className = "newClass";
innerHTML Returns or sets element content by replacing the current content document.getElementById("myid").innerHTML = "content";
nodeName, tagName Returns the element name document.getElementById("myid").nodeName; // DIV
firstChild, lastChild Accesses the first and the last element child
nextSibling, previousSibling Accesses the next and the previous element sibling
Frontend Guide
201
appendChild(), removeChild(), replaceChild() Adds new child at the end, removes the child and replaces the child respectively
click() Calls the click method
getAttribute(), setAttribute(), removeAttribute() Returns attribute value, sets attribute value and returns attribute respectively
toString() Returns the textual representation of the element
4.7.3. Event object Event object let us perform various actions as user actions like mouse click, keyboard click, mouse hover, changing some values etc… But they are rarely used like that (from HTML code) as already explained in the HTML chapter. Instead we are going to use some JavaScript framework for all that since doing it in pure JavaScript requires lot of complex code. But it is good to know these basics in order to understand what is happening in the background when you are using some framework. Since after all frameworks are built on it. So chapters 4.6 and 4.7 are just quick overview of the basic functionalities and if you would like to use pure JavaScript for accessing and changing DOM you can find the detailed reference on the Internet.
202
JavaScript
4.8. JavaScript Frameworks I am sure that at this point JavaScript gave you an impression that it is a bit complicated and dull language. It is functional but in order to get to the results it takes lot of time and coding. Luckily for us there are a lot of JavaScript frameworks available. They bring JavaScript to the modern level that matches current Web standards. As a matter of fact they have made lot of Web standards and shaped that Web you see today. There are a lot of them available and most of them are truly great products and which one you will chose is completely up to you. In order to use any framework you need to know basics of HTML, CSS and JavaScript.
4.8.1. Modern JavaScript frameworks Each of them is like a small new language and there are several books for all of them. So we will decide on one in this book and that is jQuery. Here is the short overview of the most popular frameworks. I recommend you visit all of them, take a look at the examples, go through the documentation on so you can get to know them better and also make a better decision on which one to use.
jQuery (http://jquery.com/) One of the most popular frameworks with very good support both from the authors and community. That is very important for us so we have lot of documentation and examples available. jQuery is fast and concise library that simplifies all tasks about DOM manipulation, handling events, making requests etc… Because if that jQuery is perfect choice to start with.
MooTools (http://mootools.net/) Also very popular library with good community support. This library is compact, modular and object oriented. It allows us to write powerful and flexible JavaScript code which will perform
Frontend Guide
203
well in every environment.
prototype (http://prototypejs.org/) This framework is made to ease the development of dynamic Web application and lot of other frameworks use this one within their solutions. Prototype is easy to use with class application and it offers excellent support with handling ajax application parts.
script.aculo.us (http://script.aculo.us/) This is an addon to prototype framework which allows us to easily create cross-browser interfaces for animations, testing, ajax etc…
4.8.2. jQuery First of all you should know that jQuery website is the best source for learning it, having huge tutorial database, examples and references. Along with the core library there are plenty of jQuery plugins that provide us some “ready to use” functionality and ease usual tasks. The term “Plugin” generally means an add-on to something that expands its functionality. In order to use jQuery plugins we need core jQuery of course. You can find all plugins in the plugin repository http://jquery.com/plugins/. Another useful part of jQuery is jQuery UI which stands for User Interface. This is like a mini library which provides us with “ready to use” functionalities for standard UI elements. It is similar to jQuery as script.aculo.us is to prototype.
4.8.2.1. Using framework In order to use jQuery we need the core library which actually is just one file in source or minified version. Source should be used for development and minified for production. You can download it from 204
JavaScript
official jQuery website or use one of the online versions from some CDN (Content Delivery Network) like Google or Microsoft. In all of the following examples we’ll assume that jQuery is loaded on the following way: <title>Document</title> <script type="text/javascript" src="http://code.jquery.com/jquery1.5.min.js"></script> <script type="text/javascript"> // code here </script> </head> Without that nothing will work. Also it is (usually) important that we first load jQuery and then load rest of the JavaScript code.
4.8.2.2. Syntax jQuery syntax has two part: selector and action: $(selector).action(); We can use random number of actions, one after another. As for the selectors, jQuery uses combination of Xpath and CSS selector syntax so if you learned CSS selectors you won’t have any problems with these. The following example hides all p elements: $("p").hide(); But if we want this to work properly we have to make sure that DOM is completely loaded and then that code called. If you have tried to run some of the previous pure JavaScript examples and used JavaScript in the head part most of it didn’t execute because of the same thing. JavaScript is trying to select something that isn’t loaded
Frontend Guide
205
yet. jQuery has an excellent solution for it which check just for necessary elements to be loaded. $(document).ready(function(){ // code here }); We will always use this with jQuery, so our every following example should start like this and we’ll just add JavaScript code in to the “//code here” part. <title>Document</title> <script type="text/javascript" src="http://code.jquery.com/jquery1.5.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ // code here }); </script> </head>
4.8.2.3. Selectors With jQuery we can select anything in a very simple way. We can group jQuery selectors in the following way: Element selectors 206
$("*") - All elements $("#header") - element with id=header $(".header") - element with class=header $("div") all div elements $(".class1.class2") - element with class1 and class2 $("#elemenat1 #elemenat2") - Combinators JavaScript
Selectors based on the position
$("p:first") - First p element $("p:last") - Last p element $("tr:even")and $("tr:odd") - Odd and even elements $("ul li:eq(2)") - Third li element $("ul li:gt(2)") - Elements greater than the second position $("ul li:lt(2)") - Elements less than the second position
Selectors based on the attributes
$("[href]") - All elements with that attribute $("[href='test.html']") - All elements with that attribute and value $("[href!='test.html']") All elements with that attribute different from value $("[href$='.php']") - All elements whose attribute value ends with that
Type and state selectors
$(":input") - All input elements $(":input_type") Selects an element based on its type like:text, :password, :radio, :checkbox, :submit, :reset, :button, :image and :file $(":input_state") Selects an element based on its state like:enabled, :disabled, :selected and :checked
Other selectors
$(":contains('frontend')") - All elements with that content $(":empty") - All elements without children
Frontend Guide
207
$(":hidden") - All hidden elements $("p:visible") - All visible elements
4.8.2.4. Events We can work with jQuery events in two ways: First on is to call an event like click of a button. The second one is to assign a function that is going to be executed on that event. So first one is calling it and second one is handling it when it is called.
$("a").click() - Activate click event $("a").click(function(){$(this).hide()}) Call a function when click is activated (so this doesn’t call it here)
Now we can call and handle various events in jQuery. In HTML chapter we have skipped the events part because that is not the good way to do it. It is much better to work with events from JavaScript. This way we won’t have anything for functionality inside the HTML, instead it will be all part of JavaScript file. jQuery supports lot of core events and here is the list of some of them and couple of examples to demonstrate how to work with events inside of the jQuery. Based on that you can easily use any other event in a similar way.
208
bind() - Binds one or more handlers for element click() - Element click function dblclick() - Element double click function live() - Binds one or more handlers for the current and future elements ready() - Makes sure that all elements are loaded submit() - Element submit function
JavaScript
4.8.2.5. Example 3 - jQuery events We’ll make one example that demonstrates working with events. Let’s assume that we have one input, checkbox, textarea and submit. While you change input value document title will change, checkbox will allow or disallow textarea writing and by clicking on the submit button text inside textarea will show in some div. First we’ll write HTML code and setup jQuery. <html> <head> <title>Events</title> <script type="text/javascript" src=" http://code.jquery.com/jquery1.5.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ // code here }); </script> </head> <body> <form action="test.php"> <input type="text" value="" /><br /> <input type="checkbox" /> Editable<br /> <textarea rows="3" cols="10" disabled="disabled"> </textarea><br /> <input type="submit" value="submit"/> </form> <div id="result"></div> </body> </html> This is simple HTML and doesn’t require any explanation. You should just notice that we have defined action attribute for the form so at
Frontend Guide
209
this point when you click on the submit button form will send its data to some page test.php. Now weâ&#x20AC;&#x2122;ll write jQuery code: $("input[type='text']").keyup(function() { document.title = $(this).val(); }); $("input[type='checkbox']").change(function() { if($(this).attr('checked')) $("textarea").removeAttr("disabled"); }); $("form").submit(function(event) { event.preventDefault(); $("#result").html($("textarea").val()); });
Figure 4.7: jQuery events
First we have defined the keyup event for our input. When user types something that action is called and it sets document title as the value of the element on which we are calling that action (this keyword). In this case that is input and input value will be title value. Instead of this keyword we could have used selector for that input and it would be the same result.
210
JavaScript
After that we have defined a change event for the checkbox. This means that whenever user changes the checkbox value that event will be activated. Inside of the block we check the value of the checkbox and based on that assign disabled attribute to textbox. In the end you should pay attention to one more detail and that is event parameter for the submit event function. This function parameter gives us the control about current action execution. In this case we have stopped the default behavior of the form so the form isn’t sending data to another page. Instead we have added the textarea value to the div result. Along with the preventDefault() method there are other methods and properties that we can use so I suggest looking it up on the Internet. Exercise: For checkbox add code that will change the textarea back to disabled when the checkbox is deselected.
4.8.2.6. Effects jQuery has lot of core effects that are very simple to use. These include “ready to use” effects like show, hide, animate and much more. Here is the list of the popular ones:
animate({styles},{options}) Performs an animation for some CSS property with optional parameters like animation speed, type, callback etc.
stop(stopAll,goToEnd) Stops the current animation
fadeIn(speed,callback), fadeOut(speed,callback) Smooth fade in and fade out effect
Frontend Guide
211
show(speed,callback), hide(speed,callback) Shows or hides an element by changing its CSS properties
slideUp(speed,callback), slideDown(speed,callback) Smoothly changes element height and set it to visible or hidden state
4.8.2.7. Example 4 - jQuery effects In order to see how simple is to use these core effect we’ll make one example that demonstrates one animation and slide effect. Let’s assume that we have one hidden div that should be shown on click and that we have another div that will change its dimensions by clicking on its content. First we’ll write HTML and CSS: <style type="text/css"> .toggle { background:red; text-align:center; height:100px; display:none; } #box { background:green; width:100px; height:100px; } </style> … <div class="toggle">content</div> <span id="doit">show/hide</span> <div id="box"><a href="#">Expand</a></div> 212
JavaScript
And add JavaScript like this: $(document).ready(function(){ $("#doit").click(function(){ $(".toggle").slideToggle("slow"); }); $("#box a").click (function(){ $(this).parent().animate({height:300, width:300},"slow"); }); });
Figure 4.8: jQuery animations
By clicking on #doit we simple call the slideToggle function with slow parameter for the speed and jQuery will do everything else for us. Next we also handle click effect and call animate function which will perform on the parent of the element who has called that function. Since the link for calling animate function is inside the div, that div is its parent and that div will do the animation. As animation parameters we have used simple CSS properties and animation speed.
Frontend Guide
213
Exercise: Add code that will change #box to the original dimensions after the animation is completed.
4.8.2.8. Callback Callback is an optional function that will be called after the animation (effect) is completed. So in the situations where we need to be sure that something has finished in order to start something else we can use callbacks. The following example demonstrates a callback that will make an alert after the animation is finished: $("a").hide(1500,function(){ alert("Animation complete"); }); In this case animation speed is in milliseconds but you can use predefined values like slow, fast etc… instead of that.
4.8.2.9. HTML manipulation As for the DOM manipulation which includes changing HTML elements and attributes jQuery offers us lot of powerful options. We have seen some of them on the previous examples and there is the list of the popular ones:
addClass(),removeClass(), hasClass() Adds, removes one or more classes and checks if class exists respectively.
before(), after() Adds content before or after selected element
214
JavaScript
prepend(), append() Adds content at the beginning or end of the element
prependTo(), appendTo() Same as the previous just the syntax is different. In this case first we tell what to add and then where so we can use what we have added as a result somewhere else in the code. We will see this on the example later on
attr(), removeAttr() Adds or removes attribute
html() Adds or returns element content as HTML
text() Adds or returns element content as text
val() Adds or returns value attribute of the element
wrap(), wrapAll(), wrapInner() Wraps one element, all elements or content of elements with HTML
remove() Removes the element from DOM
4.8.2.10. Example 5 - jQuery HTML manipulation We’ll create one example with the following functionality. Table will have two columns representing content and action delete. By clicking on delete that table row will fade out, remove and its Frontend Guide
215
content will appear in the paragraph that represents action status what is removed. Also when you click on the table row it will toggle class highlight. At the and we’ll add one input with “add row” link that will add new table row and set its content to the input content. Here is HTML code: <table> <tr> <th>Content</th> <th>Actions</th> </tr> <tr> <td>Frontend</td> <td><a href="#" class="delete"> Delete</a></td> </tr> </table> <input type="text" value="Row value" /> <a href="#" id="add">Add row</a> <p id="status"></p>
HTML is simple and doesn’t require any explanation. As for the CSS we’ll just add the highlight class with background. I recommend adding additional styles for the table. .highlight { background:yellow; } Here is the jQuery code: $("table tr").live("click", function() { if($(this).hasClass('highlight')) { $(this).removeClass('highlight'); 216
JavaScript
} else { $(this).addClass('highlight'); } }); $("#add").click(function() { var value = $("input").val(); $("table").append(" <tr><td>" + value + " </td> <td><a href=\"#\" class=\"delete\">Delete</a></td></tr>"); }); $(".delete").live("click", function() { $(this).parents("tr").fadeOut("slow", function() { var removed = $(this).remove(); $("#status").text("Removed: " + removed.text()); }); });
Figure 4.9: jQuery HTML manipulation
Frontend Guide
217
You should pay attention to couple of things. First you will notice that we have used live instead of directly using a click action for some elements, for which we have previously explained our reasoning. For elements that are not the part of the DOM at the start, so for future elements, in this example, to be added to the table we have to use live instead of click, otherwise it won’t work. By clicking on the delete link we are searching for the first tr type parent and after the fadeout animation we are making a callback function that will delete the row and add its value to the paragraph. By clicking on the add link we are calling the append function on the table and as the parameter we are using HTML code that will generate new row. Exercise: Read from the jQuery documentation about the delegate method and decide if it is better to use live or delegate method in this example. Instead of append() use appendTo() method and refractor the code.
4.8.2.11. jQuery CSS manipulation At the end let’s take a look how we can change CSS properties with jQuery. We can get or set any CSS property to the element using the css() method which can be in one of the following forms:
218
css("property") Returns CSS property value
css("property", "value") Adds a value for the property JavaScript
ď&#x201A;ˇ
css({"property":"value"," property":"value"}); Adds more properties and values
Since width and height are used a lot there are separate methods for them height() and width() so you can use them like that or through the css() method.
4.8.2.12. Example 6 - jQuery CSS manipulation Weâ&#x20AC;&#x2122;ll create one simple editor that will contain two input elements that represent property and value and by clicking on add link those values will be added to the div as CSS styles. Here is the HTML code:
Property: <input type="text" value="" id="p" /> Value: <input type="text" value="" id="v" /> <a href="#" id="add">Add style</a><p>Result:</p> <div id="result">Content</div> <a href="#" id="remove">Remove style</a> Once again HTML is very simple and here is the jQuery code: $("#add").click(function() { var p = $("#p").val(); var v = $("#v").val(); $("#result").css(p, v); resetInput(); }); function resetInput() { $("#p").val(""); $("#v").val(""); } Frontend Guide
219
$("#remove").live("click", function() { $("#result").removeAttr("style"); });
Figure 4.10: jQuery CSS manipulation
In this example we have defined a click function for add link that check input values and sends them as parameters for the css() function for the div result. When jQuery adds that style we are calling a custom function for resetting input values. At the end we have defined a click functionality through the live function for the remove link. By clicking on it all styles from result div will be removed. Exercise: Add code that will write the current styles of the #result.
4.9. Conclusion It is very difficult to imagine the Web we see today without JavaScript. Therefore JavaScript knowledge is absolutely necessary in order to do frontend development. As HTML and CSS are static, JavaScript gives dynamic aspect to the pages, better user interactivity and better user experience. After this chapter you should be able to understand any JavaScript code, both pure and framework style and therefore write your own code in order to enrich your Web applications. 220
JavaScript
Appendix 1 - Graphics editing Frontend developer job is to transform design into the code. Design files are most often in some of the graphics editing tools like Adobe Photoshop and Adobe Illustrator. Those tools allow us to access all design parts separately through layers instead of working with just one large image. Because of that we need to know how to use those tools in order to cut various images that will be part of our pages. We can group the graphics editing tools to the ones for editing raster graphic and to the ones for editing vector graphic. Vector graphic uses mathematical descriptions for the point to point relations and because of that image will be crystal clear in any size. One of the programs for working with vectors is Adobe Illustrator. On the other hand raster graphic is represented by pixels and each pixel can have different color and illumination. Because of that if we for example zoom image like this we will get blur effect and image wonâ&#x20AC;&#x2122;t look nice. Since it is expected that we produce the same result as how design looks we will always use raster graphics. One of the most popular editing tools for raster graphics is Adobe Photoshop and here are some guidelines and shortcuts that you will need as a frontend developer. Photoshop workspace Photoshop workspace can be organized in various ways. Figure a1 represents the default workspace for the CS3 version and here is an overview of the functionalities that we will use. As for the other versions they might have a slightly different workspace but all the functionalities we are going to use are the same so you can use any version you like. On figure a1 part marked with number 1 represents the list of tools available for us. We are going to use only tools for selecting and Frontend Guide
221
moving and not for drawing. Part 2 represents options for the active tool. For example if text editing tools is selected we will have different options for it like text size, font, color etcâ&#x20AC;Ś Part 3 is the layer part and also folders part that can hold layers. Using layers we can select every design element separately and perform various actions on it not affecting other layers.
Figure a1: Photoshop workspace
From the tools list we are going to use: ď&#x201A;ˇ
222
Move tool (v) Used for moving currently selected element - active layer (one or more). Active layer has blue background. We can move it by simply holding left mouse click and dragging it. If we need to move something with precision for example only by x or y axis we can hold shift key while we are dragging it. Other way to move an element is by pressing the keyboard arrows. That way element will move by 1px and if we hold shift key and then click on a arrow it will move for 10px. While left click is moved for moving element, right click will open a layer list so that we can easily Appendix 1 - Graphics editing
switch between them. If we hold alt key and move an element we will get the copy of that element - copied layer we are working with.
Marquee tool (m) Tool for selecting various shapes. By holding a click on that icon we will get a submenu where we can select for example between rectangle and circle. When desired form of the tool is selected we can make a selection by holding left mouse key and dragging it. If we hold shift key while we are drawing a shape we will get the symmetric shape. When we select what we wanted and right mouse click on the selection we will get the list of action we can use for that selection, for example we can copy is or cut it to a separate layer. Selected shape can be edited from the main menu by clicking on the select - modify and that way we can for example contact it or expand it for 5px. If we need a nonsymmetric shape we can add new selections to the current selection by holding shift and drawing new one. Or we can remove part of the selection by holding alt and drawing shape that is going to be removed. This way we can for example remove the middle part of the circle and get a donut shape. With the selected are we can do plenty of actions like transforming it in various ways (expand, contract, rotate…). But the most important one for us is to save that selection as a separate image. Every design usually has a logo in it so that is an example of one image to be saved separately and afterwards loaded into HTML. Simplest way to do that is to click ctrl + c or ctrl + mouse click on the active selection and that way it will be copied. Then we can open a new document and Photoshop will set its dimensions to the exact ones as our copied area. In the new document we can click ctrl + v and we’ll get that image.
Crop Tool (c) Simple tool for cropping parts of the image into the new one. We
Frontend Guide
223
can modify the crop selection once it is made.
Slice Tool (k) Very useful tool for us. With it we can select some part of the design, right click on the selection and select the edit slice option that will show is dimensions of the selections as well as the x and y distance for it. So this way we can do various measurements.
Type Tool (t) Used for writing or selecting text. Text can be selected only if it is a textual layer, we can’t select a text that is part of the graphics. When a text is selected we can see its font, size, color etc… Also we can see the line height, text formatting and all of that wi will use in CSS. By clicking on the part that represents the text color we’ll get the new window where we can see the hexadecimal value of the color.
Eyedropper Tool (i) We can select any color with this tool simply by clicking anywhere on the design and we’ll get that color.
Zoom Tool (z) At the end you should know how to use zoom tool that allows us to zoom in or out in order to perform some task with more precision.
By clicking on any of these tools we will get options for it that give us more possibilities so I suggest taking a look for every one of them. Also lots of additional options are available from the main menu. Most of the options are intuitive and don’t require an explanation. Layers are the independent parts of the design holding graphics that we can modify without affecting the rest of the design. On the figure a1 they are marked with the number 3. Usually they are organized 224
Appendix 1 - Graphics editing
into the folders and logical parts of the Website. Selected layer (one or more) has blue background and all actions that we do are just for it. New layer can be added on several ways, one of them is clicking on the “add new layer” icon in the lower right corner or selecting that option from the main menu. Also when we start writing a new text it will be automatically placed into the new layer. Each layer can have a name that we can change as well as the position based on the other layers. We can change that position by holding it and dragging up or down. Position is important since based on it layer can be hidden by other layer or not. If we click on the eye icon we can temporarily hide that layer. If we use alt key and then click on the eye icon all layers will be hidden except for that one. By doing that again everything gets back to normal. Another good option is locking layers and that way we can be sure that a layer won’t be modified. Along with that one another very important functionality is selecting only the part of the layer that actually has some graphics on it. We can do that by holding the ctrl key and clicking on the rectangular area that represents the layer preview. Layers are often given some effect like transparency or something else that will style it additionally. It is important to know that by simply copying layer selection you won’t copy layer effects. So for example if the logo has some shadow as effect when you copy it there won’t be any shadow - effect won’t be copied. We can fix this in several ways. For example we can first copy the layer selection and then copy layer effects. Or the second option which I recommend is to add an empty later under that layer and select the “merge down” option from the menu. That way we’ll merge those layers and their effects and get one layer ready to be copied without losing any styles. As you can see merge function merges several layers into one layer. Also there is “flatten image” function available and it will merge all of the layers into one image.
Frontend Guide
225
As a option separate from the graphic editing tool I would like to point out to “print screen” functionality available for every OS. Most usual way to activate it is just by pressing the “print screen” key on the keyboard and then open for example Photoshop and press ctrl + v.
Image formats When we get to the point where we have a part of the design ready to be saved as separate image we should know what options do we have for it. Since that image is going to be used on the Internet its size is very important. On the other hand image quality is also very important so we need to know image formats in order to pick the best one. First of all instead of clicking on the “file - save” we will use “file - save for web” option. That way we will get a new window for options for image optimization. Figure a2 represents different parts of that window.
Figure a2: Image optimization
226
Appendix 1 - Graphics editing
Part marked with the number 1 gives us information about the final image size and that number will change when we change image options. With part 2 we can compare different image versions like original an optimized version. On this comparation we can see the quality and size differences. Part 3 gives us the possibility to select different format types and also options for specific format. Usually our images will be in one of the following formats: JPG, GIF and PNG (PNG-24). Here is an overview of their characteristics:
JPG Most importantly this format doesn’t support transparency. So if we try to save an image with transparent part as JPG image, color value of the mate field will fill the transparent parts. This is a format with very good compression for the large images with lot of colors. Photoshop gives us the possibility to select the quality on the scale from 0 to 100, which actually represents the compression factor. For different images we’ll use different compression.
GIF This format can be transparent but only as completely transparent or not. Mate option is very useful here since its value will be used for the image edges so that they don’t look squared on the background. If we plan to use the image on the white background we will use mate with the white color to get the nice transition. GIF is used for the images with small color range.
PNG This format supports transparency completely and image won’t have any quality loses since there is no compression like for the previous types. But because of that image will have large size so it is used only for smaller images.
Frontend Guide
227
Appendix 2 - SEO friendly coding SEO means Search Engine Optimization and it is one completely separate area, performed after the application is completed and in production mode. Using different methods based on the market, competition and other parameters it is tried to better position Web application on the search engines. Search engines are one of the basic ways to get traffic and because of that it is very important for us how they “see” our applications. Today’s search engines are sophisticated applications that rank our application in a smart way using lot of parameters. We are not going to do the actual optimization process since that process lasts for month and results are analyzed all the time. But our part as the frontend developer makes a huge part in all that because you can write the frontend code in many ways and those differences are important for SEO. Here is the list of tips and advices what to do in order to get best SEO results.
Valid markup So far we have been always saying that you should follow standards and keep the code valid as much as possible so we are going to follow those rules here as well. Semantic and valid code will get you a better ranking.
Organize the code in the smart way You have seen how one layout can be different in code and provide the same visual result. Because of that it should be organized in the smart way. Let’s assume that we have a layout with two columns where the left one is the main column with all of the content and the right one has some advertisement and less relevant information. Since search engines scan the page code from top to bottom in this example we should first write the left
228
Appendix 2 - SEO friendly coding
column in our code.
Meta information Meta information are information about information. The most important thing is to have keywords and description in the head part. That way you can tell search engines what is this page about. As for the graphics search engines can’t know what is some image about so you have to use alt attributes. Title attribute is a general attribute so it can be applied for all of the tags and that is also a good way to provide additional information where it is needed.
Smart use of headlines Part of every design is logo and sometimes slogan. These are one of the most important information for search engines and you should place it in a appropriate tag based on that. Bad choice would be some helper tag like span. Instead you should use headlines with the highest priority like h1 and h2. If headline is a logo and not text then we’ll probably have to use an image for it. In that situation we can place it in h1 and necessarily use alt and title attribute. Also we can apply one nice trick here and that is using background as logo and hide the HTML text with the text-indent property.
Clean code All files should be separated (CSS, JS…) and just loaded into the page. You shouldn’t use CSS and JS code inside of the page. You should have a reasonable amount of HTML elements which means that you should use CSS as much as possible. You should use main CSS functionalities like inheritance as much as possible as well. Basically the good indicator about all of this is a visual look of your code. If it looks messy with lot of helper elements, additional classes and other you should write it in another way.
Frontend Guide
229
230
Appendix 2 - SEO friendly coding
Figures list 2.0: Simple HTML page ............................................................................. 24 2.1: Default styling for text elements ......................................................... 26 2.2: Multimedia and the lists ...................................................................... 29 2.3: Form.................................................................................................... 33 3.1: Applying style to the page ................................................................... 46 3.2: Partial document tree for the example 4 .............................................. 49 3.3: Inheritance document tree .................................................................. 50 3.4: Style inheritance result ....................................................................... 51 3.5: Overwriting same inherited values ...................................................... 52 3.6: Selector priority by the â&#x20AC;&#x153;strengthâ&#x20AC;? ...................................................... 53 3.7: Selector priority by position inside the CSS document ........................ 54 3.8: ID selector priority to class selector ..................................................... 57 3.9: Multiple classes ................................................................................... 58 3.10: Element states .................................................................................. 65 3.11: Pseudo elements ............................................................................... 67 3.12: Combinators ..................................................................................... 68 3.13: Child combinator ............................................................................... 69 3.14: Code editor help when writing HTML and CSS .................................. 74 3.15: Em unit inheritance ........................................................................... 78 3.16: Various text formatting ..................................................................... 82 3.17: Content vertical align ........................................................................ 84 3.18: Repeating one pattern on x and y axis ............................................... 87 3.19: Repeating one pattern on the y axis .................................................. 89 3.20: Filling the missing background with the solid color ........................... 90 3.21: Repeating one pattern on the x axis .................................................. 90 3.22: No background repeat ...................................................................... 91 3.23: Element box model ........................................................................... 93 3.24: Default look of block elements .......................................................... 93 3.25: Padding ............................................................................................. 94 3.26: Border ............................................................................................... 95 3.27: Margin ............................................................................................... 97 3.28: W3C box model ................................................................................. 97 3.29: FireBug layout option ..................................................................... 100 3.30: Default block element behavior ...................................................... 102 3.31: Block element width ........................................................................ 103
Frontend Guide
231
3.32: Default float behavior ...................................................................... 106 3.33: Text formatting to the float elements .............................................. 106 3.34: Float layout example ....................................................................... 107 3.35: Order of the float elements .............................................................. 108 3.36: Float element height ........................................................................ 109 3.37: Clear left and right ........................................................................... 109 3.38: Clear both ........................................................................................ 110 3.39: All elements are float ....................................................................... 111 3.40: Blueprint grid system ....................................................................... 111 3.41. Absolute positioning ........................................................................ 115 3.42: Position: relative .............................................................................. 116 3.43: Overflow: visible ............................................................................... 118 3.44: CSS resize ........................................................................................ 119 3.45: Overflow: hidden .............................................................................. 120 3.46: Channing element structure ............................................................ 122 3.47: CSS show and hide ........................................................................... 124 3.48: Block navigation .............................................................................. 125 3.49: List style navigation ......................................................................... 127 3.50: Styling tables ................................................................................... 129 3.51: Web fonts for browsers .................................................................... 136 3.52: Default form elements look ............................................................. 138 3.53: Form styling with basic CSS2 properties .......................................... 140 3.54: Styling form with CSS3 ..................................................................... 142 3.55: CSS Sprites image ............................................................................ 144 3.56: CSS Sprites demo ............................................................................. 145 3.57: CSS Sprites as navigation ................................................................. 146 3.58: !important declaration ..................................................................... 150 3.59: Fluid layout....................................................................................... 153 3.60: Combined fluid layout ..................................................................... 153 4.1. FireBug JavaScript console ................................................................ 161 4.2: Arithmetic operators ......................................................................... 165 4.3: Assignment operators ....................................................................... 166 4.4: Comparation operators ..................................................................... 167 4.5: Logical operators ............................................................................... 167 4.6: Special characters ............................................................................. 168 4.7: jQuery events .................................................................................... 210 4.8: jQuery animations ............................................................................. 213 4.9: jQuery HTML manipulation ............................................................... 217
232
Figures list
4.10: jQuery CSS manipulation ................................................................ 220 a1: Photoshop workspace........................................................................ 222 a2: Image optimization ........................................................................... 216
Frontend Guide
233
Examples list 1 - empty HTML page .......................................................................... 24 2 - text formatting ...................................................................................... 25 3 - multimedia and lists ............................................................................... 28 4 - form ....................................................................................................... 32 5 - Adding styles to pages ........................................................................... 45 6 - ID and class selectors ............................................................................. 56 7 - Element states ....................................................................................... 64 8 - Pseudo elements ................................................................................... 66 9 - Font and basic typography ..................................................................... 76 10 - Text formatting and align ..................................................................... 81 11 - Vertical align, Exercise .......................................................................... 83 12 -Text hiding ............................................................................................ 84 13 - Positioning background ........................................................................ 87 14 - Element moving .................................................................................. 98 15 - Positioning and displaying .................................................................. 100 16 - float and clear .................................................................................... 105 17 - Positioning ................................................................................. 114 18 - Overflow and clip ........................................................................ 117 19 - Changing element structure ......................................................... 122 20 - Hiding and displaying elements ................................................... 123 21 - Block navigation ......................................................................... 124 22 - Using lists for navigation .................................................................... 126 23 -Table styling ....................................................................................... 128 24 - Modern CSS 3 design ......................................................................... 138 25 - Fluid layout ........................................................................................ 152 26 - Combined fluid layout ........................................................................ 153 JS 1 - Printing variables ............................................................................. 164 JS 2 - Dynamic types ................................................................................. 166 JS 3 - jQuery events................................................................................... 209 JS 4 - jQuery effects .................................................................................. 212 JS 5 - jQuery HTML manipulation.............................................................. 215 JS 6 - jQuery CSS manipulation ................................................................. 219
234
Examples list
Frontend Guide
235