english

learn php

16. html
20 minutes / 3925 words

sixteen

html

you don't have to master every detail of html to work with php. in fact, you don't need to know much of it at all. but, given that you've made it this far, it's probably time to make sure you have the basics down before we move on with html processing extensions.

html pages are generally stored in files with a .htm extension. the default html page in a directory is typically index.htm, much like the default php script is index.php. whether html is classified as a language or just a document format is an ongoing debate but the result doesn't matter. you can think of it as a language where every command is wrapped in <> and most commands, referred to as tags, have an open and close with the content between them like this...

<tag>content</tag>

tags can take parameters and those parameters can have content or just exist as present/absent like true/false conditions...

<tag param param2="content" param3="more content">even more content</tag>

some tags don't take content so they don't need the open and close and take the close term inside the open...

<tag param="content" />

tags can be nested...

<tag>
    <tag2>content</tag2>
</tag>

tags must be contained, though, or the results become unpredictable. html doesn't return errors, just mangled results. in other words, in this example, you can't close tag before closing tag2, once tag2 has been opened. given that html is a document format, though, that makes sense. if you start a paragraph and bold a word, you have to stop bolding before you can stop the paragraph. the same requirement exists in php -- you have to close the inside brackets before the outside brackets in functions or if blocks.

<p>my favorite fruit is <i>bananas</i>!</p>

returns a paragraph with "my favorite fruit is bananas!".

html has a large collection of built-in tags but anything that's not already built-in can be used as a custom tag. custom tags all behave the same as div unless modified.

the structure of an html page looks like this, though you've already seen this in the template example...

<!doctype html>
<html lang="en">
    <head>
        <title></title>
    </head>
    <body>
    </body>
</html>

while an html document can technically just be a blank file, this is the practical bare minimum content. !doctype tells the browser that it's an html document. it is the only tag that doesn't take either a close / or a close version of the tag because it's a special tag, beginning with !. there are no other exceptions to the rule.

html is where the entire content to be parsed is contained. head is things that aren't going to be displayed for the user but need to be known by the browser like the title, which is used as the name of the tab or bookmark but not actually showed as part of the content. body is the page to be displayed. html should always take a lang parameter. in this case, it's en for english but it should match the language of the content. this is for accessibility -- screen readers need to know what language to read in.

head tags

title, we have already seen.

meta is the other tag that's in pretty much all head sections. it is a parameter sent to the browser. in the template example, we saw...

<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=10.0" />

these are some of the most common parameters to be sent. charset tells the browser what type of characters to use -- in this case, utf-8, probably the most common unicode set on the web. i recommend always using utf-8. it is the de facto universal standard. viewport tells the browser, particularly if it's on a mobile device, how to fit the page on the screen and how much it can be zoomed in and out. a zoom scale of 1-10 is a good starting point for most web applications and starting with the site and device being the same width is a typical setting, though not necessarily the best for all apps.

note that meta doesn't take content so it just ends with / instead of a whole </meta> close tag.

base tells the browser where links should begin.

<base href="https://php.org/" />

means a link that doesn't have a server address in it will just be assumed to start with https://php.org/.

link allows external files to be loaded. this is frequently used for stylesheets, where the display information lives.

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

calls a stylesheet called style.css. if this is combined with the base command we just saw, the address of the stylesheet would be https://php.org/style.css.

script allows external javascript files to be loaded and executed.

<script src="script.js"></script>

calls a javascript file called script.js and runs it. note that script does have the option to take content so it requires a close tag instead of just /. it is possible to write javascript code directly between <script> and </script>. there are some situations where this is necessary but it is usually messy. for anything more than a few lines of basic javascript, it is a good idea to put it in a separate file.

<script>
console.log("javascript is enabled.");
</script>

much like script, there is an option to use style to put css directly in the html file. again, this is generally unwise for anything more than a few basic lines but it is useful in some situations.

<style>
h1{
    color: rgb(128 128 128/85%);
}
</style>

style can also take src like script but this has been replaced by the link tag we have already seen in modern html.

all other tags go in body...

organizational tags

