Mastering CSS - Rich Finelli - E-Book

Mastering CSS E-Book

Rich Finelli

0,0
37,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Rich Finelli's modern CSS training course, based on his bestselling Mastering CSS video, now available in a book. Master CSS from best practices to practical CSS coding.

About This Book

  • Learn CSS directly from Rich Finelli, author of the bestselling Mastering CSS training course
  • From best practices to deep coding, Rich Finelli shares his CSS knowledge with you
  • Rich Finelli covers the latest CSS updates with flexbox and works with retina devices

Who This Book Is For

This book is for web designers who wish to master the best practices of CSS in their web projects. You already know how to work with a web page, and want to use CSS to master website presentation.

What You Will Learn

  • Master fundamental CSS concepts like the anatomy of a rule set, the box model, and the differences between block and inline elements
  • Employ flexbox to layout and align elements simply and cleanly
  • Become proficient with CSS3 properties such as transitions, transforms, gradients, and animations
  • Delve into modular, reusable, and scalable CSS for more organized and maintainable style sheets
  • Understand media queries and other pillars of responsive web design
  • Get creative with the @font-face property, Google Web Fonts, font services such as Typekit, as well as, icon fonts
  • Understand the workflow for HiDPI (retina) devices using 2x images, SVG, and the srcset attribute

In Detail

Rich Finelli trains you in CSS deep learning and shows you the techniques you need to work in the world of responsive, feature-rich web applications. Based on his bestselling Mastering CSS training video, you can now learn with Rich in this book! Rich shares with you his skills in creating advanced layouts, and the critical CSS insights you need for responsive web designs, fonts, transitions, animations, and using flexbox.

Rich begins your CSS training with a review of CSS best practices, such as using a good text editor to automate your authoring and setting up a CSS baseline. You then move on to create a responsive layout making use of floats and stylable drop-down menus, with Rich guiding you toward a modular-organized approach to CSS.

Your training with Rich Finelli then dives into detail about working with CSS and the best solutions to make your websites work. You'll go with him into CSS3 properties, transforms, transitions, and animations. You'll gain his understanding of responsive web designs, web fonts, icon fonts, and the techniques used to support retina devices. Rich expands your knowledge of CSS so you can master one of the most valuable tools in modern web design.

Style and approach

Let Rich Finelli train you in CSS! This book has a direct training style because it is based on Rich's bestselling Mastering CSS training course.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 341

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Mastering CSS

 

 

 

 

 

 

 

 

 

 

 

 

 

A guided journey through modern CSS

 

 

 

 

 

 

 

 

 

 

 

 

 

Rich Finelli

 

 

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Mastering CSS

 

 

Copyright © 2017 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 author, 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: October 2017

Production reference: 2171117

 

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78728-158-5

www.packtpub.com

Credits

Author

Rich Finelli

Project Editor  

Suzanne Coutinho

 

Commissioning Editor  

Dominic Shakeshaft

 

 

 

Proofreader

Safis Editing

 

Acquisition Editor

Ben Renow-Clarke

Indexer

Pratik Shirodkar

 

Content Development Editor

Monika Sangwan

Graphics

Kirk D'Penha

 

Technical Editor

Nidhisha Shetty

 

Production Coordinator

Arvindkumar Gupta

 

 

 

Copy Editor

Tom Jacob

 

 

About the Author

Rich Finelli, is a front end developer and a CS video trainer. He is truly passionate and excited about front end technologies and enjoys learning about web development. Rich writes about what he's learning on his blog, richfinelli.com.

Thanks to my friends at Packt, Ben Renow-Clarke and Nidhisha Shetty for walking me through how to write a book. They must have thought I was George R. R. Martin with how many times I missed our target dates. Sorry for that. Thanks to Dominic Shakeshaft for reaching out to me and believing that my Mastering CSS video course should be the basis for a book. Speaking of the video course, thanks to Nitee Shetty for editing and collaborating on the video course, which this book is largely based on. Thanks to my mentors at Merrill Lynch: Pratik Mehta and my manager, Paresh Deshmukh, and everyone on the Front-end Engineering team whose relentless desire to learn pushes me to keep learning and honing my craft. And most of all, I'd like to thank my wife, Renee, for all her support while writing this book. Many, many evenings were spent writing this book after work. Her support and encouragement helped me hang in there to get this book written. Love you, Renee!

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

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 [email protected] 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.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

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

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787281582.

