Title of Article
First paragraph.
Second paragraph.
User Manual:
Open the PDF directly: View PDF .
Page Count: 838
Download | ![]() |
Open PDF In Browser | View PDF |
[1] www.allitebooks.com Web Developer's Reference Guide A one-stop guide to the essentials of web development including popular frameworks such as jQuery, Bootstrap, AngularJS, and Node.js Joshua Johanan Talha Khan Ricardo Zea BIRMINGHAM - MUMBAI www.allitebooks.com Web Developer's Reference Guide Copyright © 2016 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: March 2016 Production reference: 1180316 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78355-213-9 www.packtpub.com www.allitebooks.com Credits Authors Technical Editor Joshua Johanan Abhishek R. Kotian Talha Khan Copy Editor Ricardo Zea Pranjali Chury Reviewers Chetankumar Akarte Gergo Bogdan Rahul Devaskar Project Coordinator Kinjal Bari Proofreader David Ellenwood Philippe Reneiver Gonin Robert Mion Safis Editing Indexer Monica Ajmera Mehta Natalie Olivo Mateus Ortiz Graphics Commissioning Editor Disha Haria Edward Gordon Production Coordinator Conidon Miranda Acquisition Editor Meeta Rajani Cover Work Content Development Editor Conidon Miranda Samantha Gonsalves www.allitebooks.com About the Authors Joshua Johanan is a web developer who currently lives in South Bend, Indiana. He has been a web developer for five years. He has built sites using many different languages, including PHP, Python, JavaScript, and C#; although if asked, he would prefer using Python and JavaScript. These languages have led him to use different MVC frameworks, such as Zend Framework, Django, and .Net's MVC. As you can see from this book, Joshua has also used JavaScript on both the backend with Node.js and frontend using many different libraries. These include Backbone, React, jQuery, and plain old JavaScript. He currently works for a healthcare organization, writing websites in C#. This does not allow him to utilize the latest flashy browser technologies, but it does enforce good development skills, such as maintainability and scalability. This is his first book, but he does post somewhat regularly on his blog at http:// ejosh.co/de/. I would like to thank my wife, Liz, for her support through the writing of this book. I would also like to thank Dexter and Gizmo, who hung out by my feet as I wrote most of this book. www.allitebooks.com Talha Khan is a passionate web developer, JavaScript enthusiast, software consultant, and coffee freak from Pakistan who is currently residing in UAE. He has more than five years of experience in this field. Despite graduating in mathematics and statistics, his love for web technologies pushed him toward the field of web technologies. He is experienced in developing interactive websites and web applications using PHP, MYSQL, and Dot Net Suite along with HTML, CSS, and JavaScript libraries. He has been teaching web development as well and is an active contributor on programming forums such as StackOverflow. Occasionally, he tweets at @alphaprofile. Talha has worked and consulted on various projects for several major brands and companies. Tossdown.com, a leading restaurants and food search engine of Pakistan, is among one of his major achievements. He is also running his own start-up while educating newbies on technology. He is currently working as a software architect for UAE's biggest swimming academy, Hamilton Aquatics. I want to thank my parents for keeping me motivated and my friends who supported me in writing, as I could count on them anytime if I had to use their laptop. I am also grateful to Tahir Ali Khan, who helped me at every step throughout my career and was like a guiding light. I would like to take this opportunity to thank all the teachers and mentors who helped me shape my career and helped me whenever I needed it. These people were my source of inspiration. A special thanks to Omair Bangash, who took the risk of employing someone from a non-IT background and taught me to a level where I am now teaching others. His confidence in me was enough to push me to reach to my goals. I worked under many projects of various scales and technologies under his supervision. He helped me at every step to hone my skills. I don't think I would be have been able to write this book had it not been for his constant support and motivation. Without learning from these teachers, there is not a chance I could be doing what I do today, and it is because of them and others who I may not have listed here that I feel compelled to pass my knowledge on to those willing to learn. www.allitebooks.com Ricardo Zea hails originally from Medellín, Colombia. He is a passionate and seasoned full-stack designer who is now located in Dayton, Ohio, USA. He is always looking for ways to level up his skills and those around him. Constantly wondering how things are made on the Web, how they work, and why, have made Ricardo a very technical designer, allowing him to explain to others the intricacies of design and the technicalities of the Web in ways that are very easy to understand and assimilate. Ricardo has a master's degree in publicity and advertising and has deep passion for understanding human behavior. He also has a fiercely competitive PC gaming hunger. Together, all this has allowed him to switch from the creative side of the brain to the rational side very easily, allowing him to visualize and create technically sound web and mobile designs that are responsive, perform well, and convey the proper message through design. Ricardo is the author of Mastering Responsive Web Design, Packt Publishing. He's also the organizer of the CodePen Dayton meetup group. He's a member of the Dayton web developers and UX Dayton meetup groups. He's also one of the first members of SitePoint's Ambassadors program. He's also the author of the monthly web design and development newletter Level Up!. He was also a technical reviewer for Sass and Compass, Designers Cookbook, and Sass Essentials, all by Packt Publishing. For several years, he was also a Flash and CorelDRAW professor at different universities in his home country, Colombia. Ricardo has 15 years of experience in web design and 20 years of experience in visual and graphic design. A huge and infinite thanks to my wife, Heather, and my beautiful son, Ricardo. They are my inspiration to be a better professional, a better person, a better husband, and a better dad. To my mom, Socorro, who showed me the values that made me the man I am today. To my dad, Ricardo "Pinta" Zea, for teaching me to be determined to not only be good at what I do but to be the best I can be. To God, for allowing me to share with everyone my knowledge of CSS. And to you, the readers, for giving me the chance to help you be better web professionals. www.allitebooks.com About the Reviewers Chetankumar Akarte is the CEO of Renuka Technologies Private Limited, Nagpur, located in central India. He is an engineer (electronics) from Nagpur University with more than 10 years of experience in the design, development, and deployment of web-based, Windows-based, and mobile-based applications with expertise in PHP, .NET, JavaScript, Java, Android, and more. Chetankumar likes to contribute to newsgroups and forums. He has written articles for Electronics For You, DeveloperIQ, and Flash and Flex Developer's Magazine. In his spare time, he likes to maintain his technical blog (http://www.tipsntracks. com) to get in touch with the developer community. He has been the technical reviewer for four books published by Packt Publishing. He has released more than 96 applications on the Android market! One of his applications, an English to Hindi Dictionary, is like a pocket dictionary for students, which has more than a hundred thousand downloads. You can find it at https://play.google.com/store/apps/ details?id=com.sachi.hindi.dictionary. Chetankumar lives in Nagpur with wife, Shraddha, and his two children, Kaiwalya and Hrutvij. You can visit his websites, http://www.sahityachintan.com and http://www.tipsntracks.com, or get in touch with him at chetan.akarte@gmail. com. I'd like to thank my wife, Shraddha, and my parents for their consistent support and encouragement. I'd also like to thank my lovely children, Kaiwalya and Hrutvij, who allowed me to dedicate all of their playtime with me to this book. I'd also like to thank Packt Publishing for this opportunity to do something useful, especially the project coordinator, Kinjal Bari, for all the valuable support. www.allitebooks.com Gergo Bogdan is a software engineer with over eight years of experience in the IT industry. During this time, he worked at small companies as well as multinational organizations. He has vast expertise in multiple technologies, starting from .NET and Python to JavaScript and Java. He loves to create technical articles and tutorials for fellow developers, and he is a passionate blogger (http://grelution.com). He is the author of the Web API Development with Flask video course, Packt Publishing. Rahul Devaskar is a software engineer with experience of building real-time event-driven applications, context-aware applications, and web applications. His expertise includes web apps development, mobile apps development, API server development, and real-time analytics. He has built apps using AngularJS, Node.js, MongoDB, and Ionic. I'd like to thank my wife, Niyati, for her constant support and encouragement. David Ellenwood is a frontend developer and WordPress expert with more than 15 years of experience on the Web. As the owner and solo developer at DPE Websmithing and Design, LLC, he enjoys providing consulting services to midsize customers looking to update or extend their existing websites beyond traditional brochureware. He lives with his beautiful wife and two amazing boys at the westernmost tip of Lake Superior in Superior, Wisconsin. Philippe Renevier Gonin has been an assistant professor at the University Nice Sophia Antipolis (UNS), France, since 2005. He teaches web technologies, software engineering (architecture and development), and HCI (Human Computer Interaction). On the research front, Philippe works on connections between usercentered design (for example, user and tasks models) and software engineering (for example, component architecture and UI development). www.allitebooks.com Robert Mion takes every effort to design experiences that continually delight, empower, and inspire people, often by repeatedly triggering that magical moment when your brain makes your mouth go A ha! or Of course!. This passion was ignited when watching Pixar's Toy Story at the age of eight. The fire has only grown since then. Robert continues to use his amassed knowledge of storytelling, color, typography, layout, design, human psychology, and web technologies as an excuse to have fun every day by crafting experiences designed to go beyond solving problems—to emotionally connect with users and to help them become more awesome. Robert and his wife, Laura, currently live in Fort Mill, SC—minutes south of the Queen City—with their two pugs (one, a pug-boxer mix). Natalie Olivo has worked with web-based technologies for almost a decade and began her career in coding when the majority of HTML pages were tabular and inflexible. She remembers the excitement and satisfaction in the creative process of building her first prototype for a messaging application while she was employed at one of the first popular social networks in the age before Facebook. Natalie's wide ranging experience include key development roles in companies such as Godiva, Barnes and Noble, and The Daily Beast. She has spent the last year building out the mobile web experience at The Daily Beast, and enjoys the challenges of building applications that are performant for mobile web. She is currently a senior frontend engineer at Business Insider. Mateus Ortiz is the creator of some cool open source projects such as Web Components Weekly (webcomponentsweekly.me), the first weekly World of Web Components, and web components the right way, and other projects. He is only 17 years old and spends his days helping and creating new open source projects. Mateus lives in Brazil where he makes several talks on the frontend. You can find him on Twitter at twitter.com/mteusortiz. First of all, I'd like to thank God. I'd like to thank my mother, who always supports me and helps me in everything, my father, and all my family and friends. I'd also like to thank Packt Publishing for the opportunity to assist in the review of this book. www.allitebooks.com www.PacktPub.com eBooks, discount offers, and more Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub. com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at customercare@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. TM https://www2.packtpub.com/books/subscription/packtlib Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books. Why subscribe? • Fully searchable across every book published by Packt • Copy and paste, print, and bookmark content • On demand and accessible via a web browser Table of Contents Preface Chapter 1: HTML Elements xxi 1 DOCTYPE Attributes Description html Attributes Description Document metadata head Semantic content sections body section nav Headings header footer address aside p Content sections hr pre blockquote ol ul li dl 1 2 2 2 2 2 3 3 9 9 9 10 11 12 13 13 14 14 14 15 15 15 16 17 17 18 [i] Table of Contents dt dd figure figcaption div Inline elements a abbr bdo br cite code dfn em kbd mark q s samp small span strong sub sup time var wbr Embedded content img embed object param video audio source track Tables table caption colgroup tbody 19 19 20 20 21 22 22 23 23 24 24 25 25 25 26 26 26 27 27 27 28 28 28 29 29 30 30 30 30 33 34 35 35 36 37 38 39 39 39 40 40 [ ii ] Table of Contents thead tfoot tr td th Forms Form fieldset legend label input button select optgroup option textarea Drawing elements canvas svg 41 41 42 43 43 44 44 45 46 46 47 49 50 51 52 53 54 54 55 Chapter 2: HTML Attributes 57 Global attributes accesskey class contenteditable data-* dir draggable id lang spellcheck style tabindex title Miscellaneous accept accept-charset action alt async autocomplete 57 57 58 58 58 59 59 60 60 61 61 61 62 62 62 63 63 64 64 65 [ iii ] Table of Contents autofocus autoplay autosave cite cols colspan datetime disabled download content controls for form formaction height href hreflang label list loop max maxlength media method min multiple name novalidate pattern placeholder poster readonly rel required reversed rows rowspan scope selected size src 65 66 66 66 67 67 68 68 69 69 70 70 71 71 72 72 73 73 74 74 75 75 76 76 76 77 77 78 78 79 79 79 80 80 81 81 82 82 83 83 84 [ iv ] Table of Contents start step type value width wrap 84 85 85 86 87 87 Chapter 3: CSS Concepts and Applications Basic selectors The simple selector The type selectors The universal selector The attribute selectors The class selectors The ID selectors Combinators Descendant combinator The child combinator The adjacent sibling combinator The general sibling combinator The selector specificity Pseudo-classes The link pseudo-classes User action pseudo-classes The structural selectors :first-child :first-of-type :last-child :last-of-type :nth-child() :nth-last-child :nth-last-of-type and :nth-of-type :only-child :only-of-type Validation :checked :default :disabled and :enabled :empty :in-range and :out-of-range :invalid and :valid [v] 89 90 90 90 91 92 93 94 94 95 96 97 97 98 99 99 100 101 102 102 103 103 104 104 105 106 106 107 107 107 108 108 109 110 Table of Contents :not or negation :optional and :required :lang() Pseudo-elements ::before and ::after ::first-letter ::first-line ::selection Generated content content Quotation marks 110 111 111 112 112 113 113 114 114 115 116 Chapter 4: CSS Properties – Part 1 Animation Base markup and CSS Final CSS code Background background-attachment background-blend-mode background-clip background-color background-image background-origin Box model width height padding margin border box-sizing max-height max-width min-height min-width object-fit object-position Border radius border-radius Unit Relative length units Viewport-relative length units [ vi ] 117 118 118 130 131 131 132 134 135 136 138 143 143 144 145 146 148 150 150 151 152 153 154 155 156 156 158 158 161 Table of Contents Absolute length units Angle data types Resolution units Duration units Column Flexible box (flexbox) flex-grow flex-shrink flex-basis flex-direction flex-wrap flex-flow align-content align-items align-self order justify-content flex Summary Chapter 5: CSS Properties – Part 2 Fonts font-family font-feature-settings font-size font-size-adjust font-stretch font-style font-variant font-variant-ligatures font-weight font Transform transform transform-origin transform-style Transition Positioning position top [ vii ] 162 164 165 165 166 172 173 173 174 175 176 177 178 179 180 181 182 183 183 185 185 185 186 188 189 190 191 192 192 193 194 195 195 197 198 199 202 202 203 Table of Contents bottom left right vertical-align Text color text-align text-decoration text-decoration-line text-decoration-color text-decoration-style text-indent text-overflow text-rendering text-shadow text-transform text-underline-position direction Tables table-layout border-collapse border-spacing empty-cells caption-side Words and paragraphs hyphens word-break word-spacing word-wrap line-height orphans quotes widows writing-mode letter-spacing white-space tab-size Paging page-break-after page-break-before page-break-inside 204 205 206 207 207 208 208 209 210 210 211 211 211 212 214 214 215 216 217 217 218 218 219 219 220 220 221 222 223 223 224 225 226 226 227 228 229 229 230 230 231 [ viii ] Table of Contents Chapter 6: CSS Properties – Part 3 Page box bleed marks List list-style list-style-type list-style-position list-style-image Counter counter-reset counter-increment Drop shadows box-shadow Display and visibility all clear display opacity filter overflow overflow-x overflow-y visibility z-index Masking and clipping mask mask-clip mask-composite mask-image mask-mode mask-origin mask-position mask-repeat mask-size mask-type mask-border mask-border-source mask-border-mode mask-border-slice mask-border-width [ ix ] 233 233 233 234 234 235 235 236 237 237 238 239 240 240 242 242 243 245 247 248 252 253 253 254 255 255 256 257 258 259 260 260 261 262 263 264 264 264 265 265 266 Table of Contents mask-border-outset mask-border-repeat clip-path Image rendering and orientation image-orientation image-rendering User interface cursor pointer-events outline 3-Dimensional perspective perspective-origin backface-visibility Summary 267 268 268 271 272 272 273 273 276 277 278 278 279 280 280 Chapter 7: CSS Functions 283 Filter brightness() contrast() grayscale() invert() hue-rotate() blur() saturate() sepia() Transforms matrix() matrix3d() rotate() rotate3d() rotateX() rotateY() rotateZ() scale() scale3d() scaleX() scaleY() scaleZ() skew() skewX() 283 283 284 284 285 285 286 286 286 287 287 288 288 289 289 290 291 291 292 292 293 293 294 294 [x] Table of Contents skewY() steps() translate() translate3d() translateX() translateY() translateZ() Colors hsl() and hsla() rgb() and rgba() Gradients linear-gradient() radial-gradient() repeating-linear-gradient() repeating-radial-gradient() Values attr() Responsive Table calc() url() cubic-bezier() Miscellaneous drop-shadow() element() image() opacity() perspective() rect() At-rules @charset @document() @font-face @import @keyframes @media @namespace @page @supports Global CSS keyword values Summary 295 295 296 297 297 298 298 299 299 300 300 301 302 304 305 306 306 307 308 309 310 312 312 312 313 313 314 314 315 315 316 317 320 321 323 324 325 326 328 331 [ xi ] Table of Contents Chapter 8: JavaScript Implementations, Syntax Basics, and Variable Types 333 Chapter 9: JavaScript Expressions, Operators, Statements, and Arrays 377 History of JavaScript Evolution of JavaScript JavaScript implementations Core JavaScript (ECMAScript) Document object model (DOM) Browser object model (BOM) Client-side JavaScript Loading external JavaScript files Server-side JavaScript The language syntax Language Type The character set Identifiers Reserved keywords Comments Literals Statements Optional semicolon Data type The typeof operator The undefined type The null type The number type The Boolean type The string type The object type Variable, scope, and memory Variable declaration The variable scope Primitive and reference values The execution context and scope Garbage collection Expressions Primary expressions Object initializer [ xii ] 334 335 335 336 336 337 337 339 341 344 345 345 345 351 351 353 354 356 359 360 361 362 363 364 366 367 368 369 371 372 373 374 375 377 378 379 Table of Contents The function definition expression The property access expression The invocation expression The object creation expression Evaluation expression Operators Overview Arithmetic operators Logical operators Assignment operators Exponentiation assignment (**=) Relational operators Statements Expression statements Compound empty statements Declaration statements Conditional statements Loops Jumps and labeled statements Arrays Array types Array type object Creating arrays Reading and writing array elements Multidimensional arrays in JavaScript Properties in an array Array methods ECMA5 Array methods Chapter 10: JavaScript Object-Oriented Programming Polymorphism Encapsulation Inheritance Abstraction Objects Creating objects Design patterns Property getter and setter Deleting properties Testing properties Enumerating properties [ xiii ] 380 381 382 383 383 384 384 385 390 393 396 396 400 401 401 402 403 407 411 414 414 415 415 417 417 418 419 426 433 433 433 434 434 434 435 436 449 450 450 451 Table of Contents Property attributes Serializing objects Objects methods Functions and methods Invoking functions Defining functions Function arguments and parameters Parameters and return values Functions as namespace Closure Function properties Methods Function constructor Classes and modules Classes and prototypes Constructors Defining a class Classes in the ECMA5 script Modules Inheritance Prototype chaining Constructor stealing Combination inheritance Prototypal inheritance Parasitic inheritance Parasitic combination inheritance Subclasses Built-in objects Global objects Date object Math object The RegExp object String object Array objects Chapter 11: Extending JavaScript and ECMAScript 6 Compatibility and goals JavaScript subset and extensions JavaScript subsets JavaScript extensions Const [ xiv ] 452 454 454 455 455 455 456 456 457 457 458 458 458 459 459 460 461 462 462 463 463 464 465 466 467 468 469 470 470 471 475 478 480 484 491 491 493 493 496 496 Table of Contents Let Destructuring assignment For each Iterator Generators Array Generator expression Scoped variables and constants Shorthand functions Multiple catch clauses The try clause The catch clause The finally clause E4X – ECMAScript for XML ECMAScript 6 features Arrow functions Classes Enhanced object literals Template strings Destructuring assignment Extended parameter handling Bindings Iterators and the for...of operator Generators Better Unicode support Modules Module loaders Collections Proxies Symbols Subclassable built-ins Promises Core math library APIs Binary and octal literals Reflect API Tail calls 497 498 498 498 498 498 498 499 500 500 500 501 502 504 504 505 506 507 509 510 512 514 515 516 516 517 518 519 532 532 534 534 539 540 540 551 Chapter 12: Server-side JavaScript – NodeJS File and process management Modules The OS module [ xv ] 553 555 555 558 Table of Contents The process module File functions The path module REPL Handling errors Utilities Events Crypto Buffer Console npm (Node Package Manager) Stream The net module createServer net.Server The HTTP module createServer http.Server IncomingMessage ServerResponse http.request http.get http.clientRequest 559 564 571 574 575 577 577 580 584 589 591 593 598 598 599 604 604 605 607 609 611 612 613 Chapter 13: Bootstrap – The Stylish CSS Frontend Framework Introduction to Bootstrap foundations Getting started Layouts The grid system Typography Tables Lists Forms in Bootstrap Images Navigation elements The navigation bar Panels Breadcrumbs Labels and badges Pagination [ xvi ] 615 615 617 617 620 624 627 629 630 634 636 637 638 639 640 640 Table of Contents Progress bars Advanced Bootstrap/JavaScript plugins Customizing Bootstrap Websites built with Bootstrap Bootstrap resources Chapter 14: jQuery – The Popular JavaScript Library The evolution of JQuery Getting started Installing JQuery Using jQuery Selectors Element selectors ID selectors Class selectors Events Mouse events Keyboard events Form events Document events Effects and animations Hide, show, and toggle Fade Sliding Callback callbacks.add() callbacks.fire() callbacks.remove() callbacks.disable() Chaining jQuery and the document object model jQuery traversing Ancestors Descendants Siblings Filtering Using AJAX in jQuery The jQuery Ajax load jQuery Ajax Get jQuery Ajax Post [ xvii ] 641 642 652 652 653 655 655 656 656 656 657 658 658 659 659 659 667 669 674 676 678 681 685 688 688 689 690 690 691 691 692 693 694 695 699 701 701 702 703 Table of Contents Miscellaneous jQuery functions noConflict() param() index() each() data() removeData() jQuery plugins jQuery resources Chapter 15: AngularJS – Google's In-Demand Framework Modules (ngApp) module config run Routing (ngRoute) ngView $routeProvider $route $routeParams Dependency injection Dependency injection in Angular injector $injector Controllers ngController $scope Data binding and templates Event binding Scope Digest cycle $digest $watch $apply Hierarchies Services Factory Service Provider Value [ xviii ] 704 704 704 705 706 707 707 708 709 711 712 712 713 714 715 715 715 716 717 718 718 719 719 720 721 721 722 722 722 722 723 723 724 725 725 726 727 728 729 Table of Contents Constant $http Convenience methods Notable services Promises $q Expressions Expressions in JavaScript Directives Normalization Scope Modifying DOM Event binding Directive definition object Key directives Globals Extend noop isUndefined Copy Bind Forms ngModel CSS classes Validation Testing Unit testing with Jasmine and Karma ngMock Unit testing controllers Unit testing directives Unit testing services Index 730 730 731 733 733 734 735 735 736 736 736 739 740 741 742 754 754 755 756 756 757 757 758 758 758 760 760 761 763 763 764 767 [ xix ] www.allitebooks.com Preface This book covers many concepts that any web developer may need to know. These concepts may be new or known, but forgotten. The first two chapters in this book will cover the basic elements and attributes of HTML. The next four chapters will cover the concepts and syntax of CSS. JavaScript will be the focus of the next five chapters. Finally, we will cover external libraries. These include Bootstrap, jQuery, and Angular. Because this is a reference guide, it is not set up as a read-through tutorial. Each section and concept is written to stand on its own so that you can find the piece of information that you need quickly. What this book covers Chapter 1, HTML Elements, covers all the elements that you will need when building a web page. This is focused on HTML5. Chapter 2, HTML Attributes, focuses on any the attributes that can be used with HTML elements. Chapter 3, CSS Concepts and Applications, focuses on selectors. Selectors are core to determining which elements the CSS attributes apply to. Chapter 4, CSS Properties – Part I, covers properties for animation, background, the box model, CSS units, columns, and the mighty Flexbox. Chapter 5, CSS Properties – Part II, covers properties for fonts, transforms, transitions, positions, text, tables, words and paragraphs, and paging. Chapter 6, CSS Properties – Part III, covers properties for the page box, lists, counters, drop shadows, display and visibility, clipping and masking, user interface, and 3D. [ xxi ] Preface Chapter 7, CSS Functions, covers functions for filters, transforms, colors, gradients, and values. It covers a few extra concepts like at-rules, global keyword values, and miscellaneous. Chapter 8, JavaScript Implementations, Syntax Basics, and Variable Types, talks about JavaScript implementations and language basics, including syntax and variables and their types. This chapter will enable us to understand and get started with basic scripting. Chapter 9, JavaScript Expressions, Operators, Statements, and Arrays, enables us to advance with our basic JavaScript language understanding and introduces JavaScript expressions, basic operators, statements, loops, conditions, and arrays. This also covers examples for better understanding. Chapter 10, JavaScript Object-Orientated Programming, explains the basic concepts of object-oriented programming, that is, inheritance, polymorphism, abstraction, and encapsulation. You will also learn the usage of objects, classes, and related methods. We will cover examples for better understanding. Chapter 11, Extending JavaScript and ECMA Script 6, covers all the newly introduced features of ECMAScript 6, which was released in 2015, such as new objects, patterns, syntax changes, and new methods on existing objects. This chapter covers all these features in detail. Chapter 12, Server-side JavaScript – NodeJS, continues to focus on JavaScript. The difference is that we will now write JavaScript on the server side instead of the client side. We can use the concepts covered in the other JavaScript chapters in addition to learning specific NodeJS objects and paradigms. Chapter 13, Bootstrap – The Stylish CSS Frontend Framework, talks about Bootstrap, which is an intuitive framework for creating responsive websites. It uses JavaScript, HTML, and CSS. This chapter will give you a detailed look at the Bootstrap framework and will enable you to create responsive layouts and web pages. Each topic in this chapter has a relevant example. Chapter 14, jQuery – The Popular JavaScript Library, focuses on jQuery, which is a JavaScript library that simplifies dealing with various aspects of an HTML document. In this chapter, you will learn to traverse elements of an HTML document, methods, event handling, animations, and AJAX for rapid development. Chapter 15, AngularJS – Google's In-Demand Framework, is where we conclude this book by finishing the external library section. Angular has been one of the most popular frameworks since it was introduced by Google. We will look at all the main concepts that you will need to begin writing applications with Angular. [ xxii ] Preface What you need for this book Most likely, for this book, you will need nothing that you are not already using! You will need a computer, a browser, and a text editor. Each chapter will cover different concepts and languages, so there may be differences between each chapter. Here is a summary of the various things you will need throughout the chapters: • For Chapters 1-5, you will only need a text editor and a browser. • For Chapters 6-11, you will need the same text editor and browser, but with JavaScript being a programming language, I would recommend an integrated development environment (IDE). JetBrains makes a great IDE called WebStorm for web development. However, this is not necessarily needed for these chapters. • For Chapters 12-14, you will again need a text editor and browser. An IDE would also be very helpful for this section. Anytime you are dealing with complex frameworks, an IDE will make your life easier. Although you can just use a notepad and a browser to do any sort of development, an IDE is always preferred and suggested for development in any specific language. I would suggest using Adobe Dreamweaver for beginners. The intellisense of IDE makes it a lot easier to code as it auto-suggests various methods, names, and variables, so you don't have to remember everything. As we will be dealing with the elements and document nodes in the JQuery section, you should have extensions enabled in your browser. ECMA Script 6 is very recent and not fully supported by all browsers. In some examples, you might have to load ES6 compilers to enable that feature in your browser. However, I would highly recommend that you use the latest version of Google Chrome as a client, as it covers most of the sections in ES6. Who this book is for This book is intended for beginners as well as advanced web developers. This book will be a valuable resource for anyone who is a web developer. You can look up any concept that deals with HTML, CSS, JavaScript, NodeJS, Bootstrap, jQuery, or Angular in this book. Conventions In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. [ xxiii ] Preface Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "HTML5 has a simple document type declaration, ." A block of code is set as follows:This is an example HTML elementWhen we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: try{ JSON.parse(jsonObject); } catch (ex) { //do something with this error } Any command-line input or output is written as follows: # cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample /etc/asterisk/cdr_mysql.conf New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen." Warnings or important notes appear in a box like this. Tips and tricks appear like this. [ xxiv ] Preface Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail feedback@packtpub.com, and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors. Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. Downloading the example code You can download the example code files for this book from your account at http:// www.packtpub.com. If you purchased this book elsewhere, you can visit http://www. packtpub.com/support and register to have the files e-mailed directly to you. You can download the code files by following these steps: 1. Log in or register to our website using your e-mail address and password. 2. Hover the mouse pointer on the SUPPORT tab at the top. 3. Click on Code Downloads & Errata. 4. Enter the name of the book in the Search box. 5. Select the book for which you're looking to download the code files. 6. Choose from the drop-down menu where you purchased this book from. 7. Click on Code Download. Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of: • WinRAR / 7-Zip for Windows • Zipeg / iZip / UnRarX for Mac • 7-Zip / PeaZip for Linux [ xxv ] Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub. com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/ content/support and enter the name of the book in the search field. The required information will appear under the Errata section. Piracy Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at copyright@packtpub.com with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content. Questions If you have a problem with any aspect of this book, you can contact us at questions@packtpub.com, and we will do our best to address the problem. HTML Elements HyperText Markup Language (HTML) is a language that annotates text. Annotation of text is done using elements. Using the following p element, as an example, we will see how to use HTML:This is an example
HTML elements also have attributes that will modify how they are rendered or interpreted. Attributes are added inside of the starting tag. Here is the class attribute in a div element:This is an exampleThere have been multiple specifications of HTML so far, but we will just look at the most commonly used and important elements of HTML5. HTML5 is the latest official specification, so we will be as future-proof as possible at the time of writing this book. You will want to follow the specifications of HTML as closely as possible. Most browsers are very forgiving and will render your HTML, but when you go beyond the specifications, you can and will run into strange rendering issues. All HTML elements will have global attributes. The attributes listed for each element in the sections that follow are the attributes beyond the global attributes. DOCTYPE The DOCTYPE element defines the document type of the file, as follows: [1] HTML Elements Attributes The documentType attribute that you can see in the preceding code lets the browser know the type of document you will use. Description HTML5 has a simple document type declaration, . This lets the browser know that the document is HTML5. The previous versions of HTML needed a formal definition of the version being used, but HTML5 has removed this for simplicity. Most browsers will enforce strict adherence to the document type declared and try and figure out what it is based on looking at the document. This can lead to rendering issues, so it is recommended that you do follow the standards. Here is an HTML5 declaration: html The html element is the root element of the HTML document: Attributes The manifest attribute links to a resource manifest that lists which files should be cached. Description The html element must directly follow the DOCTYPE element. This is the root element that all other elements must be descendants of. The html element must have one head element and one body element as its children. All other elements will be inside these tags. [2] Chapter 1 Here is what a simple HTML page looks like: Hey Document metadata The next elements will give metadata about the document. In addition to this, you can also include links to resources, such as CSS and JavaScript. head The head element is the metadata parent element. All other metadata elements will be children of this element: Description The head element usually must have a title element inside it. The elements that can go in head are title, link, meta, style, script, noscript, and base. These elements are explained next. Here is an example of the head element that defines a title and stylesheet element:Title that appears as the tab name title The title element displays the title of the document. This is what is displayed in the browser's tab or the browser window:[3] HTML Elements Description The title element is an aptly named element. This is a required element in head, and there should only be one title element for a document. Here is a simple example of title element: Example link The link element links a resource to the current document: Attributes The attributes that are used in the link element are as follows: • crossorigin: This tells the browser whether to make the Cross-Origin • href: This indicates the URL of the resource • media: This selects the media that this resource applies to • rel: This indicates the relationship of this resource to the document • sizes: This is used with rel when it is set to icons • type: This indicates the type of content of the resource Resource Sharing (CORS) request or not Description The link element has a lot of attributes, but most of the time, it is used for loading the CSS resources. This means that you will want to use the attributes href, rel, type, and media at least. You can have multiple link elements in a head element. Here is a simple example of how to load CSS: See also You can also refer to the crossorigin, href, media, rel, sizes, and type attributes to find out more details about the title element. [4] Chapter 1 meta The meta element contains metadata about the document. The syntax is as follows: Attributes The attributes that are used in the meta element are as follows: • content: This states the value of either the name or http-equiv attribute. • http-equiv: This attribute, in the case of HTML5, can be set to defaultstyle, which sets the default style. Alternatively, it can be set to refresh, which can specify the number of seconds taken to refresh the page and a different URL for the new page if needed, for example, httpequiv="1;url=http://www.google.com". • name: This states the name of the metadata. Description The meta tag has many nonstandard applications. The standardized applications can be viewed in Chapter 2, HTML Attributes. Apple has many meta tags that will pass information to an iOS device. You can set a reference to an App Store application, set an icon, or display the page in the full screen mode, as just a few examples. All of these tags are nonstandard, but useful when targeting iOS devices. This is true for many other sites and companies. You can use multiple meta tags in a head element. Here are two examples. The first example will refresh the page every 5 seconds and the other will define the author metadata: See also You can also refer to the name attribute to find out more details about the meta element. [5] HTML Elements style The style element contains the style information. CSS: Attributes The attributes that are used in the style element are as follows: • media: This is a media query • scoped: The styles contained in this element only apply to the parent element • type: This sets the type of document; the default value is text/css Description The style element is usually in the head element. This allows you to define CSS styles for the current document. The preferred method of using CSS is to create a separate resource and use the link element. This allows styles to be defined once and used everywhere on a website instead of defining them on every page. This is a best practice as it allows us to define the styles in one spot. We can then easily find and change styles. Here is a simple inline stylesheet that sets the font color to blue: See also You can also refer to the global attributes and Chapters 3-7 to know more details about the style element. base The base element is the base URL for the document. The syntax is as follows:[6] Chapter 1 Attributes The attributes that are used in the base element are as follows: • href: This indicates the URL to be used as the base URL • target: This indicates the default target to be used with the URL Description The base URL is used whenever a relative path or URL is used on a page. If this is not set, the browser will use the current URL as the base URL. Here is an example of how to set the base URL: See also You can also refer to the target attribute to find out more details about the base element. script The script element allows you to reference or create a script for the document: [ 64 ] Chapter 2 autocomplete The autocomplete attribute defines whether the element can be autocompleted: Elements The form and input elements are used in the autocomplete attribute. Description The autocomplete attribute lets the browser know whether or not it can autocomplete the form or input from the previous values. This can have on and off as the values. Here is an example: autofocus The autofocus attribute defines whether the element would be focused automatically on the elements: Elements The button, input, select, and textarea elements are used in the autofocus attribute. Description The autofocus attribute will set the focus to the element. This should only be used on one element. Here is an example of the autofocus attribute with a text input: [ 65 ] HTML Attributes autoplay The autoplay attribute defines whether the audio or video track should play as soon as possible: Elements The audio and video elements are used in the autoplay attribute. Description The autoplay attribute will make the element play as soon as it can, without having to stop to load. Here is an example with an audio file: autosave The autosave attribute defines whether the previous values should be saved: Elements The input element is used in the autosave attribute. Description The autosave attribute tells the browser to save values entered into this input. This means that on the next page load, the values will be persisted. It should have a unique name that the browser can associate the saved values to. This attribute may or may not work in some browsers as it is not fully standardized. Here is an example: cite The cite attribute has the source of the quote: [ 66 ] Chapter 2 Elements The blockquote, del, ins, and q elements are used in the cite attribute. Description The cite attribute points to the source of a quote by providing a URL. Here is an example: After a meal there's nothing like a good cigar.cols The cols attribute gives the number of columns:Elements The textarea element is used with the cols attribute. Description The cols attribute gives the number of columns in a textarea element. Here is an example of it in use: colspan The colspan attribute gives the number of columns a cell should span: Elements The td and th elements are used in the colspan attribute. [ 67 ] HTML Attributes Description The colspan attribute gives the number of columns a table cell should span. Here is an example using a table element:
1 and 2 | |
1 | 2 |
Pets | Dogs |
Cats |
Name | Age |
---|---|
Gizmo | 4 |
structure.
Here are a few spans in a row: 1 2 3 4
CSS: span + span { color: #ff0000; } The general sibling combinator This selector targets any element that has the same parent and follows the first: element-a ~ element-b Description This is similar to the adjacent sibling combinatory; in that, both elements need the same parent. The difference is that the two elements can be separated by other elements. Here is an example that shows that both the second and third spans will be targeted even though there is an em element between them. Here is the HTML:Here are a few spans in a row: 1 2 3 4
Here is the CSS rule: span ~ span { color: #ff0000; } [ 97 ] CSS Concepts and Applications The selector specificity This is not a selector rule like the others in this section. An element can be targeted by multiple rules, so how do you know which rule takes precedence? This is where specificity comes in. You can calculate which rule will be applied. Here is how it is calculated. Keep in mind that an inline style will trump any selector specificity: • The number of ID selectors in the selector is denoted by a • The number of class selectors, attribute selectors, and pseudo-classes in the selector is denoted by b • The number of type selectors and pseudo-elements in the selector is denoted by c • Any universal selectors are ignored The numbers are then concatenated together. The larger the value, the more precedence the rule has. Let's look at some selector examples. The examples will be composed of the selector and then the calculated value: • h1: a=0 b=0 c=1, 001 or 1 • h1 span: a=0 b=0 c=2, 002 or 2 • h1 p > span: a=0 b=0 c=3, 003 or 3 • h1 *[lang="en"]: a=0 b=1 c=1, 011 or 11 • h1 p span.green: a=0 b=1 c=3, 013 or 13 • h1 p.example span.green: a=0 b=2 c=3, 023 or 23 • #title: a=1 b=0 c=0, 100 • h1#title: a=1 b=0 c=1, 101 The easiest way to think about this is that each grouping (a, b, or c) should be a smaller group of elements to choose from. This means that each step has more weight. For example, there can be many instances of h1 on a page. So, just selecting h1 is a little ambiguous. Next, we can add a class, attribute, or pseudo-class selector. This should be a subset of the instances of h1. Next, we can search by ID. This carries the most weight because there should only be one in the entire document. Here is an example HTML that has three headings:First paragraph.
Second paragraph.
Here is the CSS. This will change the text of the first paragraph red: p:first-child { color: #ff0000; } :first-of-type This targets the first element type that is a child of another element: :first-of-type Description The :first-of-type attribute is different from :first-child because it will not select the element unless it is the first child. This is the same as :nth-of-type(1). Here is an example that will target the first paragraph element even though it is not the first child. Here is the HTML:First paragraph.
Second paragraph.
First paragraph.
Second paragraph.
Here is the CSS. This will change the color of the second and first paragraph red. This selector works because even on the most basic of pages, the p element is a child of the body element: p:last-child { color: #ff0000; } :last-of-type This targets the last element type that is a child of another element: :last-of-type Description The :last-of-type attribute is different from :last-child because it will not select the element unless it is the first last-child attribute. This is the same as :nthlast-of-type(1). Here is an example that will target the last paragraph element. Here is its HTML:First paragraph.
Second paragraph.
A linkFirst (will be red) |
Second |
Third (will be red) |
First |
Second |
Third |
Fourth |
First
First Span Second SpanSecond
Third
[ 105 ] CSS Concepts and Applications Here is the CSS. This rule will only target the paragraphs and make the odd ones red: p:nth-of-type(2n+1) { color: #ff0000; } See also The previous section :nth-child. :only-child This targets an element that has no siblings: :only-child Description This will match when the :only-child attribute is the only child of an element. Here is an example with two tables, where one has multiple rows and the other has only one:First |
Second |
Third |
Only |
Only p.
Not the
only one.
Targeted Element
Non targeted element
Here is the CSS. Only the first paragraph will be targeted: p:not(.not-me) {color: #ff0000; } [ 110 ] Chapter 3 :optional and :required The :optional and :required attributes target elements that are either optional or required, respectively. :optional :required Description This is used for any input element that is required or optional. Here is an example that has two inputs—one that is required and one that is not: Here is the CSS. The required input will have red text and the optional input will have green text: :required { color: #ff0000; } :optional { color: #00ff00; } :lang() The :lang() attribute targets based on the language: :lang(language) Description This selector works differently to the attribute selector; in that, this will target all elements that are in a specific language even if they are not explicitly defined. The attribute selector will only target elements that have a lang attribute. Here is an example with a span element that does not have a lang attribute, but it is the child of the body which does: This is English. [ 111 ] CSS Concepts and Applications Here is the CSS. The first rule will match the element, but the second will not match anything: :lang(en) { color: #ff0000; } span[lang|=en] { color: #00ff00; } Pseudo-elements These are selectors that go beyond what is specified in the document. The selectors select things that may not even be elements in the document. Pseudo-elements are not considered part of a simple selector. This means that you cannot use a pseudo-element as part of the :not() selector. Finally, only one pseudo-element can be present per selector. Note that all of the pseudo-elements start with a double colon (::). This was introduced in CSS3 to help differentiate between pseudo-classes that have a single colon (:). This is important because in CSS2, pseudoelements only had the single colon. For the most part, you should use the double colon. ::before and ::after These are used to insert generated content before or after the selected element: ::before ::after e Description This will insert content into the document based on the selector. Whether the content is placed before or after the element targeted depends on the pseudo-element used. Refer to the Generated content section to see what you can insert. Here is an example that uses both ::before and ::after. This will create a turkey sandwich. Here is the HTML.Turkey
Here is the CSS that will put a slice of bread before and after the turkey: p.sandwich::before, p.sandwich::after { content: ":Slice of Bread:"; } [ 112 ] Chapter 3 See also Generated content ::first-letter This targets the first letter of an element: ::first-letter Description This will select the first letter of an element as long as it does not have any other content before it, for example an img element before a character would make ::first-letter not select the first character. Any punctuation that either precedes or follows the first letter would be included with the first letter. This will select any character, including not just letters but also numbers. This only applies to block-like containers such as block, list-item, table-cell, table-caption, and inline-block elements. The ::first-letter pseudo-element will only match if the first letter is on the first formatted line. If there is a line break before the first letter appears, it will not be selected. Here is an example, which will not select the first letter:
First letter
This is a long line of text that may or may not be broken up across lines.
Here is the CSS. The T in This will be two times the font size of all the other characters: p::first-letter { font-size: 2em; } ::first-line The ::first-line attribute targets the first line of an element: ::first-line [ 113 ] CSS Concepts and Applications Description This will target the first formatted line of a block-like container such as a block box, inline-block, table-caption, or table-cell. Here is an example, with the following HTML:This is a long line of text that may or may not be broken up across lines based on the width of the page and the width of the element it is in.
This is the entire first line.
Here is the CSS. This will make the first line, whatever it may be, red: p::first-line { color: #ff0000; } ::selection This targets text highlighted by the user: ::selection Description This pseudo-element allows you to style any text that is highlighted by the user. This pseudo-element does not exist in CSS3, but it is part of the next version. Most browsers will still honor this pseudo-element. Here is an example:Highlight this to text.
Here is the CSS. When the text is selected, the text will be white on a red background: ::selection { color: #ffffff; background: #ff0000; } Generated content This is not a selector, but is used with the pseudo-elements ::before and ::after. There are only certain types of content that you can generate. Here is a rundown. [ 114 ] Chapter 3 content This is the content that will be placed either before or after elements: content(none,Don't quote me on this.[ 115 ] CSS Concepts and Applications Here is the CSS. The h1 elements will have the word "chapter" along with a number before each. The h2 element will have a line break in its content. Finally, the blockquote will have an opening quote and a closing quote: h1 { counter-increment: chapter; } h1::before { content: "Chapter" counter(chapter) ": " attr(class) ; } h2::before { content: "New\A Line"; white-space: pre; } blockquote::before { content: open-quote; } blockquote::after { content: close-quote; } Quotation marks Quotation marks specify which characters are used as open and close quotes: quotes: [
Don't quote meThe quotation marks are completely arbitrary. Here is the CSS: blockquote { quotes: ":" "!" "&" "*"; } [ 116 ] CSS Properties – Part 1 CSS properties are characteristics of an element in a markup language (HTML, SVG, XML, and so on) that control their style and/or presentation. These characteristics are part of a constantly evolving standard from the W3C. A basic example of a CSS property is border-radius: input { border-radius: 100px; } There is an incredible number of CSS properties, and learning them all is virtually impossible. Adding more into this mix, there are CSS properties that need to be vendor prefixed (-webkit-, -moz-, -ms-, and so on), making this equation even more complex. Vendor prefixes are short pieces of CSS that are added to the beginning of the CSS property (and sometimes CSS values too). These pieces of code are directly related to either the company that makes the browser (the "vendor") or to the CSS engine of the browser. There are four major CSS prefixes: -webkit-, -moz-, -ms- and -o-. They are explained here: • -webkit-: This references Safari's engine, Webkit (Google Chrome and Opera used this engine in the past as well) • -moz-: This stands for Mozilla, who creates Firefox • -ms-: This stands for Microsoft, who creates Internet Explorer • -o-: This stands for Opera, but only targets old versions of the browser Google Chrome and Opera both support the -webkit- prefix. However, these two browsers do not use the Webkit engine anymore. Their engine is called Blink and is developed by Google. [ 117 ] CSS Properties – Part 1 A basic example of a prefixed CSS property is column-gap: .column { -webkit-column-gap: 5px; -moz-column-gap: 5px; column-gap: 5px; } Knowing which CSS properties need to be prefixed is futile. That's why it's important to keep a constant eye on CanIUse.com. However, it's also important to automate the prefixing process with tools such as Autoprefixer or -prefix-free, or mixins in preprocessors, and so on. However, vendor prefixing isn't in the scope of the book, so the properties we'll discuss are absent of any vendor prefixes. If you want to learn more about vendor prefixes, you can visit Mozilla Developer Network (MDN) at http://tiny.cc/ mdn-vendor-prefixes. Let's get the CSS properties reference rolling. Animation Unlike the old days of Flash, where creating animations required third-party applications and plugins, today we can accomplish practically the same things with a lot less overhead, better performance, and greater scalability all through CSS only. Forget plugins and third-party software! All we need is a text editor, some imagination, and a bit of patience to wrap our heads around some of the animation concepts CSS brings to our plate. Base markup and CSS Before we dive into all the animation properties, we will use the following markup and animation structure as our base: HTML: CSS: .element { width: 300px; height: 300px; } [ 118 ] Chapter 4 @keyframes fadingColors { 0% { background: red; } 100% { background: black; } } In the examples, we will only see the .element rule since the HTML and @keyframes fadingColors will remain the same. The @keyframes declaration block is a custom animation that can be applied to any element. When applied, the element's background will go from red to black. Ok, let's do this. animation-name The animation-name CSS property is the name of the @keyframes at-rule that we want to execute, and it looks like this: animation-name: fadingColors; Description In the HTML and CSS base example, our @keyframes at-rule had an animation where the background color went from red to black. The name of that animation is fadingColors. So, we can call the animation like this: CSS: .element { width: 300px; height: 300px; animation-name: fadingColors; } This is a valid rule using the longhand. There are clearly no issues with it at all. The thing is that the animation won't run unless we add animation-duration to it. [ 119 ] CSS Properties – Part 1 animation-duration The animation-duration CSS property defines the amount of time the animation will take to complete a cycle, and it looks like this: animation-duration: 2s; Description We can specify the units either in seconds using s or in milliseconds using ms. Specifying a unit is required. Specifying a value of 0s means that the animation should actually never run. However, since we do want our animation to run, we do the following: CSS: .element { width: 300px; height: 300px; animation-name: fadingColors; animation-duration: 2s; } As mentioned earlier, this will make a box go from its red background to black in 2 seconds and then stop. animation-iteration-count The animation-iteration-count CSS property defines the number of times the animation should be played, and it looks like this: animation-iteration-count: infinite; Description Here are two values: infinite and a number, such as 1, 3, or 0.5. Negative numbers are not allowed. Add the following code to the prior example: CSS: .element { width: 300px; height: 300px; animation-name: fadingColors; animation-duration: 2s; animation-iteration-count: infinite; } [ 120 ] Chapter 4 This will make a box go from its red background to black, start over again with the red background and go to black, infinitely. animation-direction The animation-direction CSS property defines the direction in which the animation should play after the cycle, and it looks like this: animation-direction: alternate; Description There are four values: normal, reverse, alternate, and alternate-reverse. • normal: This makes the animation play forward. This is the default value. • reverse: This makes the animation play backward. • alternate: This makes the animation play forward in the first cycle, then backward in the next cycle, then forward again, and so on. In addition, timing functions are affected, so if we have ease-out, it gets replaced by ease-in when played in reverse. We'll look at these timing functions in a minute. • alternate-reverse: This is the same thing as alternate, but the animation starts backward, from the end. In our current example, we have a continuous animation. However, the background color has a "hard stop" when going from black (end of the animation) to red (start of the animation). Let's create a more "fluid" animation by making the black background fade into red and then red into black without any hard stops. Basically, we are trying to create a "pulse-like" effect: CSS: .element { width: 300px; height: 300px; animation-name: fadingColors; animation-duration: 2s; animation-iteration-count: infinite; animation-direction: alternate; } [ 121 ] CSS Properties – Part 1 animation-delay The animation-delay CSS property allows us to define when exactly an animation should start. This means that as soon as the animation has been applied to an element, it will obey the delay before it starts running. It looks like this: animation-delay: 3s; Description We can specify the units either in seconds using s or in milliseconds using ms. Specifying a unit is required. Negative values are allowed. Take into consideration that using negative values means that the animation should start right away, but it will start midway into the animation for the opposite amount of time as the negative value. Use negative values with caution. CSS: .element { width: 300px; height: 300px; animation-name: fadingColors; animation-duration: 2s; animation-iteration-count: infinite; animation-direction: alternate; animation-delay: 3s; } This will make the animation start after 3 seconds have passed. animation-fill-mode The animation-fill-mode CSS property defines which values are applied to an element before and after the animation. Basically, outside the time the animation is being executed. It looks like this: animation-fill-mode: none; [ 122 ] Chapter 4 Description There are four values: none, forwards, backwards, and both. • none: No styles are applied before or after the animation. • forwards: The animated element will retain the styles of the last keyframe. This the most used value. • backwards: The animated element will retain the styles of the first keyframe, and these styles will remain during the animation-delay period. This is very likely the least used value. • both: The animated element will retain the styles of the first keyframe before starting the animation and the styles of the last keyframe after the animation has finished. In many cases, this is almost the same as using forwards. The prior properties are better used in animations that have an end and stop. In our example, we're using a fading/pulsating animation, so the best property to use is none. CSS: .element { width: 300px; height: 300px; animation-name: fadingColors; animation-duration: 2s; animation-iteration-count: infinite; animation-direction: alternate; animation-delay: 3s; animation-fill-mode: none; } animation-play-state The animation-play-state CSS property defines whether an animation is running or paused, and it looks like this: animation-play-state: running; Description There are two values: running and paused. These values are self-explanatory. [ 123 ] CSS Properties – Part 1 CSS: .element { width: 300px; height: 300px; animation-name: fadingColors; animation-duration: 2s; animation-iteration-count: infinite; animation-direction: alternate; animation-delay: 3s; animation-fill-mode: none; animation-play-state: running; } In this case, defining animation-play-state as running is redundant, but I'm listing it for purposes of the example. animation-timing-function The animation-timing-function CSS property defines how an animation's speed should progress throughout its cycles, and it looks like this: animation-timing-function: ease-out; There are five predefined values, also known as easing functions, for the Bézier curve (we'll see what the Bézier curve is in a minute): ease, ease-in, ease-out, ease-in-out, and linear. ease The ease function sharply accelerates at the beginning and starts slowing down towards the middle of the cycle, and it looks like this: animation-timing-function: ease; ease-in The ease-in function starts slowly accelerating until the animation sharply ends, and it looks like this: animation-timing-function: ease-in; ease-out The ease-out function starts quickly and gradually slows down towards the end and it looks like this: animation-timing-function: ease-out; [ 124 ] Chapter 4 ease-in-out The ease-in-out function starts slowly and it gets fast in the middle of the cycle. It then starts slowing down towards the end. And it looks like this: animation-timing-function:ease-in-out; linear The linear function has constant speed. No accelerations of any kind happen. It looks like this: animation-timing-function: linear; Now, the easing functions are built on a curve named the Bézier curve and can be called using the cubic-bezier() function or the steps() function. cubic-bezier() The cubic-bezier() function allows us to create custom acceleration curves. Most use cases can benefit from the already defined easing functions we just mentioned (ease, ease-in, ease-out, ease-in-out and linear), but if you're feeling adventurous, cubic-bezier() is your best bet. Here's what a Bézier curve looks like: [ 125 ] CSS Properties – Part 1 Parameters The cubic-bezier() function takes four parameters as follows: animation-timing-function: cubic-bezier(x1, y1, x2, y2); X and Y represent the x and y axes. The numbers 1 and 2 after each axis represent the control points. 1 represents the control point starting on the lower left, and 2 represents the control point on the upper right. Description Let's represent all five predefined easing functions with the cubic-bezier() function: • ease: animation-timing-function: cubic-bezier(.25, .1, .25, 1); • ease-in: animation-timing-function: cubic-bezier(.42, 0, 1, 1); • ease-out: animation-timing-function: cubic-bezier(0, 0, .58, 1); • ease-in-out: animation-timing-function: cubic-bezier(.42, 0, .58, • linear: animation-timing-function: cubic-bezier(0, 0, 1, 1); 1); I'm not sure about you, but I prefer to use the predefined values. Now, we can start tweaking and testing each value to the decimal, save it, and wait for the live refresh to do its thing. However, that's too much time wasted testing if you ask me. The amazing Lea Verou created the best web app to work with Bézier curves. You can find it at cubic-bezier.com. This is by far the easiest way to work with Bézier curves. I highly recommend this tool. The Bézier curve image showed earlier was taken from the cubic-bezier.com website. [ 126 ] Chapter 4 Let's add animation-timing-function to our example: CSS: .element { width: 300px; height: 300px; animation-name: fadingColors; animation-duration: 2s; animation-iteration-count: infinite; animation-direction: alternate; animation-delay: 3s; animation-fill-mode: none; animation-play-state: running; animation-timing-function: ease-out; } steps() The steps() timing function isn't very widely used, but knowing how it works is a must if you're into CSS animations. It looks like this: animation-timing-function: steps(6); This function is very helpful when we want our animation to take a defined number of steps. After adding a steps() function to our current example, it looks like this: CSS: .element { width: 300px; height: 300px; animation-name: fadingColors; animation-duration: 2s; animation-iteration-count: infinite; animation-direction: alternate; animation-delay: 3s; animation-fill-mode: none; animation-play-state: running; animation-timing-function: steps(6); } This makes the box take six steps to fade from red to black and vice versa. [ 127 ] CSS Properties – Part 1 Parameters There are two optional parameters that we can use with the steps() function: start and end. • start: This will make the animation run at the beginning of each step. This • end: This will make the animation run at the end of each step. This is the default value if nothing is declared. This will give the animation a short delay before it starts. will make the animation start right away. Description After adding a steps() function to our current example, it looks like this: CSS: .element { width: 300px; height: 300px; animation-name: fadingColors; animation-duration: 2s; animation-iteration-count: infinite; animation-direction: alternate; animation-delay: 3s; animation-fill-mode: none; animation-play-state: running; animation-timing-function: steps(6, start); } Granted, the pulsating effect in our example isn't quite noticeable when we add the steps() function. However, you can see it more clearly in this pen from Louis Lazarus when hovering over the boxes, at http://tiny.cc/steps-timingfunction Here's an image taken from Stephen Greig's article in Smashing Magazine, Understanding CSS Timing Functions, that explains start and end from the steps() function: [ 128 ] Chapter 4 Also, there are two predefined values for the steps() function: step-start and step-end. • step-start: This is the same thing as steps(1, start). It means that every change happens at the beginning of each interval. • step-end: This is the same thing as steps(1, end). It means that every change happens at the end of each interval. CSS: .element { width: 300px; height: 300px; animation-name: fadingColors; animation-duration: 2s; animation-iteration-count: infinite; animation-direction: alternate; animation-delay: 3s; animation-fill-mode: none; animation-play-state: running; animation-timing-function: step-end; } [ 129 ] CSS Properties – Part 1 animation The animation CSS property is the shorthand for animation-name, animationduration, animation-timing-function, animation-delay, animationiteration-count, animation-direction, animation-fill-mode, and animationplay-state. It looks like this: animation: fadingColors 2s; Description For a simple animation to work, we need at least two properties: animation-name and animation-duration. If you feel overwhelmed by all these properties, relax. Let me break them down for you in simple bits. Using the animation longhand, the code would look like this: CSS: .element { width: 300px; height: 300px; animation-name: fadingColors; animation-duration: 2s; } Using the animation shorthand, which is the recommended syntax, the code would look like this: CSS: .element { width: 300px; height: 300px; animation: fadingColors 2s; } This will make a box go from its red background to black in 2 seconds, and then stop. Final CSS code Let's see how all the animation properties look in one final example showing both the longhand and shorthand styles. [ 130 ] Chapter 4 Longhand style .element { width: 300px; height: 300px; animation-name: fadingColors; animation-duration: 2s; animation-iteration-count: infinite; animation-direction: alternate; animation-delay: 3s; animation-fill-mode: none; animation-play-state: running; animation-timing-function: ease-out; } Shorthand style .element { width: 300px; height: 300px; animation: fadingColors 2s infinite alternate 3s none running ease-out; } The animation-duration property will always be considered first rather than animation-delay. All other properties can appear in any order within the declaration. Here is a demo in CodePen: http://tiny.cc/animation Background The CSS background properties handle the display of background effects on HTML elements. background-attachment The background-attachment CSS property defines how the background of an element scrolls relative to its containing parent, and it looks like this: background-attachment: fixed; [ 131 ] CSS Properties – Part 1 Description There are three values: scroll, fixed, and local. • scroll: The background does not move within its container • fixed: The background stays fixed to the viewport, no matter what • local: The background scrolls within its container and the viewport CSS: .scroll { background-attachment: scroll; } .fixed { background-attachment: fixed; } .local { background-attachment: local; } Here is a demo in CodePen: http://tiny.cc/css-background background-blend-mode The background-blend-mode CSS property specifies how the background image of an element should blend with its background color, and it looks like this: background-blend-mode: multiply; Description There are 18 possible blend mode values: • color: Hue and saturation from the top color prevail, but the luminosity of • color-burn: The final color is the result of taking the bottom color and • color-dodge: The final color is the result of dividing the bottom color with • darken: The final color is the result of taking the darkest value per color in the bottom color is added. Gray levels are preserved. inverting it, dividing the value by the top color, and then inverting that value. the inverse of the top one. each channel. [ 132 ] Chapter 4 • difference: The final color is the result of taking the lighter color and • exclusion: The result is similar to the difference, but with lower contrast. • hard-light: If the bottom color is darker, then the result is multiply. However, if the bottom color is lighter, the result is screen. • hue: Takes the hue of the top color, and the saturation and luminosity of the bottom color. • inherit: The final color inherits the blend mode of its parent container. • initial: This is the default value without any blending. • lighten: The result is the lightest values per color from each channel. • luminosity: The result is the luminosity of the top color, and the hue and • multiply: Multiply the top and bottom colors. This is the same effect as printing the colors on a translucent film and laying them one on top of the other. • normal: The final color is the color on top, regardless of the color underneath • overlay: The final color is multiply if the bottom color is darker. And it would be screen if the bottom color is lighter. • saturation: The final color is the saturation of the top color plus the hue and • screen: Invert both the top and bottom colors, multiply them, and then • soft-light: Same as hard-light attribute but softer, like pointing a diffused light on the final color. subtracting the darker color of the background image and background color. saturation of the bottom one. it. luminosity of the bottom one. invert that final color. In the following example, we will declare two backgrounds, an image and a color, and then apply a blend mode to them: CSS with longhand: .element { width: 500px; height: 500px; background-image: url('../images/image.jpg'); background-color: red; background-blend-mode: multiply; } [ 133 ] CSS Properties – Part 1 CSS with shorthand: .element { width: 500px; height: 500px; background-image: url(../images/image.jpg) red; background-blend-mode: multiply; } Notice that in the second example, the path to the image is not inside quotes. The quotes, single [''] or double [""], are optional. CSS-Tricks has a great Pen showing all these blend modes. However, I forked it to improve a few things on it. So, check out the CodePen demo with all the blend modes at http://tiny.cc/ background-blend-mode background-clip The background-clip CSS property helps define whether an element's background extends below its border or not, and it looks like this: background-clip: border-box; Description There are four values: inherit, border-box, padding-box, and content-box. inherit This takes the value from its parent element. border-box This makes the background cover the entire container, including the border. padding-box This makes the background extend only up to where the border starts. content-box This works like border-box, but it will take into consideration any padding, thus creating a gap between the border and the background. [ 134 ] Chapter 4 CSS: .element { background-clip: border-box; } Here is a demo in CodePen: http://tiny.cc/background-clip background-color The background-color CSS property defines the solid background color of an element, and it looks like this: background-color: red; Description Also, transparent is actually a color in CSS. If we wanted to set a gradient background color, we'd have to use the background-image property instead. This is because gradients are actually images. The color value can be defined using any of the following methods: • Named color • Hexadecimal • RGB and RGBa • HSL and HSLa CSS: /*Named Color*/ .element { background-color: red; } /*HEX*/ .element { background-color: #f00; } /*RGB*/ .element { background-color: rgb(255,0,0); } [ 135 ] CSS Properties – Part 1 /*RGBa*/ .element { /*Background has 50% opacity*/ background-color: rgba(255, 0, 0, .5); } /*HSL*/ .element { background-color: hsl(0, 100%, 50%); } /*HSLa*/ .element { /*Background has 50% opacity*/ background-color: hsla(0, 100%, 50%, .5); } background-image The background-image CSS property sets an image or gradient in the background of an element, and it looks like this: background-image: url(../images/background.jpg); Alternatively, it could also look like this: background-image: linear-gradient(red, orange); Description This property supports the JPG, PNG, GIF, SVG, and WebP image formats. We can also use the none value to declare the absence of an image. An element can also have several background images in a single declaration. When it comes to gradients, there are two styles: Linear and Radial. Linear Its syntax is linear-gradient. These gradients can go vertical, horizontal, or diagonal. [ 136 ] Chapter 4 Radial Its syntax is radial-gradient. These gradients are circular in nature, and by default, they will adapt to an element's dimension. For example, if the element is a perfect square, it would make a perfect circular radial gradient. However, if the element is a rectangle, then the radial gradient would look like an oval. We can add as many colors in a gradient as we want or need to. Unless it is strictly necessary, I recommend that you steer away from doing so, as it can have a negative impact on browser performance. Additionally, in order to give us more control over the gradients, we can define where a gradient color stops so that the following one can start. This is called color stops. Color stops can be defined in pixels or percentages. Percentages are more commonly used because of their relative nature, which helps maintain the integrity and proportions of the gradients. CSS: /*Graphic file*/ .element { background-image: url(../images/bg-texture.jpg); } /*Multiple images*/ .element { background-image: url(../images/bg-icon.svg), url(../images/bg-texture.jpg); } /*Linear gradient*/ .element { background-image: linear-gradient(red, orange); } /*Linear Gradient with color stops*/ .element { background-image: linear-gradient(red 40px, orange 25%, green); } /*Radial gradient*/ .element { background-image: radial-gradient(red, orange); } /*Radial gradient with color stops*/ .element { background-image: radial-gradient(red 40px, orange 25%, green); } [ 137 ] CSS Properties – Part 1 background-origin The background-origin CSS property defines how the background gets rendered inside an element, and it looks like this: background-origin: border-box; Description This property works similarly to the background-clip CSS property, except that with background-origin, the background is resized instead of clipped. There are four values: border-box, padding-box, content-box, and inherit. • border-box: The background extends all the way to the edge of the • padding-box: The background extends to meet the border edge to edge • content-box: The background is rendered inside the content box • inherit: This is the default value container, but under the border CSS: .element { background-origin: border-box; } Here is a demo in CodePen: http://tiny.cc/background-origin background-position The background-position CSS property allows us to place the background (image or gradient) anywhere within its parent container, and it looks like this: background-position: 10px 50%; Description We can use three different types of values: predefined keywords, percentage, and length. Predefined keywords Values such as left, right, top, and bottom are the predefined keywords. [ 138 ] Chapter 4 Percentages Values such as 5% and 80%. Length Values such as 15px 130px. This property requires you to declare two values: the first value relates to the x axis (horizontal) and the second value to the y axis (vertical). The default value is 0 0; which is exactly the same as left top. CSS: /*Default values*/ .element { background-position: } /*Keyword values*/ .element { background-position: } /*Percentages values*/ .element { background-position: } /*Length values*/ .element { background-position: } 0 0; right bottom; 5% 80%; 15px 130px; Here is a demo in CodePen: http://tiny.cc/background-position background-repeat The background-repeat CSS property has two functions: 1. To define whether a background image is repeated or not 2. To determine how the background image is repeated It looks like this: background-repeat: no-repeat; [ 139 ] CSS Properties – Part 1 Alternatively, it could also look like this: background-repeat-x: repeat; Description This property only works if background-image has been declared. There are four values: repeat, repeat-x, repeat-y, and no-repeat. • repeat: The background image will repeat in both x and y axes. This will • repeat-x: The background image will only repeat in the x axis, hence, • repeat-y: The background image will only repeat in the y axis, hence, • no-repeat: The background image will not be repeated and will only display one instance of it. completely fill the container. This is the default value. horizontally. vertically. CSS: /*Default value*/ .repeat { background-repeat: repeat; } /*Repeat horizontally*/ .repeat-x { background-repeat: repeat-x; } /*Repeat vertically*/ .repeat-y { background-repeat: repeat-y; } /*No repeat*/ .no-repeat { background-repeat: no-repeat; } Here is a demo in CodePen: http://tiny.cc/background-repeat background-size The background-size CSS property defines the size of the background image, and it looks like this: background-size: contain; Description There are five values: a length value, a percentage value, auto, contain, and cover. [ 140 ] Chapter 4 Length value This is when we use one of the following units: px, em, in, mm, cm, vw, and so on. Percentage value This is when we use percentages such as 50%, 85%, and so on. auto This value scales the image in the corresponding direction (horizontal or vertical) in order to maintain its aspect ratio and not deform it. contain This value makes sure the image can be seen completely within its parent container. The image does not bleed on the edges; it's "contained". cover This value scales the image and takes the longest dimension (horizontal or vertical). It makes sure that the image completely covers that dimension. Bleeding can occur if the container and the image have different aspect ratios. When declaring the size of the background, we can use either one or two values. The first value is the width, and the second is the height of the background image. Using one value means that the second value is set to auto. When using two values, we are then defining the width and height values of the background image. We can use any measurement unit we want. Pixels, percentages, and the auto value are the most commonly used though. We can even combine multiple images in the same container. The background shorthand property is the best way to handle this situation. CSS: .contain { background-size: contain; } .cover { background-size: cover; } .auto { background-size: auto; } [ 141 ] CSS Properties – Part 1 .multiple { background-image: url(../images/image-1.jpg), url(../images/image-2.jpg); background-size: 150px 100px, cover; } Here is a demo in CodePen: http://tiny.cc/background-size background The background CSS property is the shorthand in which we can list all background values. I often see many developers write the longhand version of the property to declare a single value, such as a color. Here is an example: background-color: red; Although this is totally fine, I prefer to use the shorthand version for practically everything: background: red; This is a bit more scalable because if we need to add any other values, all we need to do is add the new value to this declaration rather than writing a separate one. However, at the end, it's all a matter of personal style. CSS: /*BG color*/ .element { background: red; } /*BG color and image*/ .element { background: url(../images/bg.png) red; } /*BG color, image and position*/ .element { background: url(../images/bg.png) 50% 50% red; } /*BG color, image, position and do not repeat*/ .element { background: url(../images/bg.png) 50% 50% red norepeat; } /*BG color, image, position, do not repeat and size*/ .element { background: url(../images/bg.png) 50% 50% / contain red no-repeat; } /*BG color, image, position, do not repeat, size and clip*/ .element { background: url(../images/bg.png) 50% 50% / contain red no-repeat content-box; } [ 142 ] Chapter 4 /*BG color, image, position, do not repeat, size, clip and attachment*/ .element { background: url(../images/bg.png) 50% 50% / contain red no-repeat content-box fixed; } Box model Every element in the web is a square, and as such, it has intrinsic characteristics: width, height, padding, border, and margin. All these characteristics, put together, make the box model. The almighty box model is one of the most talked about subjects in the CSS industry due to IE6 and IE7 being the most popular browsers back in the day. However, they had major issues interpreting this simple CSS concept. This meant the web designers and developers had to come up with all sorts of tricks to get around such a problem. Those days are now gone, for the most part at least. Let's move on to the box model properties. width The width CSS property specifies the width of an element's content area, and it looks like this: width: 10px; Alternatively, it could also look like this: width: 10px 50px; Description The content area is inside the padding, border, and margin of the element. Let's talk about the most used values and keywords: the length value, percentage value, auto, max-content, min-content, and fit-content. Length value This is basically when we use one of the following units: px, em, in, mm, cm, vw, and so on. Percentage value This is when we use percentages such as 50%, 85%, and so on. [ 143 ] CSS Properties – Part 1 auto This is a keyword value that allows the browser to choose the width of the element. max-content This is a keyword value that makes the container take the width of its content. min-content This is a keyword value that makes the container as small as possible depending on its content. fit-content This is a keyword value that makes the container match the width of its content. This works great on containers with unknown or variable width. You can find more information on MDN at http://tiny.cc/mdn-width CSS: /*max-content*/ .element { width: max-content; } /*min-content*/ .element { width: min-content; } /*fit-content*/ .element { width: fit-content; } Here is a demo in CodePen: http://tiny.cc/width height The height CSS property specifies the height of an element's content area, and it looks like this: height: 200px; [ 144 ] Chapter 4 Description The content area is inside the padding, border, and margin of the element. The most used values are a length value, a percentage value, and inherit. Length value This is basically when we use one of the following units: px, em, in, mm, cm, vw, and so on. Percentage value This is when we use percentages such as 50%, 85%, and so on. inherit With this keyword, the element will inherit its parent container's height. You can find more information on MDN at http://tiny.cc/mdn-height CSS: /*Length value*/ .element { height: 200px; } /*Percentage value*/ .element { height: 50%; } /*Inherit value*/ .element { height: inherit; } padding The padding CSS property creates a space on all four sides of an element on the inside, between its content and the edges, and it looks like this: padding: 10px; Alternatively, it could also look like this: padding: 10px 15px; [ 145 ] CSS Properties – Part 1 Description Borders and margins are outside of the content area and do not get affected by the padding. The padding property is the shorthand for padding-top, padding-right, paddingbottom, and padding-left. We can use one, two, three, or all four values. • One value: This means that all four sides have the same value. • Two values: The first value is for Top and Bottom. The second value is for Left and Right. • Three values: The first value is for Top. The second value is for Left and Right. The third value is for Bottom. • Four values: The first value is for Top. The second is for Right. The third is for Bottom. The fourth is for Left. Negative values are not allowed. CSS: /*Shorthand, ONE value: all four sides have the same padding*/ .element { padding: 10px; } /*Shorthand, TWO values: Top & Bottom - Left & Right*/ .element { padding: 10px 15px; } /*Shorthand, THREE values: Top - Left & Right - Bottom*/ .element { padding: 10px 15px 20px; } /*Shorthand, FOUR values: Top - Right - Bottom - Left*/ .element { padding: 10px 15px 20px 25px; } /*Longhand, all values. They can go in any order*/ .element { padding-top: 10px; padding-right: 15px; padding-bottom: 20px; padding-left: 25px; } margin The margin CSS property defines an outside space on one, two, three or all four sides of an element, and it looks like this: margin: 10px; [ 146 ] Chapter 4 Alternatively, it could also look like this: margin: 10px 15px; Description The margin property is the shorthand for margin-top, margin-right, marginbottom, and margin-left. Just like with padding, we can use one, two, three, or all four values. • One value: This means that all four sides have the same padding. • Two values: The first value is for Top and Bottom. The second value is for Left and Right. • Three values: The first value is for Top. The second value is for Left and Right. The third value is for Bottom. • Four values: The first value is for Top. The second is for Right. The third is for Bottom. The fourth value is for Left. Negative values are allowed. CSS: /*Shorthand, ONE value: all four sides have the same padding*/ .element { margin: 10px; } /*Shorthand, TWO values: Top & Bottom - Left & Right*/ .element { margin: 10px 15px; } /*Shorthand, THREE values: Top - Left & Right - Bottom*/ .element { margin: 10px 15px 20px; } /*Shorthand, FOUR values: Top - Right - Bottom - Left*/ .element { margin: 10px 15px 20px 25px; } /*Longhand, all values. They 1can go in any order*/ .element { margin-top: 10px; margin-right: 15px; margin-bottom: 20px; margin-left: 25px; } Collapsing margins There is a particular behavior with the margins. If two stacked elements have top and bottom margins, the margins are not added. Instead, the larger value is the only one taken into account. [ 147 ] CSS Properties – Part 1 For example, we have anonthis.
paragraph. The heading has a
bottom margin of 20px, and the paragraph has a top margin of 10px.
Our senses immediately tell us that the total margin is 30px, but in reality, because
vertical margins collapse, only the largest value is considered, in this case, 20px.
The reason for this is that many elements, such as headings and paragraphs in our
example, have both top and bottom margins. So, having the margins collapse allows
the content and layout to maintain consistency and avoid creating undesired extra
spacing between stacked elements.
This is also good because it saves us the effort of having to "negate" margins on every
stacked element that has top and bottom margins, again, to avoid creating those
extra spaces.
The way I see it, is that collapsing margins is an editorial feature of the CSS margin
property. I hope that the prior explanations help embrace this behavior.
Here is a demo in CodePen: http://tiny.cc/collapsing-margins
border
The border CSS property is the shorthand that defines an element's border thickness,
style, and color.
The border property and all its sister properties (border-width, border-style,
and border-color) and variations are self-explanatory, so there's no need for a
Description section like in prior properties.
The CSS example ahead will help clarify the use of these properties.
border-width
This is the thickness of the border. It can be declared using px or em, but px yields
more controllable results.
border-style
This defines the type of line or no line at all. It supports the following values: dashed,
dotted, double, groove, hidden, inset, none, outset, ridge, and solid.
[ 148 ]
Chapter 4
border-color
This defines the color of the line. It supports all color modes: HEX, RGB, RGBa, HSL,
HSLs, and color name.
Keep in mind that all HTML elements are squares, so we can target any side of an
element with border-top-color, border-right-color, border-bottom-color, or
border-left-color.
The order of the values in the shorthand does not affect the output.
In the following example, the top rule in shorthand syntax accomplishes exactly the
same accomplishment as the bottom rule with the longhand syntax:
CSS:
/*Shorthand*/
.element-shorthand {
border: 10px solid green;
}
/*Longhand*/
.element-longhand {
/*Width*/
border-top-width: 10px;
border-right-width: 10px;
border-bottom-width: 10px;
border-left-width: 10px;
/*Style*/
border-top-style: solid;
border-right-style: solid;
border-bottom-style: solid;
border-left-style: solid;
/*Color*/
border-top-color: green;
border-right-color: green;
border-bottom-color: green;
border-left-color: green;
}
[ 149 ]
CSS Properties – Part 1
box-sizing
The box-sizing CSS property allows us to change the way browsers understand the
box model by default, and it looks like this:
box-sizing: border-box;
Description
There are two values: content-box and border-box.
content-box
This is the default value. The padding, border, and margin values are added to the
final width and height of the element. This value is rarely used exactly because of the
behavior I just described.
border-box
On the other hand, since this value changes the box model, the padding and border
are not added to the final width and height of the element but only to the margin.
CSS:
/*Padding, border and margin are added to the element's dimensions*/
.element {
box-sizing: content-box;
}
/*Padding and border are not added to the element's dimensions, only
margin*/
.element {
box-sizing: border-box;
}
/*Always start your CSS with this rule*/
*, *:before, *:after {
box-sizing: border-box;
}
Here is a demo in CodePen: http://tiny.cc/box-sizing
max-height
The max-height CSS property defines the maximum height of an element, and it
looks like this:
max-height: 150px;
[ 150 ]
Chapter 4
Description
The max-height attribute overrides the height property. Negative values are not
allowed.
The most used values are a length value and a percentage value.
Length value
This is when we use one of the following units: px, em, in, mm, cm, vw, and so on.
Percentage value
This is when we use percentages such as 50%, 85%, and so on.
You can find more information on MDN at http://tiny.cc/mdn-max-height
CSS:
/*Length value*/
.element {
height: 75px;
/*This property overrides height*/
max-height: 150px;
}
/*Percentage value*/
.element {
max-height: 65%;
}
max-width
The max-width CSS property defines the maximum width of an element, and it looks
like this:
max-width: 75px;
Description
The max-width attribute overrides the width property. Negative values are not
allowed.
The most used values are a length value and a percentage value.
[ 151 ]
CSS Properties – Part 1
Length value
This is when we use one of the following units: px, em, in, mm, cm, vw, and so on.
Percentage value
This is when we use percentages such as 50%, 85%, and so on.
You can find more information on MDN at http://tiny.cc/mdn-max-width
CSS:
/*Length value*/
.element {
width: 150px;
/*This property overrides width*/
max-width: 75px;
}
/*Percentage value*/
.element {
max-width: 65%;
}
min-height
The min-height CSS property defines the minimum height of an element, and it
looks like this:
min-height: 300px;
Description
The min-height attribute overrides the height and max-height properties.
Negative values are not allowed.
The most used values are a length value and a percentage value.
Length value
This is when we use one of the following units: px, em, in, mm, cm, vw, and so on.
Percentage value
This is when we use percentages such as 50%, 85%, and so on.
You can find more information on MDN at http://tiny.cc/mdn-min-height
[ 152 ]
Chapter 4
CSS:
/*Length value*/
.element {
height: 75px;
max-height: 150px;
/*This property overrides height and max-height*/
min-height: 300px;
}
/*Percentage value*/
.element {
min-height: 65%;
}
min-width
The min-width CSS property defines the minimum width of an element, and it looks
like this:
min-widht: 300px;
Description
The min-width attribute overrides the width and max-width properties.
Negative values are not allowed.
The most used values are a length value and a percentage value.
Length value
This is when we use one of the following units: px, em, in, mm, cm, vw, and so on.
Percentage value
This is when we use percentages such as 50%, 85%, and so on.
You can find more information on MDN at http://tiny.cc/mdn-min-width
CSS:
/*Length value*/
.element {
width: 150px;
max-width: 75px;
[ 153 ]
CSS Properties – Part 1
/*This property overrides width and max-width*/
min-width: 300px;
}
/*Percentage value*/
.element {
min-width: 65%;
}
object-fit
The object-fit CSS property defines how a replaced element fits inside its content
box, and it looks like this:
object-fit: cover;
Description
A replaced element is an HTML element whose content and dimensions are intrinsic
(defined by the element itself) and are not defined by CSS or by its context or
surroundings.
Examples of replaced elements are ,