there is a functional hierarchy of html organization but it's flexible. section -> div -> span. there are also several organizational tags that are only meant to exist a maximum of once on each page -- header, footer, nav, main, article, aside. with the exception of span, they all work the same way and they are used to define specific pieces, mostly for accessibility. from a visual standpoint, they all behave like div but it's good to use them to make your site more accessible.

div, short for "division", is the basic building block of an html page. it contains content and other tags. section behaves like div and generally gets treated as a higher level of hierarchy containing a group of div. you can have a nearly limitless depth of div within div as necessary for your content. (please exercise caution to avoid unnecessary complexity.)

span is like div but without the inherent break around it. it is used to contain text or images.

the other organizational tags have specific purposes for their content and they are mostly exactly what the names suggest.

header and footer are for the header and footer content. nav is for the main navigation menu. main is for the main content and article is for content that can be extracted for reading -- like by the reading mode in a browser or an rss reader for blog posts. aside is for sidebars. summary is used for article summaries but is not commonly used in practice.

the final organizational tag is the exception because it has a unique behavior, the paragraph tag, p. it is used specifically to wrap text and, by default, separates text from other paragraphs.

<html>
    <head></head>
    <body>
        <header></header>
        <nav></nav>
        <aside></aside>
        <main>
            <article>
                <section>
                    <div>
                        <p><span></span></p>
                        <p></p>
                        <p><span></span></p>
                        <p></p>
                        <p></p>
                    </div>
                </section>
            </article>
        </main>
        <footer></footer>
    </body>
</html>

it is typical to see pages without section or asidebut it is often useful to use the rest. section is generally only helpful for larger content where it is, as the name implies, divided into sections. aside, of course, only appears on pages with sidebars.

remember, how the page displays is determined by the stylesheet. the html is for content and organization, not to tell the browser how the page should look. organization is for content, not stylistic display.

parameters

tags can take parameters, as you have already seen. there are several that can apply to any tag. parameter values are wrapped in "" and separated by whitespace.

class and id allow tags to be referenced by javascript and stylesheets. id is a specific identifier that can only apply to a single tag. class is a group identifier that can apply to multiple tags, even multiple types of tag. class values are also separated by whitespace and there's no real limit to how many classes a tag can have.

<p id="first" class="one two three four five six">content</p>
<p id="second" class="three four seven">more content</p>

other parameters are specific to their tags. many can take value or type, for example. tags that don't apply to the tags they're on are simply ignored. any tag that isn't already used can be added and referenced in javascript or stylesheets.

<p customParameter="tomato" specialParameter="zucchini" evenMoreExcitingParameter="lettuce">something else</p>

these parameters will have no impact on the html but stylesheets and javascript can both access them. remember that html is not case-sensitive but javascript and stylesheets are.

text tags

beyond the organizational tags for text like p and span, there are tags used to change how text is displayed.

  • i and em are interchangeable and make text italicized.
  • b and strong are also interchangeable and make text bold.
  • sup and sub make text superscript and subscript, respectively.
  • mark highlights text.
  • del marks text as deleted, usually represented with a strikethrough.
  • ins marks text as inserted, usually represented with a underline.
  • u underlines text but is rarely used in modern html because it is typically confused with default link underlining behavior.
  • h# tags are hierarchical headings where # represented a number from 1 to 6. it is generally expected that a page will have a single h1 with the name of the page in it. beyond that, h2 is a subheading, h3 is a sub-subheading, etc. these should only be used to describe what text actually is, not how it should be displayed. stylesheets are used to determine things like size, font and weight so h# tags and other tags can behave identically from a visual perspective. their purpose is organizational and using them properly helps with accessibility.
  • code is used to mark text as code so it displays exactly as it's typed, including whitespace. pre does much the same thing without marking the text as code. kbd marks a keyboard command. var marks a code variable. samp marks sample program output.
  • blockquote is used for long quotations and, by default, indents on both sides while q is used for inline quotations.
  • abbr is used for abbreviations and cite for citations.
  • address is used for addresses.
  • time is used for dates and times.