If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Conventions

Reader feedback

Customer support

Downloading the example code

Downloading the color images of this book

Errata

Piracy

Questions

CSS Foundations

The anatomy of a rule set and the three types of style sheets

Dissecting a rule set

External style sheets

Embedded style sheets

Inline style sheets

The box model and block versus inline elements

The box model

Block level elements versus inline elements

Summary

Ramping Up

Text editors

Snippets

Multiple cursors

Syntax highlighting

Code suggestion

CSS reset

Loading Eric Meyer's CSS reset

Examining the CSS reset

Customizing the CSS reset

Chrome DevTools

How to open developer tools

Changing CSS inside the inspector

Using the console to find errors

Renaming elements — classes and IDs

Classes

Classifying multiple elements

IDs

Should we use classes or IDs?

Descendant selectors

Parent, child, and sibling elements

Creating descendant selectors

Calculating the weight of selectors

BEM

Summary

Creating a Page Layout with Floats

Float introduction–flowing text around images

The Shark movies page

The original purpose of floats

Using the clear property to solve basic problems with floats

Creating a multicolumn layout

Centering an element

Floating columns

Targeting .column using a pseudo class

Collapsed containers

Solving the problems of floats

Using the clear method

Using overflow property with hidden value

The float method

Clearfix hack

Summary

Creating Buttons with Modular, Reusable CSS Classes, and CSS3

Creating buttons with modular CSS

Different button types

Building standard buttons

Multiple classes

Changing the width of the buttons

Changing the border and font colors of the buttons

Positioning the button

Specificity rules

The weights of different selectors

The !important declaration

The universal selector

Reality of the point system

Transitions

Creating a hover state

Using the transition property

Vendor prefixes

Transforms

Applying a scale to our button

Using the translate function

Using the rotate value

Adding vendor prefixes and :focus states

Styling the call-to-action button

Adding the HTML

Positioning using CSS

Styling the button

Gradients

Using the ultimate CSS gradient generator

The CSS output of the ultimate gradient generator

Summary

Creating the Main Navigation and Drop-Down Menu

Starting the navigation

The semantic HTML for building a menu

Using CSS to style the navigation

Using pseudo classes

The first child

The last child

nth-child pseudo class

nth-of-type pseudo class

Absolute positioning

Absolutely positioning the shark

Using fixed positioning for the nav bar

Building the drop-down menu

Creating the basic HTML list

Styling the dropdown

Fixing the hover state

Hiding the drop-down menu using the off-screen hidden technique

CSS animations (part 1)

Defining the animation name, duration, and timing function

Setting additional keyframes

Vendor prefixes

CSS animations (part 2)

Animation delay, iteration-count, and fill-mode

animation-fill-mode

Using the animation shorthand

Vendor prefixes

Additional info on animations

Finalizing the navigation

Fixing the Z index issue

Adding box-shadow

Summary

Becoming Responsive

Fluid grids

Converting pixels to percentages

Calculating percentage widths

Changing padding to a percentage

A fluid grid on the shark movies page

Flexible images

The octopus, crab, and whale images

The shark image

Shrinking images on the shark movies page

Media queries

Anatomy of a media query

Considering iPads and other tablet dimensions

Adding our three columns to the media query

The mobile-first approach

Solving the navigation problem

Mobile menu

Styling the mobile nav in its open state

Adding the hamburger menu icon

Hiding the menu

Using jQuery to trigger the menu on a click

Viewport meta tag

Testing our responsive design on a mobile device

The anatomy of the viewport meta tag

Summary

Web Fonts

The @font-face property

Adding font files directly to the site

Defining and applying new fonts in our CSS

@font-face: a little tricky business

Making it work in all browsers

