As a Python developer, you can’t avoid HTML and CSS if you want to create websites.
Almost every webpage you visit online uses HTML syntax for page structure.
HTML may be styled using CSS to create a more aesthetically pleasing webpage.
Learning HTML and CSS is a great first step if you want to learn Python for web development. Frameworks like Django and Flask are built on top of these languages.
But even if you’re just starting out with Python, you can make simple webpages using HTML and CSS to show off to your friends. This guide will teach you how to:
-
Structure a basic
HTML
file -
View and inspect HTML in your
browser
-
Insert
images
and page
links
-
Style a website with
CSS
-
Format HTML with
accessibility
in mind -
Use Python to
write and parse
HTML code
You’ll receive a step-by-step guide on getting started with HTML and CSS.
In this guide, you’ll learn how to use CSS to style three pages of a website:
The HTML page you create for this project will serve as a starting point for any future websites you design.
The available source code might be useful in your future endeavors.
It’s downloadable from this link:
The last section of this tutorial provides some suggestions on where to go from here, after you’ve mastered the fundamentals of HTML and CSS.
tutorial.
Create Your First HTML File
Consider a recent webpage you enjoyed.
Maybe you caught up on the latest headlines, had a little social media fun, or watched a funny video with your pals.
The first line of every website’s source code should always be an html> tag, regardless of the site’s purpose.
HyperText Markup Language is the acronym for HTML.
You may recognize Tim Berners-name Lee’s as the man who designed the World Wide Web and HTML.
The “hypertext” in “hypertext markup language” refers to establishing links between individual HTML documents.
Hyperlinks make it possible to quickly navigate the Internet.
Markup is used to organize text inside a document.
Markup, in contrast to formatting, determines the significance of material rather than its presentation.
The purpose and function of various HTML elements will be covered here.
If you take the time to write semantic HTML code, more people will be able to read and understand your pages.
After all, you want to make sure that your material can be accessed by everyone, whether they’re using a browser or a screen reader.
There is an established norm for using each HTML element.
Web Hypertext Application Technology Working Group (WHATWG) currently defines HTML standards.
When it comes to HTML, the WHATWG fills a function analogous to that of the Python Steering Council.
The majority of websites (about 95%) are written in HTML, therefore you’ll have to learn it if you want to perform any web development in Python.
The first step in this tutorial is to create your own HTML file.
Your HTML code will be more legible by both humans and web browsers after you’ve mastered the techniques covered here.
humans.
The HTML Document
Here, you’ll learn how to make your first HTML document.
The HTML document will have the standard format used by most websites.
Start by creating a file with some content and naming it index.html.
text:
1<!-- index.html -->
2
3Am I HTML already?
The index.html file is the default starting point for most websites.
If you’re familiar with Python, you can compare the index.html file to the main.py or app.py file in a typical Python project. If your server is not set otherwise, when you go to the root URL, the server will attempt to load the index.html file. That’s why it’s open for business
Just entering https://www.example.com/ instead of the entire
URL format: https://www.example.com/index.html.
Index.html now simply contains the text “Am I HTML already?” string.
Apart for the HTML comment on line 1, you haven’t contributed any actual HTML syntax.
The browser will not display the content of HTML comments in the same way that the Python interpreter will not execute Python code comments.
However, please access index.html:
The content appears in your browser without any problems.
The browser seems capable of reading an HTML file, using just the filename extension as a guide.
That’s useful information, but it’s important to note that there are negative consequences to this pattern of conduct.
Web browsers will attempt to display HTML files at all times.
even if your content uses invalid HTML syntax.
Similar to how Python throws a SyntaxError when you attempt to execute erroneous code, the browser sometimes throws an error of its own.
The result might be problems for your site’s users if you deploy faulty code without realizing it. Please take note that you may submit your HTML file to in order to check the HTML code that you have written.
A Markup Language Checker from the W3C. This
A linting tool is a program that checks for and highlights bugs in your code.
Modify index.html with the code to make a basic, valid HTML page.
below:
1<!-- index.html -->
2
3<!DOCTYPE html>
4<html lang="en">
5<head>
6 <meta charset="utf-8">
7 <title>Am I HTML already?</title>
8</head>
9</html>
This is the bare minimum that nevertheless produces a valid HTML page.
Technically, the lang property in line 4 might be removed entirely.
But, you should indicate the language of your document’s natural content by using the proper language subtag. Please take note that the en language tag will be used only for English throughout this lesson.
To learn more, go to
database of all other language tags maintained by the official language taggers.
The language property facilitates the use of translation tools with your website, which in turn increases accessibility.
In particular, screen readers depend on an HTML document’s language declaration to choose the appropriate language mode while synthesizing the information.
Each HTML page you create will, at its core, look quite similar to the one seen above.
Yet you’re missing an essential piece of HTML code.
Just edit index.html by inserting body> after head>
:
1<!-- index.html -->
2
3<!DOCTYPE html>
4<html lang="en">
5<head>
6 <meta charset="utf-8">
7 <title>Am I HTML already?</title>
8</head>
9<body>
10Yes,<br>I am!
11</body>
12</html>
It is essential for an HTML file to include a doctype declaration at the very beginning.
This guide will teach you how to use!
The DOCTYPE html> tag informs the browser that the file includes HTML5 code and that the page should be shown in the default view mode.
Quirks mode is more compatible with older practices and browsers, and is used by browsers if they detect an out-of-date, incomplete, or absent doctype at the beginning of the page. (
(See Notes.)
An opening html> element follows the doctype declaration.
The matching /html> tag may be found on line 12.
The basic structure of an HTML element consists of an opening tag, the element’s content, and a closing tag.
Elements like the title may even be on the same line as their respective tags.
Certain components, like the meta> element on line 6, don’t have content since they lack a closing tag.
These nonexistent building blocks are known as void elements.
They do not need characteristics to function and may exist on their own. A line break is created by the br> tag on line 10.
Tags in HTML are denoted by a pair of angle brackets, which begin with a and end with a >.
The HTML element’s intended use is often indicated by the tag name inside the angle brackets.
The title> tag on line 7 is a nice illustration of this; the text it contains determines the page’s title.
The bulk of your writing will be found in the body> section.
The body> section of an HTML page is the portion of the code that displays in the browser.
Line 10 uses the truncated tag name br> for the line break element.
Check out Mozilla’s HTML elements reference to learn more about HTML tag names.
After you’re comfortable with the HTML document’s structure, you may preview your site by refreshing index.html in your browser:
Fantastic, your first real website is now live!
There’s a strong possibility you’ll use the framework you just created for your next web development project.
Click the link below to get the HTML boilerplate code and use it in the future to get a head start:
The following part will focus on enhancing the foundation you’ve already established.
You will use content and structure to discover why HTML is referred regarded as a markup language.
website.
Whitespace and Text Formatting
Thus yet, just your website’s skeleton has been marked up in your HTML page.
It’s time to go deeper and start putting together some substantial stuff.
Insert the following into the body> section of index.html to give yourself something to work with.
:
1<!-- index.html -->
2
3<!DOCTYPE html>
4<html lang="en">
5<head>
6 <meta charset="utf-8">
7 <title>Am I HTML already?</title>
8</head>
9<body>
10Hello, World Wide Web!
11This is my first website.
12
13About me
14
15I'm a Python programmer and a bug collector.
16
17Random facts
18
19I don't just like emoji,
20I love emoji!
21
22My most-used emoji are:
23 1. lady_beetle
24 2. snake
25 3. thumbs_up
26
27Links
28
29My favorite websites are:
30 * realpython.com
31 * python.org
32 * pypi.org
33</body>
34</html>
It seems that your browser did not identify any whitespace on this page.
You may have broken up your content over numerous lines within body>, but the browser will render it as a single long line.
You, the Python developer, are well aware of the importance of whitespace in creating readable Python code.
Python’s execution of your code may be affected by how you choose to indent your lines.
Browsers automatically reduce nested spaces, line breaks, and indentation to a single space.
Providing additional information to the browser is necessary if you want to style your content differently.
You may now organize index.html by inserting HTML elements into
content:
1<!-- index.html -->
2
3<!DOCTYPE html>
4<html lang="en">
5<head>
6 <meta charset="utf-8">
7 <title>Am I HTML already?</title>
8</head>
9<body>
10<h1>Hello, World Wide Web!</h1>
11<p>This is my first website.</p>
12
13<h2>About me</h2>
14<p>I'm a Python programmer and a bug collector.</p>
15
16<h3>Random facts</h3>
17<p>I don't just <em>like</em> emoji,<br>
18I <strong>love</strong> emoji!</p>
19<p>My most-used emoji are:</p>
20<ol>
21 <li>lady_beetle</li>
22 <li>snake</li>
23 <li>thumbs_up</li>
24</ol>
25
26<h2>Links</h2>
27<p>My favorite websites are:</p>
28<ul>
29 <li>realpython.com</li>
30 <li>python.org</li>
31 <li>pypi.org</li>
32</ul>
33</body>
34</html>
Putting your text within HTML blocks tells the browser more about what you want it to do with the text.
To begin, examine the HTML components that enclose more substantial
text:
Line | HTML Element | Description |
---|---|---|
10 |
|
Main headline of your website |
11 |
|
Paragraph, to structure text and related content |
13 |
|
Second-level headline, nested below
|
16 |
|
Third-level headline, nested below
|
20 |
|
Ordered list, typically rendered as a numbered list |
28 |
|
Unordered list, typically rendered with bullets (
) |
Six levels of nesting are allowed for headline components.
Although there is often just one h1> element, several h2> through h6> tags may be included.
Screen reader compatibility relies heavily on the headline parts of your HTML text.
It’s common for readers to scan headlines in order to quickly find what they’re looking for.
If you want your HTML to be legitimate and accessible, you can’t afford to miss the headline level.
The headline tags function similarly to elevators, granting access to many levels of a structure.
There are a number of ways to leave a floor.
But keep in mind that you can’t construct the second story without the first.
That is to say, you can’t have a h3 element on your website until you’ve already defined a h2 element.
The content of several of the HTML elements you used above is limited to text.
The content of others is structured using extra HTML elements.
further:
Line | HTML Element | Description |
---|---|---|
17 |
|
Emphasizes content |
18 |
|
Indicates important content |
21 |
|
List item, must be contained in a list element |
There is purpose behind every HTML element.
That’s why it’s crucial to choose the right markup for certain sections of text.
When you apply the appropriate semantics, your material may be understood by a wider audience.
That everyone can use your website, you do:
The Web is built from the ground up to be accessible to everyone, regardless of their operating system, browser, language, location, or physical or mental capabilities. When this objective is met, persons with a wide variety of sensory, motor, perceptual, and cognitive abilities may participate fully in the online world. (
(See Notes.)
There are several HTML components that are easy to understand.
Use the p> tag to create paragraphs.
Some of the other parts are more difficult to understand:
The default HTML style in your browser may also make a good impression by applying unique styling to each element.
Markup is a way to give your website’s information more context.
Understanding your content depends on your ability to write HTML with proper semantics.
It’s not only the browser that benefits from using correct semantics in your HTML text. If your material is consumed by people using text-to-speech software, the produced HTML page will be available to them as well.
HTML5 Doctor is an excellent guide for anyone interested in expanding their knowledge of current HTML standards.
Check out Google’s accessibility training to learn more about inclusive web design.
.
Links, Images, and Tables
The ability to quickly navigate between different websites is fundamental to the online experience.
Hyperlinks, more generally referred to as links, are the identifiers for these sources.
Without links, websites would be isolated, inaccessible except for their unique addresses.
In addition, you wouldn’t be able to move about a website’s various pages if there weren’t any connections leading to and from them.
Create a navigation menu in your HTML code to link your existing HTML pages.
code:
<!-- index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Am I HTML already?</title>
</head>
<body>
<nav>
<a href="emoji.html">Emoji</a>
</nav>
<!-- ... -->
</body>
</html>
The nav> element is used to identify a navigational hub.
The anchor, or a>, element is used inside of nav> to create a clickable link.
Hypertext Reference (href) is an attribute that specifies the link’s destination.
Files in one directory may be linked to another directory’s contents via relative links.
You could assume that every links will have a corresponding URL, but relative links eliminate the need for this.
In this instance, the referenced file is called emoji.html.
The browser will automatically finish the whole URL for you if you tell it to look for emoji.html in the same directory.
In this approach, you may avoid the hassle of updating any absolute paths before releasing your web project.
Emoji.html has not yet been created.
Create an additional HTML file titled emoji.html next to index.html to resolve this.
:
<!-- emoji.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My favorite emoji</title>
</head>
<body>
<nav>
<a href="index.html">Home</a>
</nav>
<h1>My favorite emoji</h1>
<p>I don't just <em>like</em> emoji,<br>
I <strong>love</strong> emoji!</p>
<p>Here's a list of my most-used emoji:</p>
<ol>
<li>lady_beetle</li>
<li>snake</li>
<li>thumbs_up</li>
</ol>
</body>
</html>
Emoji.html has the same basic format as index.html.
The body> section of both emoji.html and index.html are almost similar; the only difference is that the headline in emoji.html has been upgraded to h1>.
The body> tag has a nav> element at its very top.
You’ve changed your link to go to index.html this time.
Next, drop a gallery.html file into the images/ folder you just made in your project’s root directory.
:
1<!-- images/gallery.html -->
2
3<!DOCTYPE html>
4<html lang="en">
5<head>
6 <meta charset="utf-8">
7 <title>Image gallery</title>
8</head>
9<body>
10<nav>
11 <a href="../index.html">Home</a>
12 <a href="../emoji.html">Emoji</a>
13</nav>
14<h1>Image gallery</h1>
15</body>
16</html>
In a second, you’ll be updating gallery.html with some new pictures.
Then, examine lines 11 and 12, which are where your internal links reside.
You need to put two dots (..) and a slash (/) before the link destination, since index.html and emoji.html are located in a folder above gallery.html.
Provide a link to your gallery in the main menu of index.html for even easier access.
:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Am I HTML already?</title>
</head>
<body>
<nav>
<a href="emoji.html">Emoji</a>
<a href="images/gallery.html">Gallery</a>
</nav>
<!-- ... -->
Emoji.html links may also be used to showcase your work.
:
<!-- emoji.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My favorite emoji</title>
</head>
<body>
<nav>
<a href="index.html">Home</a>
<a href="images/gallery.html">Gallery</a>
</nav>
<!-- ... -->
Whenever you create a link to an HTML page, you have to consider how you’ll get there from the current file.
Gallery.html may be found in the images/ subfolder, one level down from index.html.
So, you must include the subdirectory when connecting to gallery.html, like you have done above.
When connecting pages on your website, relative links are preferable.
Absolute links are used whenever an external connection is required.
:
<!-- index.html -->
<!-- ... --->
<h2>Links</h2>
<p>My favorite websites are:</p>
<ul>
<li><a href="https://www.realpython.com">realpython.com</a></li>
<li><a href="https://www.python.org">python.org</a></li>
<li><a href="https://www.pypi.org">pypi.org</a></li>
</ul>
<!-- ... --->
On your favorites list, you don’t just link to HTML files; you link to whole websites.
The addresses of these sites are exactly the same as those you would put into your browser.
Launch your browser and explore your site with the new links you added:
Links are an essential component of the overall design of the Internet, not simply for linking the pages on your own site.
Check out this HTML anchors lesson if you’re interested in learning more about links.
Images are also an important part of the Internet.
There wouldn’t be much to do online if people couldn’t show off their holiday photos and kitten GIFs.
The src property of the img> element is used to provide the location of the picture to be included in the HTML page.
You may specify the image’s origin using the src attribute, which works like href in a hyperlink.
The alt element should be used to provide descriptive text for images wherever possible.
In doing so, you ensure that users using screen readers may access your site.
Modify gallery.html by adding a link to three
images:
<!-- images/gallery.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Image Gallery</title>
</head>
<body>
<nav>
<a href="../index.html">Home</a>
<a href="../emoji.html">Emoji</a>
</nav>
<h1>Image Gallery</h1>
<img src="sky_1.png" alt="Cloudy sky.">
<img src="sky_2.png" alt="Sun shining through a cloudy sky.">
<img src="sky_3.png" alt="Sky with almost no clouds.">
</body>
</html>
After downloading the resources using the following code, you may locate the sky photos in the images/ folder:
If you’re using your own photos, make sure the filenames reflect that.
To ensure that your photographs can be seen by everyone, remember to include revise the alt text that explains what they depict.
In many ways, the alt text is analogous to Python docstrings.
The alt text defines the image’s content, while the docstring may explain the object’s function.
Alt text, like docstrings, should conclude with a period ( . ).
It takes time and effort, but it’s well worth it to add metadata to your photographs.
When a lovely dog is present in an image, it should be shared with the world.
If you still need persuading, have a look at Alt-texts: The Definitive Guide over at axess lab.
What you see when you open gallery.html in a browser should look somewhat like this:
Adding pictures to your website is a terrific way to make it more interesting to look at.
The picture gallery, however, is all over the place, and the website itself seems dated due to a lack of modernization.
It’s time for that to alter!
Next, you’ll learn how to style your HTML to have more say over how your website’s components look.
look.
Style Your Content With CSS
When you open a simple HTML file in a browser, the browser automatically applies some basic formatting.
That’s why you could tell the pieces apart in the prior paragraph without manually adding any formatting.
That’s essentially a favor done for you by the browser.
Indeed, when you create HTML, all you’re doing is defining the markup of your website.
The items on your website can’t be styled in any way using pure HTML.
The addition of CSS is required to style elements.
“CSS” refers to the Cascading Style Sheets format.
Later on, you’ll find that your CSS style rules may be nested inside one another,
Cascading Style Sheets arose from this principle.
It’s a foundational Internet technology, much like HTML.
It allows you to divide your website’s presentation from its content:
Your material should make sense in its source order in addition to having solid semantics and an appealing layout; you can always move it about using CSS later on if you want to, but you should get the source order right from the start so that what screen reader users hear makes sense. ( Original)
Here, you’ll find out how to implement your own custom style for your website.
CSS.
Add Color to Your Website
All you’ve done so far is open an HTML file on a web browser.
Nonetheless, web browsers are potent instruments that may be of great assistance when building a website.
With your browser’s developer tools, you can look inside any website.
The browser’s developer tools are helpful for a variety of tasks, but especially when working with CSS.
Changes you make in the developer tools will not be saved.
If you make changes and then refresh the page, they will be lost.
Whenever you’re satisfied with your modified styles, you can then paste the code into an HTML file’s style> element.
The style> element has to be included to the head section of index.html.
:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Am I HTML already?</title>
<style>
body {
background-color: rgb(20, 40, 60);
color: rgb(240, 248, 255);
}
a {
color: rgb(255, 111, 111);
}
</style>
</head>
<body>
<!-- ... -->
</body>
</html>
The style> element allows you to include CSS rules into an HTML file.
Even though browsers aren’t picky, the style> element should only be used within the head>.
Alternatively, you could get a brief glimpse of unstyled content when the browser attempts to display components before applying any CSS rules.
CSS, not HTML, is what you’ll find inside of a style> tag.
With CSS, you may specify how certain website components should be visually rendered.
Selectors let you to specify the items you want to affect, and are often followed by a declaration block.
Type selectors are used to select the body> and all a> elements in the preceding CSS code.
Later on in the guide, you’ll learn how to employ some other CSS selectors.
Already interested in learning more about CSS selectors? Check out Mozilla’s dedicated CSS selectors website.
A pair of braces, an opening one and a closing one, define the boundaries of the declaration block.
Within a block, declarations are separated by semicolons ( ; ).
There are two main sections to the declaration:
parts:
-
Property:
The identifier defining the feature -
Value:
The description of how the feature should be handled
There is a colon between the property and the value ( : ).
By adjusting the RGB values, the following code sets the background color of the body> to a deep blue and the text color to a very light gray.
With the second CSS ruleset, you’re using a trendy salmon color for all of your links.
The colors you choose may have a significant impact on how your site is perceived.
There are many methods to define colors in CSS.
To learn more about how current CSS colors are used, you may consult this handy guide from Smashing Magazine. A word of caution: there are more than a
You may utilize any of a hundred distinct characteristics and give them any of a wide variety of values. The more code you write in CSS, though, the more you’ll get familiar with its syntax, features, and peculiarities, just as you would with Python.
Altering your website’s presentation is as simple as picking a new color scheme or set of fonts.
The font color was modified by your previous actions.
Next, use the font-size property to increase or decrease the body text.
property:
<!-- index. html -->
<!-- ... -->
<style>
body {
background-color: rgb(20, 40, 60);
color: rgb(240, 248, 255);
font-size: 1.3em;
}
a {
color: rgb(255, 111, 111);
}
</style>
<!-- ... -->
You can make text appear in a browser 1.3 times as large as the font size of the parent element by using the font-size: 1.3em; property.
As html> is the parent element of body>, the text will appear in the browser at a size 1.3 times that of the system’s normal font.
Since sixteen pixels is the standard font size, the text will appear to be about twenty-one pixels in height.
The font size could be set explicitly in pixels if desired.
Text sizes are often expressed in either percentages or em, however.
The em unit, named after the letter “M,” has a long history of usage in typography as a unit of measurement for horizontal margins. (
(See Notes.)
When letters were cast into metal blocks, the horizontal breadth of the cast block was often the whole letter M.
Em is a suitable unit for making scalable designs in CSS, and it can also be used for vertical lengths.
It means visitors may enlarge images without compromising the look of your site.
This is especially crucial for mobile users and those who want to enlarge the font size for easier reading.
There are numerous more length units available in CSS than pixels and em.
It’s a good idea to check over these units and experiment with other sorts of units when you begin focused on developing your website.
Another fundamental factor that affects the look of your website is the typeface you choose for the content.
tremendously.
Change the Font
Fonts are a fantastic resource for giving your work a new look and feel.
There are two main options when selecting typefaces for a website:
options:
- Rely on the fonts your visitor has installed on their system.
- Load custom web fonts from either your server or external resources.
In any case, defining a font stack is recommended.
When more than one font is specified in font-family, the browser will attempt to load them in the order given, from left to right.
right:
<!-- index. html -->
<!-- ... -->
<style>
body {
background-color: rgb(20, 40, 60);
color: rgb(240, 248, 255);
font-family: "Helvetica", "Arial", sans-serif;
font-size: 1.3em;
}
a {
color: rgb(255, 111, 111);
}
</style>
<!-- ... -->
The preceding code declares a font stack, which causes the browser to try to load the Helvetica font first.
When a font in the font stack isn’t available, the browser will move on to the next backup font on the stack.
If neither Helvetica nor Arial is installed, the browser will choose another available sans-serif font.
Making your information understandable begins with selecting an appropriate typeface.
But, remember that the readability of your writings depends on more than just the font you choose.
You may experiment with the web typography’s visual appeal by changing the font size, line height, and color.
The more comprehensible your writing is, the wider your audience will be. Important: CSS attributes may be organized in any order you choose. Although functional groups of attributes may be easier to create than alphabetical ones, the former may be easier to maintain over time.
The CSS attributes of some developers are even organized.
in terms of length.
Check out the typeface that appears when you open index.html in your browser:
To find out which font was used, you may utilize your browser’s dev tools.
So what if it’s not Times New Roman or Courier?
Jump down here and tell the Real Python community the font your computer uses.
Loading custom web fonts allows you more control over the displayed font. If you want to utilize unique fonts on your website, you should check out the excellent tutorial How to use @font-face in CSS.
You haven’t even begun to create your website properly using the CSS that you’ve included to your HTML.
The possibilities for customizing your content using CSS are almost endless.
Check out Mozilla’s CSS reference if you’re interested in learning more.
.
Separate Your Concerns
Using the style> element, you inserted the CSS code from the previous step into index.html.
You could just as easily copy and paste the code to style emoji.html the same way.
Copying and copying code isn’t recommended, but you know that as a Python developer.
Having the same code in two locations makes code maintenance difficult.
Python allows you to avoid duplicating code by allowing you to import modules.
Similar capabilities exist in HTML to include external resources.
This enables you to use an external CSS file and make HTML references to that style sheet.
In addition to index.html and emoji.html, you should also generate a file titled style.css.
Next, copy the code from index.html’s style> and paste it into style.css.
:
1/* style.css */
2
3body {
4 background-color: rgb(20, 40, 60);
5 color: rgb(240, 248, 255);
6 font-family: "Helvetica", "Arial", sans-serif;
7 font-size: 1.3em;
8}
9
10a {
11 color: rgb(255, 111, 111);
12}
Remember that your CSS file just includes the CSS declarations.
The style> element, which is used to enclose CSS code in index.html, is unnecessary in a separate CSS file.
Note the use of CSS comment syntax in the first line.
A comment begins with a forward slash and an asterisk (/*).
It is OK to break up a CSS remark over numerous lines.
Finish your remark with an asterisk and a forward slash (*/).
Including a link to style.css in the index.html header is now possible.
file:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Am I HTML already?</title>
<link rel="stylesheet" href="style.css">
<!-- Removed: <style> ... </style> -->
</head>
<!-- ... -->
The link> tag is very much like the anchor tag (a>).
The link is also described by a href property.
Yet, it is a non-functional link since it is an empty element that only includes attributes.
Emoji.html needs the link to the stylesheet added as
well:
<!-- emoji.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My favorite emoji</title>
<link rel="stylesheet" href="style.css">
</head>
<!-- ... -->
Add the relative link to style.css so that the modifications in gallery.html are also reflected.
:
1<!-- gallery.html -->
2
3<!DOCTYPE html>
4<html lang="en">
5<head>
6 <meta charset="utf-8">
7 <title>Image Gallery</title>
8 <link rel="stylesheet" href="../style.css">
9</head>
10
11<!-- ... -->
Don’t forget that style.css lives in the images/ directory, one level up from gallery.html.
Hence, you shouldn’t simply link to style.css, but rather../style.css.
Check your pages in the browser once you’ve changed the CSS references:
Now there is a uniform look across all of your pages.
All pages will immediately reflect any changes made to style.css.
As a Python web developer, you will likely be tasked with creating substantial portions of HTML code.
Nonetheless, it’s usual practice to rely on third-party CSS frameworks for the actual design work in CSS.
You may get ready-made CSS code from a CSS framework.
You may need to make some changes to your HTML code in order to make full use of a CSS framework.
Yet, once learned, a CSS framework may help you avoid having to manually style HTML components in the future.
Bootstrap is a widely used CSS framework.
Actual Python tutorials on managing to-do lists and making a flashcards app both use the use of Simple.css or Bulma. Keep in mind that you may load an external stylesheet if you choose to begin your CSS creations from fresh.
To reload the style sheet. Incorporating a
If you use the reset style sheet trick before loading your own styles, the browser will clear its default style settings. You may now customize the appearance of any HTML element on your website as you see fit.
With the link> element, you may include non-local, external CSS style sheets in the same way you would include a local style sheet.
If your website uses many style sheets, the order in which they are referenced is important.
You’re about to begin looking into this conduct.
To begin, update your HTML files by include a link to an additional style sheet.
The following is a sample of the index.html file.
:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Am I HTML already?</title>
<link rel="stylesheet" href="https://cdn.simplecss.org/simple.css">
<link rel="stylesheet" href="style.css">
</head>
<!-- ... -->
Cascading style sheets is possible, as suggested by the C in CSS.
The new look is immediately apparent when you open index.html in your browser:
You have merged the style specifications from your internal style.css and the external simple.css files.
Change the load order of the external style sheets to see what happens.
The look of your site will change as you refresh the pages.
Properties in CSS are equivalent to overwriting variables in Python.
In most cases, an element’s value will be determined by the most recent value assignment.
You learnt how to replace the style> element with an external style sheet in this chapter.
There is a third option for incorporating CSS rules into HTML.
To apply direct formatting to HTML components, use the style property. The term for this kind of formatting is inline CSS. The usage of inline CSS style is not without merit.
Therefore, it is best to hold off on utilizing HTML and CSS until after you have mastered the basics.
In a nutshell, ad
It is not recommended to use inline CSS.
Further control over your design is possible by explicitly linking your CSS declarations with certain HTML components.
The next part of this tutorial will teach you how to use CSS to design elements with more versatility.
classes.
Use Classes for Greater Flexibility
So far, you’ve simply applied your CSS rules to broad categories of HTML content.
Nevertheless, by establishing rules for HTML properties, your CSS code may be far more particular.
By assigning a class property to an HTML element, its class value may be used as a selector in a style sheet.
One of the most important features of CSS classes is that they enable you to group similar components, apply a rule to them all at once, and perhaps alter them while maintaining a consistent appearance.
To round off photos, for instance, you may create a new image class. Assigning a class to just the pictures that need rounded corners is far more efficient than using the img name to target all image components.
The added benefit is that you may provide the same class to other components to make their corners round as well.
You may change the code in gallery.html to see how CSS class selectors function by
this:
1<!-- images/gallery.html -->
2
3<!-- ... -->
4<head>
5 <meta charset="utf-8">
6 <title>Image Gallery</title>
7 <link rel="stylesheet" href="https://cdn.simplecss.org/simple.css">
8 <link rel="stylesheet" href="../style.css">
9</head>
10
11<!-- ... -->
12
13<h1>Image Gallery</h1>
14<div class="gallery rounded">
15 <img src="sky_1.png" alt="Cloudy sky." class="rounded">
16 <img src="sky_2.png" alt="Sun shining through a cloudy sky." class="rounded">
17 <img src="sky_3.png" alt="Sky with almost no clouds." class="rounded">
18</div>
19<!-- ... -->
Very simply, you must provide a reference to your external style sheets.
Since the style sheet is located in a folder above the gallery.html file, you must prepend the two dots before linking to it.
Then, you’re using a div to enclose the image tags.
The div> element is used for basic page layout.
There is no semantic value in it, hence it should only be used if no other HTML element is better suited.
You are also enhancing HTML components using class attributes.
Line 14 even uses a space-separated list to bind together several classes.
To do this, you’ll need to provide two separate CSS classes to the div element.
In comparison, images in lines 15–17 have just one CSS class applied to them.
Go to style.css and add this CSS to make the classes.
code:
1/* style.css */
2
3/* ... */
4
5.gallery {
6 background: rgba(255, 255, 255, 0.2);
7 padding: 1em;
8}
9
10.rounded {
11 border-radius: 15px;
12}
13
14.gallery img {
15 margin-right: 0.2em;
16 width: 150px;
17}
The HTML class attribute is where you, without a dot, refer to the CSS class ( . ).
Nevertheless, in order to choose the class attributes in your CSS code, you must prefix the selector with a dot.
Check out Mozilla’s documentation on CSS selectors if you want to learn more.
Lines 6 and 7 provide the parameters for the.gallery element, such as a background color and a padding of 1em on both sides.
You may apply a fifteen-pixel-radius round border to all HTML components using the.rounded selector.
Line 14 demonstrates how to link CSS selectors.
You may create a rule for all img elements inside an HTML element with the class gallery by using the space-separated selector list.gallery img.
The CSS declarations on lines 15 and 16 make the gallery pictures 150 pixels wide and provide some space to the right side with margin-right.
CSS elements’ spacing may be modified with the use of the padding, margin, and border attributes.
These components may be seen as boxes, each with an outside border and an inside for storing information.
The box model is the name for this framework.
Boxes surround everything in CSS, and mastering them is essential for developing advanced layouts and aligning elements. (
(See Notes.)
Understanding the box model is essential if you want to go further into CSS.
If you want to master the fundamentals of CSS, you may do so by following Mozilla’s how to style HTML using CSS lesson.
From here, you may launch into learning all HTML and CSS have to offer in the realm of markup and design.
Nevertheless, you’ll quickly learn that HTML, in particular, is an extremely verbose language that may be difficult to create by hand.
That’s when your Python programming talents can really shine.
Following this, you’ll have a better understanding of how to interact with HTML files using Python.
effectively.
Handle HTML With Python
You, as a Python developer, are aware of Python’s potential as a useful tool for automating processes that would otherwise need human intervention.
Python’s efficiency is very helpful when dealing with huge HTML files.
work.
Programmatically Write HTML
HTML may be a pain to create due to the need for so many opening and closing tags.
Python, fortunately, is an excellent tool for automating the generation of substantial HTML documents.
Here, you’ll learn how to add to the emoji.html file so that it displays even more details about your preferred emoji.
In lieu of the numbered list, insert a
table:
1<!-- emoji.html -->
2
3<!-- ... -->
4<h1>My favorite emoji</h1>
5<p>I don't just <em>like</em> emoji,<br>
6I <strong>love</strong> emoji!</p>
7<p>Here's a table of my most-used emoji:</p>
8
9<table>
10 <thead>
11 <tr>
12 <th>#</th>
13 <th>Emoji</th>
14 <th>Name</th>
15 </tr>
16 </thead>
17 <tbody>
18 <tr>
19 <td>1.</td>
20 <td>lady_beetle</td>
21 <td>Lady Beetle</td>
22 </tr>
23 <tr>
24 <td>2.</td>
25 <td>snake</td>
26 <td>Snake</td>
27 </tr>
28 <tr>
29 <td>3.</td>
30 <td>thumbs_up</td>
31 <td>Thumbs Up Sign</td>
32 </tr>
33 </tbody>
34</table>
35<!-- ... -->
The table> element is used to create tables in HTML, while the tr> element is used to construct table rows.
Tables in HTML may contain a header and a body, much like Excel tables.
Using a thead> and a tbody> in your table markup is recommended practice but not required for the table to display properly.
Adding three th> components to the first row of your table head creates three table columns.
The main body of the table consists of the same number of columns and a variable number of rows.
The td> element, also used for table headers, is also used for the table’s data cells.
The emoji table includes the Unicode explanations of your top three emoji.
No one can possibly choose only three favorite emoji.
Creating the HTML table by hand would be onerous even with a small amount, such as twelve favorite emoji.
Now you’re throwing Python into the mix?
Start by creating a new file in your project directory called emoji table.py in Python.
you:
# emoji_table.py
import unicodedata
all_emoji = "lady_beetlesnakethumbs_upparty_popperstar-struckface_with_tears_of_joydog_facepopcornsmiling_face_with_sunglassessparklesspeech_balloonface_blowing_a_kiss"
columns = ["#", "Emoji", "Name"]
table_head = f"<thead>\n<tr><th>{'</th><th>'.join(columns)}</th></tr>\n</thead>"
table_body = "\n<tbody>\n"
for i, emoji in enumerate(all_emoji, start=1):
emoji_data = [f"{i}.", emoji, unicodedata.name(emoji).title()]
table_body += f"<tr><td>{'</td><td>'.join(emoji_data)}</td></tr>\n"
table_body += "</tbody>\n"
print(f"<table>\n{table_head}{table_body}</table>")
Python’s enumerate() function and the unicodedata package make it possible to generate an emoji table automatically. The strings may or may not include newline characters (n). Any whitespace that isn’t a single space will be disregarded by the browser. But, you may make your HTML code seem better by using n.
Copy the HTML code from emoji table.py and paste it into emoji.html after running it in the console.
:
1<!-- emoji.html -->
2
3<!-- ... -->
4<h1>My favorite emoji</h1>
5<p>I don't just <em>like</em> emoji,<br>
6I <strong>love</strong> emoji!</p>
7<p>Here's a table of my most-used emoji:</p>
8
9<table>
10<thead>
11<tr><th>#</th><th>Emoji</th><th>Name</th></tr>
12</thead>
13<tbody>
14<tr><td>1.</td><td>lady_beetle</td><td>Lady Beetle</td></tr>
15<tr><td>2.</td><td>snake</td><td>Snake</td></tr>
16<tr><td>3.</td><td>thumbs_up</td><td>Thumbs Up Sign</td></tr>
17<tr><td>4.</td><td>party_popper</td><td>Party Popper</td></tr>
18<tr><td>5.</td><td>star-struck</td><td>Grinning Face With Star Eyes</td></tr>
19<tr><td>6.</td><td>face_with_tears_of_joy</td><td>Face With Tears Of Joy</td></tr>
20<tr><td>7.</td><td>dog_face</td><td>Dog Face</td></tr>
21<tr><td>8.</td><td>popcorn</td><td>Popcorn</td></tr>
22<tr><td>9.</td><td>smiling_face_with_sunglasses</td><td>Smiling Face With Sunglasses</td></tr>
23<tr><td>10.</td><td>sparkles</td><td>Sparkles</td></tr>
24<tr><td>11.</td><td>speech_balloon</td><td>Speech Balloon</td></tr>
25<tr><td>12.</td><td>face_blowing_a_kiss</td><td>Face Throwing A Kiss</td></tr>
26</tbody>
27</table>
28<!-- ... -->
Emoji table.py allows you to add more of your preferred emoji to your HTML emoji table.
The :nth-child() pseudo-class in style.css may be used to add some extra styling to your table if you’re not satisfied with its appearance.
:
/* style.css */
/* ... */
th, tr:nth-child(even) {
background-color: rgba(255, 255, 255, 0.2);
}
td:nth-child(1) {
text-align: right;
}
td:nth-child(2) {
text-align: center;
}
The use of HTML tables is highly recommended for arranging tabular data online.
If you want to learn more about dealing with HTML tables, you may consult Mozilla’s reference on HTML tables and styling tables.
Emoji table.py simplifies the process of creating bigger tables, although it is still not easy.
The terminal output must be copied into the HTML file manually at this time.
That’s not the best scenario.
But now it’s time to look at Python’s additional HTML-related benefits.
code.
Create HTML Entities With Python
You may encode your writings in HTML using the extensive array of named character references that come with HTML.
To avoid using the UTF-8 € character for the Euro currency symbol, you might instead use the HTML entity €.
As it was previously impossible to type such characters, it was crucial that they be encoded.
The genuine UTF-8 character may now be used thanks to UTF-8 character encoding.
Since it improves readability, that is often suggested.
Even so, HTML encodings may be preferable in certain circumstances.
HTML entities are typically used when
characters:
- Are visually not distinguishable
- Interfere with HTML syntax
Consider the white space in this sentence.
The Unicode standard specifies twenty-five whitespace characters.
The regular space () and the non-breaking space () are two examples of these that have identical appearances ( ).
There is no visual distinction between the rooms.
The latter, however, is escaped as its HTML entity, , as you can see by viewing the page’s source code:
HTML documents require the use of escaped characters, such as the opening angle bracket () and closing angle bracket (>), to properly display HTML tags.
Take another look at the tutorial’s source code and pay attention to the escaped angle brackets:
A is used to escape the opening angle brackets.
To escape a closing angle bracket, type >.
Python’s inbuilt html module provides access to a comprehensive list of HTML entities.
module:
>>>
>>> import html
>>> html.entities.html5
{'Aacute': 'Á', 'aacute': 'á', 'Aacute;': 'Á', 'aacute;': 'á',
...
'zscr;': '𝓏', 'zwj;': '\u200d', 'zwnj;': '\u200c'}
There are four dictionaries defined by the HTML entities module.
HTML5 is one such language; it converts references to characters in HTML to their corresponding Unicode values.
You can determine an object’s HTML entity name using the html.entities.codepoint2name property.
character:
>>>
>>> import html
>>> code_point = ord("€")
>>> code_point
8364
>>> html.entities.codepoint2name[cp]
'euro'
The ISO 4217 currency code for the euro is 8364.
The value “euro” is found in the codepoint2name dictionary entry for 8364.
To create the valid € HTML entity, prefix the name with an ampersand (&) and append a semicolon (;) before using the name in your code.
Python can save you the trouble of having to memorize and manually type in the correct HTML entities.
The html module in Python also includes a parser that can be used to analyze HTML.
documents.
Parse HTML With Python
Python’s built-in html module can also help when you need to read data from HTML files.
Here, you’ll use html.parser to create a rudimentary HTML parser.
The script you’ll be writing will make use of the gallery.html file you made in the first part of this tutorial.
The following link will take you back to that section of the tutorial, or you can download all of the files at once:
Make sure to include a parse image links.py file in the same directory as gallery.html.
:
# images/parse_image_links.py
from html.parser import HTMLParser
class ImageParser(HTMLParser):
def handle_starttag(self, tag, attrs):
for attr, val in attrs:
if attr == "src" and tag == "img":
print(f"Found Image: {val!r}")
with open("gallery.html", mode="r", encoding="utf-8") as html_file:
html_content = html_file.read()
parser = ImageParser()
parser.feed(html_content)
If markup elements are detected in HTML data fed to an instance of Python’s HTMLParser, the instance will call its handler methods.
Create a new subclass of HTMLParser to scan the gallery.html source code for img> elements with a src attribute, as shown above.
The final product for the gallery.html file
this:
Found Image: 'sky_1.png'
Found Image: 'sky_2.png'
Found Image: 'sky_3.png'
This may not be a big deal for your local file since you can always just open it in your editor to reference it.
But think of what you could do if you modified the above script to extract the code from any URL.
If the html module in Python has piqued your interest, a primer on web scraping in Python would be a good next step.
You can also use Beautiful Soup to construct a web scraper for a more hands-on approach.
Check out the rest of this post for some additional steps to take before you start parsing.
tutorial.
Continue With HTML and CSS in Python
Simple HTML and CSS can get you very far.
When a programming language like Python is added to the mix, working with HTML and CSS becomes even more enjoyable.
Learn about some technologies that could help you put your HTML and CSS skills to use.
CSS.
JavaScript
In this tutorial, you learned the basics of HTML, the language used to create websites.
CSS is used to format and layout content.
That’s a fantastic foundation on which to build websites.
But no discussion of HTML, CSS, and JavaScript would be complete.
Because of its interpretive nature, modern websites cannot function without JavaScript.
JavaScript allows you to incorporate additional features into your websites.
HTML and CSS, for instance, can be dynamically updated in response to user interaction.
If you’re a programmer interested in web development, learning JavaScript is a great first step.
Go to Mozilla’s JavaScript tutorial if you want to learn more about the language.
Pythonistas interested in learning more about JavaScript should read Python vs. JavaScript for Pythonistas.
.
Jinja
In this tutorial, you learned how to use Python strings to save HTML markup for later use in generating HTML code on the fly.
The integration of HTML and Python into a growing web project can become challenging.
To keep tasks organized, using templates is recommended.
The front-end code for your site won’t need to be duplicated if you use templates.
As a result, you can store your HTML markup in template files and then add Python to them.
Jinja is the preferred template engine in Python.
Python and Jinja allow for the generation of HTML code on the fly.
However, you can go further if you so choose.
Jinja is useful whenever you need to generate programmatic content in text files.
Check out Real Python’s introduction to Jinja templating if you want to learn how to create feature-rich templates with Jinja.
.
Flask
You can create functional web applications with just a rudimentary understanding of HTML and CSS.
The front end, which the user sees, is handled by HTML and CSS.
You’ll need some mechanism in the background to pull data from the server.
Web frameworks are useful for this purpose. When starting from scratch, Flask is a great Python web framework to use.
After installing the flask package with pip, a Flask project is initiated by writing some basic code in a single Python file.
In other words, you can take things slowly and steadily improve your project as you go.
The Flask by Example tutorial will teach you the fundamentals of creating websites with Python and the Flask framework.
microframework.
Django is another widely used Python web framework.
When you create a new Django project, as opposed to a Flask project, you are provided with a framework to work within.
The administrative back end and associated databases are ready for use without the need to add much in the way of custom code.
Django’s strength can be an advantage for more ambitious web projects, but the framework’s many files can be daunting to newcomers.
Fortunately, Real Python has a plethora of Django tutorials available.
Building a portfolio app or a diary web app are both great places to start when learning Django.
The Django series of social networking frameworks is ideal if you want to create a larger project.
you.
PyScript is a new framework that makes it possible to use Python in a web browser, so
PyScript
.
Don’t confuse it with Flask or Django or any other web framework.
The rich and easily accessible ecosystem of Python libraries makes PyScript just as powerful as HTML, if not more so. (
(See Notes.)
If you’re interested in learning more about how to use Python in your web browser, I recommend A First Look at PyScript.