it is worth noting that q, abbr, cite and address are rarely used or seen in practice outside html guidebooks. blockquote is extremely common. time, kbd, var and samp are practically never used and you'll likely never see them.

  • br inserts a new line inside any text.
  • hr inserts a horizontal ruled line.

links

we have already looked at loading external documents for stylesheets and javascript using link and script.

  • img loads an image and its address is in its src property (source).
<img src="myImage.jpg" />
  • a creates a clickable link and its address is in its href property (hypertext reference).
learn more about <a href="https://php.org">php</a>.
  • button also creates a clickable link but it is used to perform an action instead of loading a new page. they look slightly different by default but can be styled to be identical so button and a should be used for their specific purposes, not for how they look.
<button class="update">load new information</button>
  • svg creates an svg vector image. scalable vector graphics is a way of drawing graphics using text and looks similar to html.
  • canvas allows a graphic to be drawn using specific parameters, usually from javascript.
  • media, audio and video allow embedding of specific types of media. these are typically used in combination with significant stylesheet and javascript to make them work as intended.
  • figure, figcaption and picture also allow media embedding and description and can be thought of as a more advanced img tag.
  • embed and object allow specific types of embedding but are generally considered outdated and were mostly used for flash and shockwave in the early days of the interactive web. they have very niche modern use cases but, in a corporate development environment, you could go your whole career without ever using them.

lists

lists come in two types -- ordered and unordered. that doesn't mean that an unordered list displays in a random order. it is a reference to numbering. by default, an ordered list is displayed with numbers while an unordered list is displayed with bullets. you can certainly change the details of how they look, just like with all other html tags, but it's a good distinction to keep in mind.

<ol>
    <li>one</li>
    <li>two</li>
    <li>three</li>
    <li>four</li>
    <li>five</li>
</ol>

renders as...

1. one
2. two
3. three
4. four
5. five
<ul>
    <li>mouse</li>
    <li>chimpanzee</li>
    <li>panda</li>
    <li>tapir</li>
    <li>kangaroo</li>
</ul>

renders as...

• mouse
• chimpanzee
• panda
• tapir
• kangaroo

of course, you can change how they display using stylesheets. these are only default behaviors.

note that li has no meaning outside either ol or ul. you can use it if you like but its behavior will be unpredictable because that's outside its specified purpose. html is forgiving in that it never gives errors. it is unforgiving in that it doesn't tell you when you've done something that won't necessarily work the same way on different browsers.

dl and its members, dt, create a definition list but this is mostly still included for backward-compatibility and tends not to be used in modern html.

tables

html has a history of tables being misused because, when html was originally designed, it had almost no way to organize information or change how it is displayed. since then, decades ago, we now have organizational tags and stylesheets so we don't need to use tables to change how things look. don't fall into that trap. it makes things very hard for people with reduced vision or other accessibility issues to navigate your site and causes all kinds of potential problems in making it display properly on different screen sizes.

html tables have a single purpose. displaying tabular data like spreadsheets. that is, of course, something very useful. there is a pattern to how they are displayed and it's easier to see an example using them all than look at the tags individually.

<table>
    <caption>
        items
    </caption>
    <thead>
        <tr>
            <th>animal</th>
            <th>vegetable</th>
            <th>mineral</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>giraffe</td>
            <td>turnip</td>
            <td>mica</td>
        </tr>
        <tr>
            <td>horse</td>
            <td>broccoli</td>
            <td>olivine</td>
        </tr>
        <tr>
            <td>deer</td>
            <td>cauliflower</td>
            <td>halite</td>
        </tr>
        <tr>
            <td>hippopotamus</td>
            <td>squash</td>
            <td>talc</td>
        </tr>
        <tr>
            <td>tiger</td>
            <td>cabbage</td>
            <td>hematite</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td>5 animals</td>
            <td>5 vegetables</td>
            <td>5 minerals</td>
        </tr>
    </tfoot>
</table>

renders as...

animal vegetable mineral
giraffe turnip mica
horse broccoli olivine
deer cauliflower halite
hippopotamus squash talc
tiger cabbage hematite
5 animals 5 vegetables 5 minerals

forms and form elements