Google Web Fonts

Finding Google Fonts

Applying fonts in CSS

Adobe Typekit

Selecting fonts from Typekit

Adding fonts to the site

Icon fonts

Building the footer

Downloading a free icon font from the ZURB Foundation

Adding the icon font to our website

Styling icon fonts

Summary

Workflow for HiDPI Devices

2x images

Creating a retina size image (2x)

Sizing down the 2x image using CSS

Checking the image quality on a retina device

Background images

Targeting the seaweed in the footer

Media query for device pixel ratio

Serving the 2x image only to retina devices

Scalable Vector Graphic (SVG)

Saving an Illustrator file as an SVG

Adding the SVG file as a background image

Adding the SVG as a regular ol' <img>

You can't stop SVG's, you can only hope to constrain them!

Using an inline SVG

Source set attribute (srcset)

What is srcset?

Adding a set of images to srcset

Testing the image set

Simplifying the srcset attribute

Browser support

Using the W descriptor and sizes attribute of the srcset attribute

Summary

Flexbox, Part 1

Overview of the flexible box layout module

Flex terminology

Flex container and flex items

Main size and cross size

Main axis and cross axis

Justify-content and align-items

From floats to flexbox

Removing float-related properties from the columns section

Turning on flexbox using display: flex

Changing the flex-direction

Browser shrinking

Understanding flex-grow, flex-basis, flex-shrink, and flex

Using flex-grow

Using flex-basis

Using flex-shrink

Using the flex shorthand

More layout, more positioning

Using the justify-content property

Nesting Flexboxes

Using automatic margins

Summary

Flexbox, Part 2

Building the product listing

Using align-items

Using the align-self Flexbox property

Using flex-wrap and align-content

Using flex-wrap

Using align-content

Using the flex-flow shorthand

Changing the display order of flex items

Accessibility impact

Vendor prefixes

Autoprefixer

Gulp

Flexbox homework assignment

Summary

Wrapping Up

The next steps

CSS preprocessors

Variables

Mixins

SASS nesting

Creating and importing partial files with SASS

JavaScript and jQuery

Conclusion and links

The box model and block versus inline elements

Floats

Modular CSS

CSS3

Creating the navigation

Making the site responsive

Web fonts

HiDPI devices

Flexbox

Final tidbit of advice: Audio Podcasts are terrific

Summary

Preface

HTML, CSS, and JavaScript are the three core languages of the web. The more you know about all three of them, the better off you'll be. Of these three, the role of CSS is as the presentation language of the web. It describes things such as the colors, fonts, and layout of your pages.

There are some basic prerequisites for this book. I expect you understand how to write HTML, and understand basic CSS including styling fonts, adding margins, padding and background colors, and other things, such as what a hexadecimal color code is. In the coming chapters, I'll cover some of the basic concepts such as the box model, display properties, and types of style sheet. I'll also touch on a small amount of JavaScript and jQuery. You don't need any prior knowledge of these, but you will be getting a taste of them in this book.

Now, take a look at the final site we're going to build. In order to learn CSS, we'll finish building the following HTML5 website, which is all about sharks. I say finish building this site because the basic HTML and CSS will already be in place, and you can download them from the download package for this book. We'll add all the things that I will show you, and more. This site features modular and reusable CSS, which you will learn about as we move through the book. The site will first be built with floats for layout, before we rewrite the layout using flexbox. And we use web fonts for our text:

The navigation features a drop-down menu that uses CSS animations:

The site also features a call-to-action button with a CSS gradient:

The site is fully responsive. When we resize the browser, you can see that our two-column layout shifts into a single-column layout:

Also, our menu turns into a menu designed for mobile devices:

If we scroll down a little bit, we can see that we have ghost buttons that use CSS transitions. It's ready for HiDPI devices such as Apple's retina displays:

Most of the imagery on the site uses SVG:

At the very bottom of the page, we are using an icon font:

So, as you can see, you'll learn some really cool stuff in this book. To get the most out of it, I recommend that you follow along with me as I code.

What this book covers

