29,99 €
In the ever-evolving landscape of web development, mastering HTML and CSS is crucial for building modern, responsive websites. This comprehensive guide equips you with the essential knowledge and skills you need to excel in web design and development.
Starting with the foundational principles of HTML and CSS, the book swiftly advances to cover more complex topics, providing a thorough understanding of these vital technologies. You’ll learn how to build websites from scratch, create intuitive user input forms, and enhance web design by integrating multimedia elements like videos, animations, and themes. Emphasizing responsive web design principles, this book teaches you how to create layouts that flawlessly adapt to different devices using media queries. You’ll also get to grips with SEO essentials to optimize website visibility and search engine rankings. A dedicated section guides you through performance optimization techniques to ensure your websites deliver a smooth and lightning-fast user experience.
By the end of this HTML and CSS book, you’ll have developed confidence in your web development skills, and you'll be well-equipped to build modern, visually appealing, and high-performing websites.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 472
Veröffentlichungsjahr: 2024
Practical HTML and CSS
Elevate your internet presence by creating modern and high-performance websites for the web
Brett Jephson
Lewis Coulson
Ana Carolina Silveira
Copyright © 2024 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.
The author acknowledges the use of cutting-edge AI, such as ChatGPT, with the sole aim of enhancing the language and clarity within the book, thereby ensuring a smooth reading experience for readers. It’s important to note that the content itself has been crafted by the author and edited by a professional publishing team.
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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.
Group Product Manager: Kaustubh Manglurkar
Publishing Product Manager: Urvi Sambhav Shah
Book Project Manager: Srinidhi Ram
Senior Content Development Editor: Feza Shaikh
Technical Editor: Simran Ali
Copy Editor: Safis Editing
Indexer: Rekha Nair
Production Designer: Aparna Bhagat
Marketing Coordinators: Nivedita Pandey
First published: November 2019
Second edition: November 2024
Production reference: 1260924
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK.
ISBN 978-1-83508-091-7
www.packtpub.com
To my daughters, Adeline and Viola, for keeping me busy, having too much fun, and making it hard to find time to write anything.
– Brett Jephson
To Rebecca, Louis, Dylan, and Mae, for all of your love and support.
– Lewis Coulson
To my sister, Angelica, who bravely raised me surrounded by books.
– Ana Carolina Silveira
Brett Jephson is a product engineer specializing in frontend engineering and design systems. He has worked in media, games, and app companies for many years, putting all the latest and greatest web technologies to use in many interesting ways while championing accessibility and good UI.
I would like to thank Kate for supporting me and doing more than her share of looking after the kids (Adeline and Viola) while I worked on this book.
Lewis Coulson is a senior frontend developer with over 10 years of commercial experience. He has worked at a range of organizations ranging from creative agencies to government departments.
I would like to thank my family who have supported me whilst writing this book: Rebecca, Louis, Dylan, and Mae.
Ana Carolina Silveira is a seasoned frontend web developer, known for her expertise in CSS and her deep understanding of user experience and behavior. As an open source enthusiast, she actively participates in community projects, sharing her knowledge and passion for web development with others.
First and foremost, I would like to thank God for granting me the knowledge needed for this project; SDG. I am also deeply grateful to my husband, Lucas, for his support and encouragement throughout the process of writing this book. A heartfelt thanks as well to my family, friends.
Akhilesh Tiwari is a software engineer with over 20 years of experience. He obtained his MTech from BITS Pilani, India. Akhilesh has developed software solutions for the world’s leading organizations, such as Merck, Novartis, BNY Mellon, Fujitsu, Cognizant, and Persistent Systems to name a few. Akhilesh now resides in New Jersey, USA, where he enjoys a fulfilling family life with his wonderful wife and two adorable children.
First of all, I would like to thank the Supreme Personality of Godhead, Krishna, for everything. I would like to thank my loving parents for their unconditional love and support. I would not have been able to do this book review without the support of my loving wife, Sanchita, and my two young ones, Osh and Radha. Last but not least, I would like to thank Packt for this opportunity and their trust.
With knowledge of HTML and CSS, you can build visually appealing, interactive websites without relying on pre-packaged website-building tools and their limitations. Practical HTML and CSS takes you on a journey, showing you how to create beautiful websites using your own content while understanding how they work and how to manage them in the long term.
The book begins by introducing HTML5 and CSS3, guiding you through the website development process with easy-to-follow steps. You’ll explore how browsers render websites, progressing to adding rich multimedia elements such as video and audio to create a more cinematic experience. You’ll also use JavaScript to add interactivity to your site, build intuitive forms to capture user data, and add slick transitions with animations. You’ll delve into mobile-first development using responsive design and media queries, ensuring your sites perform seamlessly across all devices.
Throughout, you’ll engage in hands-on projects and learn how to craft beautiful, responsive applications. Each chapter builds on the last, expanding your knowledge and equipping you with the skills needed to craft stunning, professional websites. Along the way, you’ll also learn how to optimize your sites for performance and SEO, preparing you to tackle the most in-demand technologies in the industry.
Whether you’re a beginner or looking to refine your expertise, this guide serves as a comprehensive roadmap for your journey and a trusted companion throughout your career. As you progress, you’ll find yourself returning to its pages for advice, inspiration, and best practices. With Practical HTML and CSS, you’re not just learning a set of tools—you’re building a solid foundation that will support your growth as a web developer for years to come.
The two technologies covered in this book, HTML and CSS, are available to anyone with a web browser and a text editor. This means this book is aimed at anyone who wants to put together a web page and is looking for some practical exercises to help them learn. Here’s who will benefit most from this guide:
Aspiring web developers: If you’re just starting your journey in web development, this book provides a solid foundation in HTML and CSS. You’ll gain a comprehensive understanding of these essential technologies, allowing you to build your first websites with confidence.Junior developers: For those with some experience in web development, this guide offers deeper insights into best practices and advanced techniques. It will help you enhance your skill set, improve your portfolio, and advance in your career.UI/UX designers: Understanding the structure and styling of web pages is crucial for designers. This book will enable you to better collaborate with developers by understanding how your designs are implemented using HTML and CSS.Freelancers and entrepreneurs: If you’re building or managing your own website, this guide will equip you with the knowledge to create and maintain your web presence without relying on external developers.The book is accessible to someone learning web development for the first time but it delves into a lot of subject areas and goes beyond the fundamentals of what you can do with HTML and CSS. We hope, therefore, that there is something useful for anyone in their formative years as a web developer.
Chapter 1, Introduction to HTML and CSS, provides a grounding in the fundamentals of web development. Through practical exercises, the chapter introduces you to the syntax of both HTML and CSS, looks at the relationship between HTML and CSS, and explains the roles of these technologies in rendering a web page in the browser.
Chapter 2, Structure and Layout, introduces you to the structural elements in HTML, including header, footer, and section tags. You will also learn the three main CSS layout techniques: float, flex, and grid.
Chapter 3, Text and Typography Styling, introduces you to text-based elements, such as paragraphs, headings, and lists. We will go over how to style text-based elements in web pages and let your creativity run wild.
Chapter 4, Creating and Styling Forms, introduces you to the creation of web forms, starting with the key HTML elements used in forms and then learning how to style them with CSS. Along the way, you will also learn how to style your forms with validation styling.
Chapter 5, Adding Animation to Web Pages, explores how to effectively incorporate animations into web applications using CSS. You’ll be introduced to the versatile transform property, the intricacies of z-index, the smooth transitions enabled by CSS, and the powerful @keyframes rule for creating complex animations. By the end of this chapter, you’ll have created a portfolio-worthy project that demonstrates how these techniques can be applied in various real-world scenarios.
Chapter 6, Themes, Color, and Polishing Techniques, dives into managing styles based on user preferences using CSS themes and other refining techniques. You’ll gain an understanding of color theory with HSL, and how to implement light and dark themes, utilize CSS filters, and apply effective typography. We’ll also explore how to combine these approaches to enhance and personalize the user experience, ensuring your web designs are both visually appealing and user-centric.
Chapter 7, Using CSS and HTML to Boost Performance, provides an understanding of how we can measure web performance using Core Web Vitals. Through practical exercises, it explains some simple techniques using HTML and CSS that we can use to improve the performance of a web page.
Chapter 8, Responsive Web Design and Media Queries, teaches you how to implement responsive applications using breakpoints and media queries. We’ll delve into the “mobile first” approach, ensuring that your applications are optimized for mobile devices without sacrificing performance or design quality. You’ll also learn about viewports, responsive values, and the incredibly useful Flexbox layout, equipping you to create adaptive, high-quality web applications.
Chapter 9, Ensuring Accessibility in HTML and CSS, explains some of the challenges that web pages can present to users with disabilities and provides simple techniques using HTML and CSS that we can employ to improve the experience for those users while also improving the experience for all users.
Chapter 10, SEO Essentials for Web Developers, provides an in-depth guide to understanding SEO and how to measure its performance. You’ll learn about Core Web Vitals, strategies to improve SEO metrics, and how to position your application for high visibility in search engines. This chapter focuses on mastering the tools and techniques to outsmart search algorithms, giving your web projects a competitive edge.
Chapter 11, Preprocessors and Tooling for Efficient Development, takes a step further into performance and scalability. You’ll learn how to architect and build scalable, maintainable applications using powerful build tools such as Gulp and Webpack to automate development processes. We’ll also explore preprocessors such as Less and Sass, which enhance the capabilities of CSS, making your development process more efficient and your code more manageable.
Chapter 12, Strategies for Maintaining CSS Code, focuses on CSS performance and maintainability, introducing methodologies such as BEM (which stands for Block, Element, Modifier) and tools such as Tailwind CSS. These approaches help you maintain clean, organized, and efficient CSS code, ensuring your projects remain scalable and easy to manage as they grow.
Chapter 13, The Future of HTML and CSS – Advancements and Trends, provides a look at the latest advancements and emerging trends in HTML and CSS. This chapter serves as a guide to the future of web development, offering insights into the technologies and features that will shape tomorrow’s web. As the final chapter of this book, this chapter opens the door to the cutting-edge resources and innovations you can start exploring today to stay ahead in the rapidly evolving world of web development.
Software/hardware covered in the book
Operating system requirements
HTML5
Any OS with a web browser
CSS
Any OS with a web browser
Chrome Dev Tools
Any OS with Chrome web browser
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Practical-HTML-and-CSS-Second-Edition. If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “To do this, create a folder named styles inside the project’s folder.”
A block of code is set as follows:
/* Layout styles */ .container { max-width: 1200px; margin: 0 auto; padding: 0 20px; } .grid { display: flex; flex-wrap: wrap; }When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" > <link rel="stylesheet" href="styles/base.css"> <link rel="stylesheet" href="styles/layout.css"> <link rel="stylesheet" href="styles/module.css"> <link rel="stylesheet" href="styles/state.css"> <link rel="stylesheet" href="styles/theme.css"> </head>Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “As this is an example taken from the Packt website, you will notice that it contains items such as the company logo, search bar, and the Sign In button.”
Tips or important notes
Appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Once you’ve readPractical HTML and CSS, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?
Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link belowhttps://packt.link/free-ebook/978-1-83508-091-7
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directlyIn this part, we’ll explore the fundamental principles of creating web pages. We’ll start by learning about the fundamental concepts behind how web pages work. Next, we’ll explore techniques for structuring our web pages and styling them with custom layouts. Finally, we’ll delve into text and typography, paying close attention to styling concerns.
This section contains the following chapters:
Chapter 1, Introduction to HTML and CSSChapter 2, Structure and LayoutChapter 3, Text and Typography StylingWhether you want to build a web page to advertise your business, blog about a hobby, or maintain an online community, HyperText Markup Language (HTML) and Cascading Style Sheets (CSS) are the foundations upon which you will build.
HTML and CSS work together but each has a different role in making a web page. A web page is made up of lots of different types of content (text, images, links, video, and audio). HTML structures that content and CSS styles it. Together, they tell the browser how and what to render.
These two technologies are simple to get started with and provide enough power and expressivity that they let you get your ideas out there to the vast audience on the web.
Navigate to a website and what you see is the rendered output of content marked up with HTML and styled with CSS. As a browser user, you have access to the source code of a web page. In Chrome, for example, you can view a page’s source code by pressing the keys Ctrl + U on a PC or command + option + U on a Mac. Alternatively, you can right-click with a mouse and choose View Page Source. Try it yourself. As an example, the following two figures show what the Packt website’s Web Development portal looks like when rendered in the browser and as source code respectively.
Figure 1.1: The Packt Publishing site’s Web Development portal
Figure 1.2: The HTML source code of the Packt site
By learning to write the HTML and CSS that make up the source code, we can create our own modern website.
In this chapter, we will develop an understanding of how a web page renders by following the process from initial request to completed composition. We will learn how to build a simple web page using HTML and then we will learn how to style that page with CSS.
The following topics will be covered in the chapter:
How a web page rendersUnderstanding HTMLUnderstanding CSSBy the end of this chapter, you will have been introduced to two of the core technologies of the web – HTML and CSS – and you will understand their roles in creating websites. You will have created a page from scratch and you will have used selectors to target parts of that web page for styling.
The code files for this chapter can be found at https://packt.link/808iP.
When we navigate to a web page in our favorite browser, what happens? How do HTML and CSS translate to the page we see in front of us? In other words, how does a web page render?
The following figure shows a flowchart of the process, which is then further explained:
Figure 1.3: Flow chart of the web page render process
To summarize the process:
The user starts by navigating to a URL, possibly via a hyperlink or by typing the URL into the address bar of their browser.The browser will make a GET request to the disk or a network. It will read the raw bytes from that location and convert them to characters (based on character encoding, such as UTF-8).The browser then parses these characters according to the HTML standard to find the tokens that are familiar as HTML elements, such as <html>and <body>.Another parse is then made to take these tokens and construct objects with their properties based on the rules appropriate to that token. At this point, the objects are defined.Finally, the browser can define the relationships between these objects and construct the HTML DOM (Document Object Model) for the web page.At this point, we have a DOM but not a rendered web page. The next task is to construct the CSSOM (CSS Object Model). Again, the browser will load any style sheet resources it needs to, which were found while parsing the document. It will then construct the styles associated with nodes in the tree structure, which gives us the CSSOM.With the information gathered in the DOM and the CSSOM, the browser can create a render tree. The render tree is constructed by combining information from the CSSOM and the HTML DOM. Nodes in the HTML DOM that will not be rendered (for instance, those with the display: none; style) are excluded from the render tree. Those that are rendered are enriched with their computed style rules.Now the browser has all the information it needs, it can begin to calculate the positions of elements in the rendered viewport. This is called the layout stage. The browser lays elements out based on their size and position within the browser viewport. This stage is often also called reflow. It means the browser must recalculate the positions of elements in the viewport when elements are added to or removed from the page or when the viewport size is changed.Finally, the browser will rasterize or paint each element on the page, depending on their styles, shadows, and filters to render the page the user will see.In this section, we have given a brief and simplified summary of the rendering of a web page. Think about how many resources might be loaded on a relatively complicated website and with JavaScript running events and we can see that much of this process happens frequently and not in such a linear manner. We can start to see the complexities of what a browser is doing when it renders your web page.
In the next section, we will start to look at how we create a web page by learning about the syntax of HTML, which helps us structure and contextualize our content. We will learn about the syntax of HTML and the elements we can use, and we will apply this knowledge to create a simple web page.
HTML is a markup language used to describe the structure of a web page.
Consider a snippet of text with no markup:
HTML HyperText Markup Language (HTML) is a markup language used to describe the structure of a web page. We can use it to differentiate such content as headings lists links images Want to https://www.packtpub.com/web-development Learn more about web development.The preceding snippet of text makes some sense. It may also raise some questions. Why does the snippet begin with the word HTML? Why is there a URL in the middle of a sentence? Is this one paragraph?
Using HTML, we can differentiate several bits of content to give them greater meaning. We could mark the word HTML as a heading, <h1>HTML</h1>, or we could mark a link to another web page using <a href="https://www.packtpub.com/web-development">Learn more about web development</a>.
There have been several versions of HTML since its first release in 1993 at the beginning of the web. Throughout the rest of this chapter, and indeed the rest of this book, we will be looking at and working with the current version of the HTML language, HTML5, which is the 5th major version of HTML. When we use the term HTML, we will refer specifically to HTML5 and if we need to talk about a different version we will do so explicitly (e.g., HTML 4.01).
In the next section, we will look at the syntax of HTML in more detail.
The syntax of HTML is made up of tags (with angle brackets, <>) and attributes. HTML provides a set of tags that can be used to mark the beginning and end of a bit of content. The opening tag, closing tag, and all content within those bounds represent an HTML element. The following figures show the HTML element representation without and with tag attributes respectively:
Figure 1.4: HTML element representation without tag attributes
Figure 1.5: HTML element representation with tag attributes
A tag has a name (for instance, p, img, or h1), and that name combined with attributes will describe how the browser should handle the content. Many tags have a start and end tag with some content in between, but some tags don’t expect any content, and these can be self-closing.
An opening tag can have any number of attributes associated with it. These are modifiers of the element. An attribute is a name-value pair. For example, href="https://www.packtpub.com/web-development" is an attribute with the name of href and the value of https://www.packtpub.com/web-development. An href attribute represents a hypertext reference or a URL, and when this attribute is added to an anchor element, <a>, it creates a hyperlink that the user can click in the browser to navigate to that URL.
To provide information within an HTML document to be ignored by the parser and not shown to the end user, you can add comments. These are useful for notes and documentation to aid anyone who might read or amend the source of the HTML document. A comment begins with <!-- and ends with -->. Comments, in HTML, can be single or multiline. The following are some examples:
<!-- Comment on a single line --> <!-- This comment is over multiple lines. Comments can be used to inform and for detailed documentation. -->You can use comments to provide helpful hints to other developers working on the web page but they will be ignored by the browser when parsing the page.
Let’s see what the previous snippet of text content looks like when it is given some meaning with HTML:
<h1>HTML</h1> <p> HyperText Markup Language (HTML) is a markup language used to describe the structure of a web page. </p> <p> We can use it to differentiate such content as: </p> <ul> <li>headings</li> <li>lists</li> <li>links</li> <li>images</li> </ul> <p> Want to <a href="https://www.packtpub.com/web- development">learn more about web development?</a> </p>If we were to look at this HTML code rendered in a browser, it would look like the following figure:
Figure 1.6: HTML rendered in the Google Chrome web browser
The first line shows the HTML text content with a start tag, <h1>, and an end tag, </h1>. This tells the browser to treat the text content as an h1heading element.
The next line of our code snippet has a <p> start tag, which means the content until the corresponding end tag, </p> (on the last line), will be treated as a paragraph element. We then have another paragraph and then an unordered list element that starts with the <ul> start tag and ends with the </ul> end tag. The unordered list has four child elements, which are all list item elements (from the <li> start tag to the </li>end tag).
The last element in the example is another paragraph element, which combines text content and an anchor element. The anchor element, starting from the <a> start tag and ending at the </a> end tag, has the learn more about web development? text content and an href attribute. The href attribute turns the anchor element into a hyperlink, which a user can click to navigate to the URL given as the value of the href attribute.
As with our example, the contents of a paragraph element might be text but can also be other HTML elements, such as an anchor tag, <a>. The relationship between the anchor and paragraph elements is a parent-child relationship.
HTML5 defines more than a hundred tags that we can use to mark up parts of an HTML document. These include the following:
The document root element: <html>Metadata elements: <base>, <head>, <link>, <meta>, <style>, and <title>Content sectioning elements: <address>, <article>, <aside>, <body>, <footer>, <header>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <main>, <nav>, and <section>Block text elements: <blockquote>, <dd>, <details>, <dialog>, <div>, <dl>, <dt>, <figcaption>, <figure>, <hr>, <li>, <menu>, <ol>, <p>, <pre>, <summary>, and <ul>Inline text elements: <a>, <abbr>, <b>, <bdi>, <bdo>, <br>, <cite> , <code>, <data>, <dfn>, <em>, <i>, <kbd>, <mark>, <q>, <rp>, <rt>, <ruby>, <s>, <samp>, <small>, <span>, <strong>, <sub>, <sup>, <del>, <ins>, <time>, <u>, <var>, and <wbr>Media elements: <area>, <audio>, <img>, <canvas>, <map>, <track>, <video>, <embed>, <iframe>, <object>, <picture>, <portal>, <source>, <svg>, and <math>Scripting elements: <noscript>and <script>Table elements: <caption>, <col>, <colgroup>, <table>, <tbody>, <td>, <tfoot>, <th>, <thead>, and <tr>Form elements: <button>, <datalist>, <fieldset>, <form>, <input>, <label>, <legend>, <meter>, <optgroup>, <option>, <output>, <progress>, <select>, and <textarea>Web component elements: <slot>and <template>We don’t have to know all of these tags to use HTML well; some fulfill more common use cases than others. Each has a distinct purpose and provides a different semantic meaning and throughout this book, we will go into some detail about how to use these elements.
When starting with HTML, it can be easy to find the number and variety of elements overwhelming. It may be helpful to think about HTML in terms of content types.
The following table has a description and example of the different content types that can describe an element:
Type
Description
Example
Metadata
Content hosted in the head of an HTML document. Doesn’t appear in the web page directly but is used to describe a web page and its relationship to other external resources.
<meta name="viewport" content="width=device-width,initial-scale=1.0">
Flow
Text and all elements that can appear as content in the body of an HTML document.
<body>
<h1>Heading</h1>
<p>Some content…</p>
</body>
Sectioning
Used to structure the content of a web page and to help with layout. Elements in this category are described in Chapter 2, Structure and Layout.
<aside></aside>
<article class="blog-post">
<section></section>
</article>
Phrasing
Elements such as those used for marking up content within a paragraph element.Chapter 3, Text and Typography, will be largely concerned with this content type.
<p><em>Emphasized text</em> and some normal text.</p>
Heading
Elements used to define the headings of a section of an HTML document. The h1-6 elements represent headings with h1 having the highest ranking.
<h1>Main Heading</h1>
<h2>Subheading</h2>
Embedded
Embedded content includes media, such as video, audio, and images.
<img src="media/kitten.png" alt="A cute kitten">
Interactive
Elements that a user can interact with, which include media elements with controls, form inputs, buttons, and links.
<input type="password" name="password" required>
Table 1.1: Different content types
Let’s run through an example of how an element can fit into these category types using the <img> element.
If we want to embed an image in our web page, the simplest way is to use the img element. If we want to create an img element, an example of the code looks like this: <img src="media/kitten.png" alt="A cute kitten">.
We set the src attribute on the img element to an image URL; this is the source of the image that will be embedded in the web page.
Unless your image has no value other than as a decoration, it is a very good idea to include an alt attribute. The alt attribute provides an alternative description of the image as text, which can then be used by screen readers if an image does not load, or in a non-graphical browser.
Note
A screen reader is a software application that allows people who are visually impaired or blind to access and interact with a computer. The screen reader allows a user to navigate a web page with a keyboard and will output the content as speech. We will look further at accessibility in Chapter 9.
An img element is a form of embedded content because it embeds an image in an HTML document. It can appear in the body of an HTML document as the child element of the body element, so it would be categorized as flow content.
An image can be included as content in a paragraph, so it is a type of phrasing content. For example, we could have inline images appear in the flow of a paragraph:
<p> Kittens are everywhere on the internet. The best thing about kittens is that they are cute. Look here's a kitten now: <img src="media/kitten.jpg" alt="A cute kitten">. See, cute isn't it? </p>This code would render the following figure, with the image embedded in the paragraph and the rest of the text flowing around it:
Figure 1.7: Image with text flowing around it
In certain circumstances, an img element is a type of interactive content. For this to be the case, the image must have a usemap attribute. The usemap attribute allows you to specify an image map, which defines areas of an image that are treated as hyperlinks. This makes the image interactive.
An img element does not act as metadata and it does not provide a sectioning structure to an HTML document. Nor is it a heading.
Elements can appear in more than one category and there is some overlap between the relationships of the categories. Some of these elements are very common and are used often, but some of these elements have very specific purposes and you may never come across a use case for them.
The content types can be useful for understanding how elements work together and which elements are valid in where. For further reference, we can see where each available element is categorized in the W3C’s documentation on HTML5: https://html.spec.whatwg.org/multipage/dom.html#kinds-of-content.
A web page is made up of an HTML document. The document represents a hierarchical tree structure similar to a family tree. Starting from a root element, the relationship between an element and its contents can be seen as that of a parent element and a child element. An element that is at the same level of the hierarchy as another element is a sibling to that element. We can describe elements within a branch of the tree as ancestorsand descendants.
This structure can be represented as a tree diagram to get a better idea of the relationship between elements.
Take, for example, this simple HTML document:
<html> <head> <title>HTML Document structure</title> </head> <body> <div> <h1>Heading</h1> <p>First paragraph of text.</p> <p>Second paragraph of text.</p> </div> </body> </html>Here, the root is an html element. It has two children: a head element (containing a title) and a body element containing some more content. It can be represented as a tree diagram as follows:
Figure 1.8: A representation of the HTML document as a tree diagram
In the browser, this code would render the following web page:
Figure 1.9: HTML rendered in the Google Chrome web browser
The <html> element is the parent of both the <head> and <body>, which (as children of the same parent) are siblings. <body> has one child, a <div> tag, and that has three children: an <h1> element and two <p> elements. The <h1> element is a descendant of <body> but not of <head>.
Understanding this structure will become more important when we look at CSS selectors and how we target parts of the HTML document later in this chapter.
An HTML5 document normally starts with a doctype declaration and has a root html element with two children – the head element and the body element.
The doctype declaration tells the browser it is dealing with an HTML5 document. The doctype is <!DOCTYPE html> and appears as the first line of the document. It is recommended to always add a doctype to make sure your HTML document renders as expected.
Note
The doctype declaration is not case sensitive, so variations such as <!doctype html> and <!DOCTYPE HTML> are equally valid.
One of the nice things about HTML5 is that it simplifies doctype declaration. Before HTML5, there were two commonly used variations of web markup – HTML4 and XHTML1 – and they both had strict, transitional, and frameset versions of their doctype declarations. For example, the HTML 4 strict declaration looked like this: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">.
After the doctype, we have the html element, which is the root of the HTML document.
It is strongly recommended that you add a lang attribute to your html element to allow the browser, screen readers, and other technologies, such as translation tools, to better understand the text content of your web page.
The two children of the html element are as follows:
The head element, which includes the title and metadata providing information about assets to load and how web crawlers and search engines should handle the page.The body element, which mostly represents the content rendered for a human browser user to consume. This includes articles, images, and navigation.In code, the structure we have described looks like this:
<!doctype html> <html lang="en"> <head><title>Page Title</title></head> <body></body> </html>This code would result in a blank web page with no content or metadata.
The head is home to most machine-read information in an HTML document. The browser, screen readers, and web crawlers can get a lot of information from metadata and handle the web page differently depending on that information.
The following elements are considered metadata content:
base: This lets you set a base URLlink: This determines the relationship between a page and a resource (such as an external style sheet)meta: This a catch-all for metadatatitle: This is the name of your web page as it appears in the browser tab and search results and is announced by screen readersThe meta element can represent many different types of metadata, including some used by social networks to represent a web page.Some common usages include the following:
Setting character encoding for a page – <meta charset="utf-8">Setting the viewport for a browser on a mobile device – <meta name="viewport" content="width=device-width, initial-scale=1">These elements give web developers ways to tell a browser how to handle the HTML document and how it relates to its environment. We can describe our web page for other interested parties (such as search engines and web crawlers) using metadata.
In our first example, we will create a very simple web page. This will help us to understand the structure of an HTML document and where we put different types of content.
In this exercise, we will create our first web page. This will be the minimal foundation upon which future chapters can build.
Note
The complete code for this exercise can be found at https://packt.link/SduQx.
The steps are as follows:
To start, we want to create a new folder, chapter_1, and then open that folder in Visual Studio Code (File | Open Folder…).Next, we will create a new plain text file and save it as index.html.In index.html, we start by adding the doctype declaration for HTML5: <!DOCTYPE html>Next, we add an HTML tag (the root element of the HTML document): <html lang="en"> </html>In between the opening and closing tags of the html element, we add a head tag. This is where we can put metadata content. For now, the head tag will contain a title: <head> <title>HTML and CSS</title> </head>Below the head tag and above the closing html tag, we can then add a body tag. This is where we will put the majority of our content. For now, we will render a heading and a paragraph: <body> <h1>HTML and CSS</h1> <p> How to create a modern, responsive website with HTML and CSS </p> </body>The result of this exercise should look like the following figure when opened in a browser:
Figure 1.10: The web page as displayed in the Chrome web browser
We’ve been tasked with creating a website for an online on-demand film store called Films On Demand. We don’t have designs yet but want to set up a web page boilerplate that we can use for all the pages on the site.
We will use comments as placeholders to know what needs to change for each page that is built on top of the boilerplate template. For visible content in the body element, we will use lorem ipsum to get an idea of how content will flow.
The steps are as follows:
Create a file named template.html.We want the page to be a valid HTML5 document. So, we will need to add:The correct doctype definition.Elements to structure the document: The html element, the head element, and the body element.A title element that combines the Films on Demand brand with some specifics about the current page.Metadata to describe the site: We’ll set this to Buy films from our great selection. Watch movies on demand.Metadata for the page character set and a viewport tag to help make the site render better on mobile browsers.We want to add placeholders for a heading (an h1 element) for the page, which we will populate with lorem ipsum, and a paragraph for the content flow, which we will also populate with the following lorem ipsum text:"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam quis scelerisque mauris. Curabitur aliquam ligula in erat placerat finibus. Mauris leo neque, malesuada et augue at, consectetur rhoncus libero. Suspendisse vitae dictum dolor. Vestibulum hendrerit iaculis ipsum, ac ornare ligula. Vestibulum efficitur mattis urna vitae ultrices. Nunc condimentum blandit tellus ut mattis. Morbi eget gravida leo. Mauris ornare lorem a mattis ultricies. Nullam convallis tincidunt nunc, eget rhoncus nulla tincidunt sed. Nulla consequat tellus lectus, in porta nulla facilisis eu. Donec bibendum nisi felis, sit amet cursus nisl suscipit ut. Pellentesque bibendum id libero at cursus. Donec ac viverra tellus. Proin sed dolor quis justo convallis auctor sit amet nec orci. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus."
Note
The solution to this activity can be found at https://packt.link/WbEPx
In this section, we’ve looked at HTML, the markup language that structures and gives context to the content of a web page. We have looked at the syntax of HTML, created our first web page, and learned about the structure of an HTML document. When we’ve looked at our web page in a browser, it has been rendered with the default styling provided by the browser. In the next section, we will look at how we can customize the styling of our web page using CSS. We will learn how to add styles, how to specify what parts of a page they apply to, and some of the properties we can style.
CSS is a style sheet language used to describe the presentation of a web page.
The language is designed to separate concerns. It allows the design, layout, and presentation of a web page to be defined separately from content semantics and structure. This separation keeps source code readable and lets a designer update styles separately from a developer who might create the page structure or a web editor who is changing content on a page.
A set of CSS rules in a style sheet determines how an HTML document is displayed to the user. It can determine whether elements in the document are rendered, how they are laid out on the web page, and their aesthetic appearance.
In the next section, we will look at the syntax of CSS.
A CSS declaration is made of two parts: a property and a value. The property is the name for some aspect of style you want to change; the value is what you want to set it to.
Here is an example of a CSS declaration:
color: red;The property is color and the value is red. In CSS, color is the property name for the foreground color value of an element. That essentially means the color of the text and any text decoration (such as underline or strikethrough). It also sets a currentcolor value.
For this declaration to have any effect on an HTML document, it must be applied to one or more elements in the document. We do this with a selector. For example, you can select all the <p> elements in a web page with the p selector. So, if you wanted to make the color of all text in all paragraph elements red, you would use the following CSS ruleset:
p { color: red; }The result of this CSS ruleset applied to an HTML document can be seen in the following figure:
Figure 1.11: Result of a CSS rule applied to <p> elements in HTML
The curly braces represent a declaration block and that means more than one CSS declaration can be added to this block. If you wanted to make the text in all paragraph elements red, bold, and underlined, you could do that with the following ruleset:
p { color: red; font-weight: bold; text-decoration: underline; }The result of this CSS ruleset applied to an HTML document can be seen in the following figure:
Figure 1.12: Several CSS declarations applied to <p> elements in HTML
Multiple selectors can share a CSS ruleset. We can target these with a comma-separated list. For example, to apply the color red to p elements, h1 elements, and h2 elements, we could use the following ruleset:
p, h1, h2 { color: red; }Multiple CSS rulesets form a style sheet. The order of these CSS rules in a style sheet is very important as this is partly how the cascade or specificity of a rule is determined. A more specific rule will be ranked higher than a less specific rule and a higher-ranked rule will be the style shown to the end user. We will look at cascade and specificity later in this chapter:
Figure 1.13: A CSS ruleset explained
There are several ways we can add CSS to a web page:
Via an element’s style attribute (inline styles)With a style element in the head or body of the HTML documentBy linking an external style sheet to the HTML document with a link elementEach of these methods has pros and cons. Inline styles apply only to that element and have high specificity but we can’t access pseudo-classes and pseudo-elements this way. They can make maintenance and updates time-consuming. Both the link and style elements provide greater separation of concerns, keeping the CSS separated from the HTML, which can be beneficial for organization and maintaining a clean code base.We will try out each of these methods in the following exercises.
In this exercise, we will add styles to a web page using the link element, the style element, and the style attribute.
Note
The complete code for this exercise can be found at https://packt.link/yspKi.
Here are the steps:
Let’s start with a simple web page: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Adding styles</title> </head> <body> <h1>Adding styles</h1> <p>First paragraph</p> <p>Second paragraph</p> </body> </html>Before adding any styles, the web page will look like this:
Figure 1.14: The unstyled web page
We’ll make the text more readable by creating an external CSS file that we can link to our web page. To do that we save a file named styles.css in the chapter_1 folder.Add the following CSS to styles.css: body { font-family: Arial, Helvetica, sans-serif; font-size: 18px; padding: 0; margin: 1rem; } h1 { margin: 0; margin-bottom: 1rem; } p { margin: 0; margin-bottom: .5rem; }Next, we need to link the file to the web page. We do this with a link element added to the tag <head> of the web page beneath the tag <title>: <link href="styles.css" rel="stylesheet">Using a style element, added just before the end tag of body, we can set a different color for all paragraph elements: <style> p { color: red; } </style>The result will look similar to the following figure, with all paragraphs colored red:
Figure 1.15: The web page with styles applied
Finally, we will give the first paragraph a different style using an inline style attribute, setting the color to blue and adding a line-through text decoration as follows: <p style="color: blue; text-decoration: line-through"> First paragraph </p>The result will be like the one shown in the following figure:
Figure 1.16: The web page with inline style applied
Note
Inline styles have precedence over CSS rules applied in a style element. We will look at specificity and the rules of the cascade later in this chapter.
We’ve looked at how we can add styles to a web page. In the next section, we will look at the different CSS selectors we can use to apply our styles to parts of the HTML document.
To target elements in the HTML document with CSS, we use selectors. There are a lot of options available to help you select a wide range of elements or very specific elements in certain states.
Selectors are a powerful tool and we will look at them in some detail as the different options available can help with both web page performance and making your CSS more maintainable.
For example, you can use a selector to target the first letter of a heading, like you might expect to see in a medieval book:
h1::first-letter { font-size: 5rem; }Or, you could use a selector to invert the colors of every odd paragraph in an article:
p { color: white; background-color: black; } p:nth-of-type(odd) { color: black; background-color: white; }We will explore a variety of the options available to us when creating selectors.
Three commonly used selectors are as follows:
Element type: For example, to select all p elements in an HTML document, we use the p selector in a CSS ruleset. Other examples are h1, ul, and div.A class attribute: The class selector starts with a dot. For example, given the <h1 class="heading">Heading</h1> HTML snippet, you could target that element with the .heading selector. Other examples are .postand .sub-heading.An ID attribute: The id selector starts with a hash symbol. For example, given the <div id="login"> <!-- login content --> </div> HTML snippet, you could target this element with the #login selector. Other examples include #page-footerand #site-logo.To select all elements throughout an HTML document, you can use the universal selector, which is the asterisk symbol (*). Here is an example snippet of CSS that is often added to web pages; a value is set on the html element and then inherited by all descendant elements:
html { box-sizing: border-box; } *, *:before, *:after { box-sizing: inherit; }Using the inherit