form elements in html are extremely useful but the form tag itself is a relic of an outdated way of having pages interact with each other.

on the web in the 1990s, when html was new, forms were used to collect information and submit them to other pages, usually processed by scripting languages like perl on servers. they then returned new pages. this is what php was originally built to do -- receive and process form data. what this causes is a website that doesn't respond to how a user behaves as they do things. a more modern approach is to allow users to interact with what's on the page and send the information to the server for processing in the background, receiving the result and displaying it on the existing page. this process uses ajax (asynchronous javascript and xml). the name is a little misleading because, while it was originally designed to work with xml, what is returned rarely is anymore. it is usually either html (which some developers avoid but i highly recommend for many reasons) or json, which we have already used extensively for data storage and retrieval.

the short version? if you find yourself using html form elements like input and textarea, great. if you find yourself using form and submit, you're doing it wrong and it would be a good idea to rethink the flow of your app.

that being said, you will certainly see form in the wild so be aware that form exists as a wrapper tag like ol and ul but that its purpose is outdated. some developers still like living in the past, however.

the other form elements, however, are part of the everyday experience on the web...

  • label is used for element labels. the label is linked to its element using for and name. if you're not applying a label, you don't need name but, if you use it, it typically matches the id for organization because javascript and css reference id while label references name.
<label for="name">name</label>
  • input is the most common tag. it allows a user to type in it. it can be one of several types...
    • text is the default and allows text to be typed.
    • password is the same as text in terms of how it behaves but it displays as * for each character.
    • submit, image and reset are only used inside form to either submit or erase all data inside. as with form, avoid.
    • checkbox and radio create checkboxes and radio buttons, respectively, allowing for on/off or one-of-many selections. these tend to be difficult to style and tend not to appear in modern sites as often.
    • button is just an old-fashioned way of using the button tag. you'll see it on some old sites but don't use it.
    • date, time and datetime-local are used to restrict input to only dates and times. (datetime-local is an odd name for it but there are historical reasons for it that should have long since been solved but likely never will be.)
    • hidden is used to define an input that is sent as part of a submission without being showed to the user, something that's surprisingly useful when combining php and html.
    • number only allows numbers and usually results in a numeric keyboard on mobile devices.
  • input has a series of restriction parameters...
    • checked specifies, if it's present, that a checkbox or radio button is checked. if it's absent, it's unchecked.
    • disabled, if present, disables input.
    • min and max limit numeric values.
    • maxlength limits the length of the input.
    • pattern requires input match a regular expression.
    • readonly, if present, disables changing the value.
    • required requires an input be completed (only when inside form so not relevant to modern html).
    • step specifies how large up and down steps are for numeric values.
    • value specifies the initial contents.
<input type="text" id="name" placeholder="jen wu" />
  • textarea is the multiline version ofinput but it only allows text input like input type="text". this is not really a restriction because all the non-text input types wouldn't apply to multiline values anyway.
<textarea id="description" placeholder="descriptive text"></textarea>

note that, unlike input, textarea has a close tag. instead of value="", the initial value is placed between textarea and /textarea like in a div or p tag. this is because new line characters in html parameters are potentially problematic -- they certainly were, at least, when html was first released and this has never really been considered for a change, though it would help with standardization and i have historically been critical of textarea treating its values differently.

  • select is the html dropdown selector and its options are listed by option. in html, it looks much like ol and ul but it behaves like a dropdown selector on your regular operating system. it is extremely limited in how it can be styled and is often replaced with a custom-built version.
<select id="country">
    <option value="fr">france</option>
    <option value="de">germany</option>
    <option value="be">belgium</option>
    <option value="es">spain</option>
    <option value="fi">finland</option>
</select>

note that the value is independent of the contents of each option. the value is what is transmitted and stored but the contents are what is displayed to the user. country and language codes, numeric months or days and formatted prices are common cases where these are different.

comments

while comments are generally unnecessary in a document format like html, they are possible.

<!-- comments go here -->

if you find yourself using them for anything other than temporary development and testing, though, you're probably doing something wrong.

assignments

© avi sato. creative commons attribution-noncommercial-noderivatives.