Chapter 1, CSS Foundations, covers the fundamental concepts necessary to master CSS.

Chapter 2, Ramping Up, talks about the Sublime text editor; CSS reset, which resets the default styles in the browser; and descendant selectors.

Chapter 3, Creating a Page Layout with Floats, deep dives into floats. We'll cover the basic usage of floats, followed by creating the layout with floats, and understanding the common headaches caused by floats and how to solve for them .

Chapter 4, Creating Buttons with Modular, Reusable CSS Classes, and CSS3, covers modular CSS and multiple classes, and uses CSS3 to add transitions, hover states, transforms, and gradients to our buttons.

Chapter 5, Creating the Main Navigation and Drop-Down Menu, explains the functionality and presentation of our primary navigation.

Chapter 6, Becoming Responsive, covers the foundations of responsive web design and explains how to implement it to transform our static website into a mobile website.

Chapter 7, Web Fonts, discusses the basic syntax of the @font-face rule, font services, usage scenarios, and providers of web fonts and icon fonts.

Chapter 8, Workflow for HiDPI Devices, covers techniques for preparing images to account for Retina using SVG and techniques like the srcset attribute.

Chapter 9, Flexbox, Part 1, introduces the Flexbox module covering the basic implementation and properties.

Chapter 10,Flexbox, Part 2, covers more depth on Flexbox, building a new product listing and more advanced properties.

Chapter 11, Wrapping Up, wraps up the concepts of CSS that we covered in this book and provides some information on other CSS features that you can explore.

What you need for this book

Throughout the book, I've used Chrome as my browser because of its DevTools, among other things, but other browsers have similar tools. We'll use DevTools to explore code directly in the browser.

I've also used macOS throughout. If you're a Windows user and I refer to the command (cmd) key anywhere in the book, you should pretend that I am referring to the Ctrl key. Other than that, I don't think this will be an issue.

I have used the text editor Sublime Text 3. I should say that Sublime isn't the only good one out there. There are others like Atom and Visual Studio Code that do many of the same things.

Even though this book is on mastering CSS, we can't do much with CSS without HTML. So, we'll be working in HTML quite a bit. The goal is to use very clean, semantic HTML; that's what we want to aim for.

Who this book is for

This book is for web designers and developers who wish to master the best practices of CSS in their web projects. You should already know how to work with a web page, and be ready to use CSS to master website presentation.

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.

Code words in text, database table names, folder names, filenames, file extensions, path names, dummy URLs, user input, and Twitter handles are shown as follows: "To change the size of text use the font-size property."

A block of code is set as follows:

h2 { font-size: 26px; font-style: italic; color: #eb2428; margin-bottom: 10px;}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

h2 {

font-size: 26px;

font-style: italic; color: #eb2428; margin-bottom: 10px;}

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 on 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.

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 email [email protected], 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 from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you. You can download the code files by following these steps:

Log in or register to our website using your email address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

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

The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Mastering-CSS. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/MasteringCSS_ColorImages.pdf.

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 [email protected] 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 [email protected], and we will do our best to address the problem.

CSS Foundations

In this first chapter, CSS Foundations, we're going to take a look at the fundamental concepts necessary to master CSS. You're going to learn about the best practices in web development.

In the world of web development, things change often. For instance, in the past, tables were the technique of choice when laying out a webpage. Today, using a table for layout is definitely not what you want to do. Floats have been the most common way to create a layout for a while and will be what we learn about first. In the last year or so, flexbox has started to overtake floats for layout and we’ll learn about flexbox towards the end of this book. CSS is progressing with other new layout modules that are designed to supplant floats for laying out a page. Grid layout, and CSS regions may be the way of the future. Since things rapidly evolve in the world of frontend web development, our key takeaway is that we can't stop learning CSS. In general, once you stop learning, your knowledge will becomes outdated very quickly. My intent is to teach the concepts and techniques that will benefit you for a long time.

In the two sections of this chapter, we'll review core concepts that are fundamental to web design and CSS. We'll start by reviewing how to create the most fundamental thing in CSS–the rule set-and go over the different places we can write those rule sets.

The anatomy of a rule set and the three types of style sheets

We're now a little more familiar with the content of the book and the website we're going to build. Before we start delving into more advanced topics, let's review a few CSS foundations. Going forward in this book, I'll use terms such as selector, property, and value, and you'll need to understand exactly what these terms mean in order to follow along. Here's what we'll do: we'll review a rule set first, and then we'll look at the three different places we can write those rule sets. So let's get started.

Dissecting a rule set

Let's jump into a CSS file and look at one of the rule sets in the following code block. It's targeting an h2-a level two headline. It's setting a font-size of 26px, a font-style of italic, a color to a shade of red, and a margin-bottom of 10px:

h2 { font-size: 26px; font-style: italic; color: #eb2428; margin-bottom: 10px; }

So nothing too scary here! Let's dissect this a little bit though:

selector { property: value; property: value; property: value; }

In the preceding code, h2 is the selector. We are selecting an element on the page to target our style rules. The h2 selector could be a p, an li, a div, an a, or any HTML element we want to target. It can also be a class, an ID, or an element attribute, which I'll talk about later. Next, we have properties and values inside the curly braces. From the opening curly brace to the closing curly brace is the declaration block. You can have as many properties as you want inside the curly braces, or declaration block. font-size, color, font-style, and margin are just a few of the many different properties that you can use. Each property has a corresponding value. Between each property and value, you must have a colon. Following the value is a semi colon, which is also mandatory. Each property and value is called a declaration. So the declaration block is everything inside the curly braces and a declaration is a single line that includes a property and a value. But really, there are three important things to remember in the anatomy of a rule set: the selector, the property, and the value. Now let's look at where we can write these rule sets.

External style sheets

Currently, we write our rule sets in an external style sheet. You can see it's literally its own file:

In the folder structure on the left-hand side of the screen, you can see that it's in a folder called css:

Besides external style sheets, there are also inline and embedded style sheets. The external style sheet is by far the best place to write your styles; it's a separate file that is linked to each HTML page. An external style sheet can control a whole website, which is the main reason why this is the preferred type of style sheet. Anywhere in between the <head></head> tags of your index.html file; this is where you can link to your external style sheet:

<head> <link rel="stylesheet" href="css/style.css"> </head>

The href attribute points to the location of the file. Here it's pointing to the css folder and then a file called style.css. There's also a rel attribute that just basically says that this is a stylesheet. In the past, you might have seen text/css as the value for the type attribute, as shown in the following code block, but that is no longer necessary in HTML5:

<head> <link rel="stylesheet" href="css/style.css"

type="text/css"

> </head>

You may have also seen a closing forward slash on a self-closing tag like the link element, but in HTML5 that forward slash is no longer necessary. So including it or excluding it won't have any impact on your site.

Embedded style sheets

Instead of using the best type of style sheet, the external style sheet, we can also write our rule sets in the head of HTML documents. This is called an embedded style sheet. There are plenty of reasons for not doing it this way. The main two reasons are that it hampers the workflow, and it only controls a single page of the site. What we would do is simply create somewhere in the head tag, these open and close <style> tags:

<head> <style> </style> </head>

Anywhere inside this open <style> tag we can start adding our rule sets, which will only affect this one page:

<head> <style> h2 { font-size: 50px; } </style> </head>

Again, this isn't the most preferred place to write your styles. Keeping them in an external style sheet will, 99 percent of the time, be the best place, but you do have the option of embedding styles in the head tag of your document.

Inline style sheets

Finally, the third type of style sheet is the inline style sheet. And its not really a style sheet - more like just an inline style. What we could do is write a style attribute actually inside an element in our HTML:

<h2 style="">

Inline styles are a little different from external and embedded style sheets that use the traditional rule set; here there's no selector and there's no complete rule set because you're writing it inside an HTML tag. We can enter a font-size of 10px. We write that property and value the same way we do in a rule set and we should cap it with a semicolon:

<h2 style="font-size: 10px;">

We can also change the color and cap that with a semicolon:

<h2 style="font-size: 10px; color: deeppink;">

Save this, refresh the website, and you can see the result:

This is by far the most inefficient way to write styles. However, writing CSS directly in an HTML element gives it the most weight and will overrule all embedded styles and all external styles that target the same element, unless the !important keyword is used. In Chapter 4, Creating Buttons with Modular, Reusable CSS Classes, and CSS3 in the Specificity Rules section, I dive into cascades and other factors that make certain rules weigh more and override other rules.

Okay, so we have now created a rule set and learned what each part of a rule set is called, specifically, the selector, property, and value. This information will be helpful for you to retain, as I'll use this terminology often. We also reviewed the three different places you can create a style sheet: externally, embedded within the <head> tag, and inline, directly inside of an element. Again, external style sheets are the most efficient because they can control an entire website. This is the only place I write CSS if I can help it. Next, we'll review two more core concepts: the box model and the display property.

The box model and block versus inline elements

In this section, we'll review two more foundations of CSS: the box model and block versus inline elements. Fully grasping these two concepts is key in laying the ground work for CSS mastery later. First, we will review the box model and then we'll look at how that relates to block level elements. We'll follow that up with the characteristics of inline elements.

The box model

The box model defines how wide and tall elements on a page will be. To determine the horizontal space an element occupies, you add up the content + padding-left + padding-right + border-left + border-right + margin-left + margin-right:

So let's take a look at this in practice by looking at the h1 on our site, which is the blue text that says, "Old Chompy".

Here is the ruleset that makes this headline look the way it does:

h1 { font-size: 40px; line-height:1.4; font-weight: bold; color: #0072ae }

Let's add in the following properties to give it a width, padding, border, and margin. As well as a noticeable background-color:

h1 { font-size: 40px; line-height:1.4; font-weight: bold; color: #0072ae

background-color: black;

width: 300px;

padding: 50px;

border: 10px solid blue;

margin: 50px;

}

Here's what our headline looks like now. One big box:

So those 5 properties that contribute to this element's box model are now in place; looking at the browser in the preceding screenshot, this h1 really looks like a box. We can see the border of 10px, the margin, which is outside the border, is 50px, and the padding, which is between the border and the text, is 50px. Then the width inside the padding is 300px. So this element's width is actually 300 + 20 + 100 + 100, which adds up to a total size of 520px. So even though we said the width is 300px by defining the width property in our CSS file, the true space this element occupies is 520px.

Now, that is the traditional box model. I can modify this traditional box model using the box-sizing property with the border-box value. So let's use the box-sizing property and see how that affects the site. Add the property and value to the bottom of the h1 declaration block, as shown here:

h1 { font-size: 40px; line-height:1.4; font-weight: bold; color: #0072ae background-color: black; width: 300px; padding: 50px; margin: 50px; border: 10px solid blue;

box-sizing: border-box;

}

As illustrated in the following screenshot, border-box will include essentially subtract the padding and border from the width and height calculation. If I use 300px as my width, the border of 20px and the padding of 100px will be subtracted from the 300px I specified. This is a more intuitive box model and it is compatible with Internet Explorer 8 and higher, as well as all other major browsers. The final horizontal space this element now occupies goes from 520px to 400px.

Block level elements versus inline elements

Let's talk a little bit about block level elements. The heading 1 (h1), heading 2 (h2), paragraphs (p), list items (li), and divs (div) are all examples of natural block level elements. Block level elements have two defining traits: they expand the full width available, and they force elements that come after them to appear on the next line, meaning they stack on top of each other. So let's remove the box-sizing property from our declaration block as well as the width property to demonstrate how they take up the full width available if no width is specified:

h1 { font-size: 40px; line-height:1.4; font-weight: bold; color: #0072ae background-color: black; padding: 50px; margin: 50px; border: 10px solid blue;}

Save this and refresh the site. You can see in the following screenshot that, as you make your browser window larger, it takes up the full width available, apart from the margin that we set of 50px on all sides:

Now let's go into the HTML file, add two more of these h1 tags into the HTML, and save it:

<section> <h1>Old Chompy</h1> <h1>Old Chompy</h1> <h1&gt;Old Chompy</h1>

Here's what that looks like:

Now you can see how these block level elements stack on top of each other: good ol' block level elements.

Inline elements, on the other hand, behave differently. They sit next to each other horizontally and they don't take up the full width available. They only take up as much width as they need. A few elements that are naturally inline elements are the anchor (<a>), <span>, <i>, <b>, <strong>, and <em> tags.

Alright, so let me go into the HTML and add three span tags to the page:

<section> <h1>Old Chompy</h1> <h1>Old Chompy</h1> <h1>Old Chompy</h1> <span>Inline</span> <span>Inline</span> <span>Inline</span>

What I'll also do is generally target those span elements in a rule set and give them a green background, just to kind of see that they're distinct:

span { background-color: green; }

Here's how that looks:

You can notice how the green inline elements sit next to each other horizontally instead of stacking vertically. Nothing special, but we can see how they do not take up the full width available, they only take as much as they need.

There are some things that inline elements do not do. They don't respond to width or margin-top or margin-bottom. So if an element is naturally inline and you give it a width and a margin-top or margin-bottom, as shown in the following code, it's going to do absolutely nothing:

span { background-color: green;

width: 1000px; margin-top: 1000px;

}

Nothing changes:

Inline elements just don't respect those properties, and those properties don't have an impact on them, so we'll remove those.

There's one last interesting thing you can do. There's a display property that allows you to change a natural block level element to inline and vice versa. So let's add a display property with the block value to our span selector and view that in the browser. So, I can just say display: block and also add some margin-top:

span { background-color: green;

display: block;

margin-top: 10px;

}

We can see that these elements now stack on top of each other and now respect themargin-topandmargin-bottomvalues:

Elements with the display property set to block would respect any width value I give it, but it also takes up the full width available. You can see that it extends all the way to the edge of our screen. We could've just as easily used the display: inline property on our h1 selector to change the nature of the display from block to inline. Lastly though, we can use display: none, which totally hides the element from the page and is often used for various reasons. So let's go to our h1 declaration and say display: none:

h1 { font-size: 40px; line-height:1.4; font-weight: bold; color: #0072ae; background-color: black; padding: 50px; margin: 50px; border: 10px solid blue;

display: none;

}

Now, if we look at our site, that h1 is invisible. It's no longer something that the browser is going to show us:

To sum up, all elements conform to a box model. The box model changes a little depending on how the box-sizing property is used, if used at all. Also, the box model changes based on whether the element is block or inline, the two most common display properties.

Summary

We have accomplished a lot in this first chapter. We've talked about how CSS is the presentation language of the web and really makes your website look like a website. We're now familiar with the site we'll be building and tools we'll be using in the upcoming chapters. We have covered core concepts such as rule sets, linking to an external style sheet, and the box model and display properties, all of which are vital in order to master CSS.

In the next chapter, we'll get into some tools that are necessary to write CSS, such as a good text editor, a CSS reset, and Chrome's Developer tools.

Ramping Up

In order to be a great coder, you need to ramp up and learn about things that will help you become a better developer. In this chapter, we're going to look at text editors that will speed up our workflow. We'll then look at a CSS reset, which resets the default browser such that its styling is reduced to nothing, and the built-in browser developer tools to help us troubleshoot our code. Then, we'll look at how to rename elements with classes and IDs as well as qualify our selectors using descendant selectors.

Text editors

HTML, CSS, and JavaScript can be written in any text-editing application. This is one of the great things about the three core web languages. The problem is that writing HTML, CSS, and JavaScript is extremely error-prone. For CSS, commas, semicolons, and curly braces need to be typed in the right spots. A specific syntax needs to be adhered to perfectly in most cases, else your page won't render as expected. The following is an illustration of TextEdit for Mac. It's similar in nature to Notepad for Windows, in that it doesn't have many features that make writing code easy:

Let's write some code in TextEdit anyway. We start with the HTML doc type. Post this, we add an HTML opening and closing tag and then the head tag and inside that the title