Another RayJune

Head First HTML And CSS 小记

The more deeply you force your brain to think, the better chance you have of learning and remembering.

(*)Intro: how to use this book

This is a learning experience, not a reference book.

Who is this book for?

Do you

  • want to learn, understand, and remember how to create web pages using the best techniques and the most recent standards?
  • prefer stimulating dinner-party conversation to dry, dull, academic lectures?

What your brain is thinking

Your brain craves novelty. It’s always searching, scanning, waiting for something unusual. It was built that way, and it helps you stay alive.

crave novelty 渴望新鲜的事物

It doesn’t bother saving the boring things; they never make it past the “this is obviously not important” filter.

How does your brain know what’s important?

Suppose you’re out for a day hike and a tiger jumps in front of you—what happens inside your head and body?

Neurons fire. Emotions crank up. Chemicals surge.
神经元会点火,情绪爆发,释放一些化学物质。

And that’s how your brain knows: This must be important! Don’t forget it!

But imagine you’re at home, or in a library. It’s a safe, warm, tiger-free zone. You’re studying.

Just one problem. Your brain’s trying to make sure that this obviously non-important content doesn’t clutter up scarce resources. Resources that are better spent storing the really big things. Like tigers. Like the danger of fire. Like how you should never again snowboard in shorts.

And there’s no simple way to tell your brain, “Hey brain, thank you very much, but no matter how dull this book is, and how little I’m registering on the emotional Richter scale right now, I really do want you to keep this stuff around.”

So what did this book do?

  • 文字与图片结合
  • 采用交谈式风格来讲述
  • 让学习的人想得更深,引起好奇心

Metacognition: thinking about thinking

If you really want to learn, pay attention to how you pay attention. Think about how you think. Learn how you learn.

So how do you get your brain to think HTML & CSS are as important as a tiger?

  • The slow way is about sheer repetition.
  • The faster way is to do anything that increases brain activity.

Here’s what YOU can do to bend your brain into submission

  • Slow down. The more you understand, the less you have to memorize.

Don’t just read. Stop and think.

When the book asks you a question, don’t just skip to the answer. Imagine that someone really is asking the question.

The more deeply you force your brain to think, the better chance you have of learning and remembering.

  • Do the exercises. Write your own notes.

Don’t just look at the exercises. Do it by yourself.

There’s plenty of evidence that physical activity while learning can increase the learning.

  • Make this the last thing you read before bed. Or at least the last challenging thing.

Part of the learning (especially the transfer to long-term memory) happens after you put the book down.

Your brain needs time on its own, to do more processing.

If you put in something new during that processing time, some of what you just learned will be lost.

  • Talk about it. Out loud.

Speaking activates a different part of the brain. If you’re trying to understand something, or increase your chance of remembering it later, say it out loud.

Better still, try to explain it out loud to someone else.

You’ll learn more quickly, and you might uncover ideas you hadn’t known were there when you were reading about it.

  • Listen to your brain.

Pay attention to whether your brain is getting overloaded.

If you find yourself starting to skim the surface or forget what you just read, it’s time for a break.

Once you go past a certain point, you won’t learn faster by trying to shove more in, and you might even hurt the process.

  • Feel something!

Your brain needs to know that this matters. Get involved with the stories. Make up your own captions for the photos.

  • Create something!

Apply this to something new you’re designing, or rework an older project.

Just do something to get some experience beyond the exercises and activities in this book.

The Language of the Web: HTML

HTML intro (HyperText Markup Language)

  • What does the web browser do? (displays the HTML page.)

That’s where HTML comes in. HTML tells the browser all about the content and structure of the page.

  • What you write (the HTML)

When the browser reads your HTML, it interprets all the tags that surround your text. Tags are just words or characters in angle brackets, like <head>, <p>, <h1>, and so on.

The tags tell the browser about the structure and meaning of your text.

So rather than just giving the browser a bunch of text, with HTML you can use tags to tell the browser what text is in a heading, what text is a paragraph, what text needs to be emphasized, or even where images need to be placed.

HTML Q&A

  • So HTML is just a bunch of tags that put around my text?

For starters. Remember that HTML stands for HyperText Markup Language, so HTML gives you a way to “mark up” your text with tags that tell the browser how your text is structured.

But there is also the HyperText aspect of HTML, which we’ll talk about a little later in the book.

  • The HTML document code has all kinds of indentation and spacing, and yet I don’t see that when it is displayed in the browser. How come?

Correct, and good catch. Browsers ignore tabs, returns, and most spaces in HTML documents. Instead, they rely on your markup to determine where line and paragraph breaks occur.

  • Why do I need the <html> tag? Isn’t it obvious this is an HTML document?

The <html> tag tells the browser your document is actually HTML.

While some browsers will forgive you if you omit it, some won’t, and as we move toward “industrial-strength HTML” later in the book, you’ll see it is quite important to include this tag.

  • What makes a file an HTML file?

An HTML file is a simple text file. Unlike a word processing file (like .doc for word), there is no special formatting embedded in it.

By convention, we add an “.html” to the end of the filename to give the operating system a better idea of what the file is.

But, as you’ve seen, what really matters is what we put inside the file.

Tags dissected

To tell the browser about the structure of your page, use pairs of tags around your content.

Element = Opening Tag + Content + Closing Tag (such as <a href="http://www.rayjune.me">Another RayJune</a>)

There are a few elements, like <img>, that are an exception to this rule.

Tags Q&A

  • I’ve noticed the HTML in some pages doesn’t always match opening tags with closing tags.

Well, the tags are supposed to match. In general, browsers do a pretty good job of figuring out what you mean if you write incorrect HTML.

But, as you’re going to see, these days there are big benefits to writing totally correct HTML.

(*)Why we need two languages(HTML & CSS)?

  • CSS looks like a totally different language than HTML. Why have two languages? That’s just more for me to learn, right?

While this does mean you need to learn two languages, you’ll discover that because each language is good at what it does.

And this is actually easier than if you had to use one language to do both jobs.

Meeting the “HT” in HTML (HyperTexT)

In Chapter 1 we found it to be a nice markup language (the “ML” in HTML) for describing the structure of web pages.

Now we’re going to check out the “HT” in HTML, hypertext, which will let us break free of a single page and link to other pages:

Use the <a> element to create a hypertext link to another web page.

Understanding attributes

Attributes are used to customize an element. And with an attribute you can provide additional information about the element.

href: It means “hypertext reference“, but we just call me “href” for short.

A hypertext reference is just another name for a resource that is on the Internet or your computer. Usually the resource is a web page, but I can also point to PDF documents…all kinds of things.

href arrtibute Q&A

  • I’ve seen many pages where I can click on an image rather than text. Can I use the <a> element for that?

Yes, if you put an <img> element between the <a> tags, then your image will be clickable just like text.

  • So I can put anything between the <a> tags and it will be clickable? Like, say, a paragraph?

You can indeed put a <p> element inside an <a> element to link an entire paragraph.

But you’ll mostly be using text and images (or both) within the <a> element.

(*)Bullet points

  • Don’t use spaces in the names you choose for files and folders for your website.
  • It’s a good idea to organize your website files early on in the process of building your site, so you don’t have to change a bunch of paths later when the website grows.
  • There are many ways to organize a website; how you do it is up to you.

The path meanings:

  • / is the root of the current drive;
  • ./ is the current directory;
  • ../ is the parent of the current directory.

Web Page Construction

You’ve certainly learned a lot already: tags, elements, links, paths…but it’s all for nothing if you don’t create some killer web pages with that knowledge.

From journal to website

  1. First, you’re going to create a rough sketch of the journal that is the basis for your page design.
  2. Next, you’ll use the basic building blocks of HTML (h1, h2, h3, p, and so on) to translate your sketch into an outline (or blueprint) for the HTML page.
  3. Once you have the outline, then you’re going to translate it into real HTML.
  4. Finally, with the basic page done, you’ll add some enhancements and meet some new HTML elements along the way.

(*)block VS inline elements

Remember:

  • block elements stand on their own
  • inline elements go with the flow.

In the meantime, you can also think about block versus inline this way:

  • block elements are often used as the major building blocks of your web page
  • while inline elements usually mark up small pieces of content

When you’re designing a page, you typically start with the bigger chunks (the block elements) and then add in the inline elements as you refine the page.

void elements intro

define:

Elements that don’t have any content by design are called void elements. (like <a>, <img>, <br>)This is a convenient shorthand that reduces the amount of markup in your HTML.

void elements Q&A

In Chapter 1 we said that an element is an opening tag + content + closing tag.

  • So how is <br> an element? It doesn’t have any content, and it doesn’t even have a closing tag.

Exactly. It doesn’t have any content. The <br> element is an element that doesn’t have any content. Why? Because it’s just meant to be a line break, nothing else.

So, when an element doesn’t have any real content by design, we just use a shorthand to represent the element and it ends up looking like <br>.

After all, if we didn’t have this shorthand, you’d be writing <br></br> every time you needed a line break, and how much sense does that make?

  • I’ve seen pages not with <br>, but with <br />. What does that mean?

It means exactly the same thing. The syntax used in <br /> is a more strict syntax that works with XHTML.

Wheneven you see <br />, just think <br>, and unless you’re planning on writing pages compliant with XHTML, you should just use <br> in your HTML.

(*)meaningful element

We always want to choose the HTML element that is closest in meaning to the structure of your content.

If this is a list, let’s use a list element. Doing so gives the browser and you the most power and flexibility to display the content in a useful manner.

list Q&A

  • Do I always have to use <ol> and <li> together?

Yes. Neither one of these elements really makes sense without the other.

Remember, a list is really a group of items: the <li> element is used to identify each item, and the <ol> element is used to group them together.

  • Can I put text or other elements inside an <ol> or <ul> element?

No, the <ol> and <ul> elements are designed to work only with the <li> element.

character entity

Browsers use < and > to begin and end tags, using them in the content of your HTML can cause problems.

But HTML gives you an easy way to specify these and other special characters using a simple abbreviation called a character entity.

For example, the > character’s abbreviation is &gt; and the < character’s is &lt;.

So:

1
The &lt;html&gt; element rocks.

Another important special character you should know about is the & (ampersand) character. If you’d like to have an & in your HTML content, use the character entity &amp; instead of the & character itself.

You can look up common ones at this URL: http://www.w3schools.com/tags/ref_entities.asp

or, for a more exhaustive list, use this URL: http://www.unicode.org/charts/

character entity Q&A

  • You said that & is special and I need to use the entity &amp; in its place, but to type in any entity I have to use a &. So for, say, the > entity, do I need to type &gt; ?

No, no! The reason & is special is precisely because it is the first character of any entity. So, it’s perfectly fine to use & in your entity names, just not by itself.

Just remember to use & anytime you type in an entity, and if you really need an & in your content, use &amp; instead.

  • When I looked up the entities at the www.w3cschools.com, I noticed that each entity has a number too. What do I use that for?

You can use either the number, like &#100 or the name of an entity in your HTML (they do the same thing). However, not all entities have names, so in those cases your only choice is to use the number.

Get connected with Internet

Uniform Resource Locator (URL)

A Uniform Resource Locator (URL) is a global address that can be used to locate anything on the Web, including HTML pages, audio, video, and many other forms of web content.

In addition to specifying the location of the resource, a URL also names the protocol that you can use to retrieve that resource(usually HTTP).

(*)What is HTTP?

  • HTTP is also known as the HyperText Transfer Protocol.

In other words, it’s an agreed-upon method (a protocol) for transferring hypertext documents around the Web.

agreed-upon 公认的,一致同意的

While “hypertext documents” are usually just HTML pages, the protocol can also be used to transfer images, or any other file that a web page might need.

  • HTTP is a simple request and response protocol.

So each time you type a URL into your browser’s address bar, the browser asks the server for the corresponding resource using the HTTP protocol.

If the server finds the resource, it returns it to the browser and the browser displays it. What happens if the server doesn’t find it? –’404 Error’

attributes Q&A

  • When I have two attributes in an element, is the order important? For example, should the title attribute always come after the href?

The order of attributes is not important in any element. So, use any ordering you like.

  • Can I have a destination id like “RayJune Xue or does an id have to beonly one word?

To work consistently with the most browsers, always start your id with a letter (A–Z or a–z) and follow it with any letter, digit, hyphen, underscore, colon, or period.

So, while you can’t use a space and have a name like “RayJune Xue”, that isn’t much of a restriction because you can always have “RayJune-Xue”, “RayJune_Xue”,RayJuneXue, and so on.

Meeting the Media: adding images to your pages

(*)How the browser works with images

Browsers handle <img> elements a little differently than other elements.

Take an element like an <h1> or a <p>. When the browser sees these tags in a page, all it needs to do is display them. Pretty simple.

But when a browser sees an <img> element, something very different happens: the browser has to retrieve the image before it can be displayed in a page.

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<body>
<h1>...</h1>
<h2>...</h2>
<p>
<img src="../images/green.jpg">
text...
</p>
<h2>...</h2>
<p>
<img src="../images/lightblue.jpg">
text...
</p>
<h2>...</h2>
<p>
<img src="../images/blue.jpg">
text...
</p>
</body>

Now let’s step through how the browser retrieves and displays this page when it get a request :

  1. The browser retrieves the file “index.html” from the server.
  2. The browser reads the index.html” file, displays it, and sees it has 3 images to retrieve. So, it needs to get each one from the web server, starting with “green.jpg”.
  3. Having just retrieved “green.jpg”, the browser displays it and then moves on to the next image: “lightblue.jpg”.
  4. This process continues for each image in the page.

JPEG, PNG and GIF

Luckily, only three of those formats are commonly used on the Web: JPEG, PNG, and GIF. The only tricky part is deciding which to use when.

JPEG

  • Use JPEG for photos and complex graphics

Works best for continuous tone images, like photographs.

Can represent images with up to 16 million different colors.

Is a “lossy” format because to reduce the file size, it throws away some information about the image.

Does not support transparency.

Files are smaller for more efficient web pages.

No support for animation.

But JPEG is not perfetc: Looked at lines, logos, small text, solid colors? They don’t look so great with JPEG.

PNG

  • Use PNG or GIF for images with solid colors, logos, and geometric shapes.

Works best for images with a few solid colors, and images wit lines, like logos, clip art and small text in images.

PNG can represent images with millions of different colors.
And PNG has three different size options: PNG-24 (supports millions of colors), PNG-16 (supports thousands of colors), and PNG-8 (supports 256 colors), depending on your needs.

PNG compresses the file to reduce its size, but doesn’t throw anything way. So, it is a “lossless” format.

support transparency.

Files tend to be larger than their JPEG equivalents, but can be smaller or larger than GIF depending on the number of colors used.

GIF

  • Use PNG or GIF for images with solid colors, logos, and geometric shapes.

Works best for images with a few solid colors, and images wit lines, like logos, clip art and small text in images.

GIF can represent images with up to 256 different colors.

also a “lossless” format.

GIF also supports transparency, but allows only one color to be set to “transparent.”

Files tend to be larger than their JPEG equivalents.

Supports animation.

(*)img Q&A

  • We’ve learned that void elements are elements without content or a closing tag. We’ve also learned that the <img> element is void. But doesn’t it have content (the image)?

Well, to be more precise, a void element is an element that doesn’t have any content in the HTML page to put the opening and closing tags around.

True, an image is content, but the <img> element refers to the image.

The image isn’t part of the HTML page itself. Instead, the image replaces the <img> element when the browser displays the page.

And remember, HTML page are purely text, so the image could never be directly part of the page. It’s always a separate thing.

  • Back to the example of a web page loading with images…when I load a web page, I don’t see the images loading one after the other. Why?

Browsers often retrieve the images concurrently. That is, the browser makes requests for multiple images at the same time.

Given the speed of computers and networks, this all happens fast enough that you usually see a page display along with its images.

Always use alt attribute

1
<img src="images/logo.jpg" alt="This is a logo">

(*)Bullet points

To handle modern displays, the concept of a CSS pixel has been created. The CSS pixel is 1/96 of an inch (96 ppi).

If you’re placing a transparent image in your web page, make sure the matte color of the image matches the background color of your web page.

Getting Serious with HTML

HTML, the new “living standard”

Rather than continue to crank out version 6, 7, 8 of HTML, the standards guys (and gals) have turned the specification into a living standard that will document the technology as it evolves.

So, no more version numbers. And you can stop calling it HTML5 because it’s just “HTML” from here on out.

并且 HTML5 是backwards compatibility(向后兼容)的,不用担心你的代码在更新的浏览器中运行不了。

living standard Q&A

  • So what happens if the spec changes tomorrow? What do I do?

If you’re writing solid HTML today and the spec changes tomorrow to incorporate a new element, then you can just keep on doing what you’re doing.

It’s up to you whether you want to use that new element or not.

  • What exactly is a spec, anyway?

The specification is the document that specifies what the HTML standard is; that is, what elements and attributes are in HTML, and more.

This document is maintained by the World Wide Web Consortium (W3C, for short), but anyone can contribute to it and have a say in how the standard is developed.

meta charset

The <meta> tag belongs in the <head> element (remember that the <head> contains information about your page). Adding a meta tag to specify the character encoding.

‘meta’ means we’re going to tell the browser something about the page.

The charset arrtibute is where we specify the character encoding. Add this line above any other elements in the <head> element

1
2
3
4
5
6
7
8
9
10
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Another RayJune</title>
</head>
<body>
...
</body>
</html>

meta Q&A

  • I’ve also seen <meta> tags that look like this: <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >. Do I need to use this instead sometimes?

No. That is the format for the <meta> tag in HTML 4.01 and earlier. In HTML5, you can just write <meta charset="utf-8">.

Getting started with CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Head First Lounge</title>
<style>
body {
background-color: teal;
}
</style>
</head>
<body>
...
</body>
</html>

or linking from “lounge.html” to the external stylesheet

1
2
3
4
5
6
7
8
9
10
11
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Head First Lounge</title>
<link type="text/css" rel="stylesheet" href="lounge.css">
</head>
<body>
...
</body>
</html>

CSS Q&A

  • How does the browser know which rule to apply to <em> when I’m overriding the inherited value?

With CSS, the most specific rule is always used.

So, if you have a rule for <body>, and a more specific rule for <em> elements, it is going to use the more specific rule.

  • How do I know which CSS properties are inherited and which are not?

In general, all of the styles that affect the way your text looks, such as font color (the color property), the font-family, as you’ve just seen, and other font-related properties such as font-size, font-weight (for bold text), and font-style (for italics) are inherited.

Other properties, such as border, are not inherited. A lot of the time, you can follow your common sense.

class selector

1
2
3
4
5
6
7
blockquote.greentea, p.greentea {
color: teal;
}
/* or this */
.greentea {
color: teal;
}

elements can be in more than one class.

1
<p class="greentea raspberry blueberry">

Styling with fonts and colors

Q&A

You’ve got quite a few choices for specifying font sizes: px, em, percentages(%), and keywords. Here’s a recipe:

  1. Choose a keyword (we recommend small or medium) and specify it as the font size in your body rule. This acts as the default size for your page.
  2. Specify the font sizes of your other elements relative to your body font size using either em or percentages (the choice between em and percentages is yours, as they are essentially two ways to do the same thing).
  • If I don’t specify any font sizes, do I just get the default font sizes?

Yes, and what those sizes are depends on your browser, and even the version of the browser you are running. But in most cases, the default body font size will be 16 pixels.

  • And what are the default sizes for the headings?

Again, it depends on the browser, but in general,

  • <h1> is 200%
  • <h2> is 150%
  • <h3> is 120%
  • <h4> is 100%
  • <h5> is 90%
  • <h6> is 60%

of the default body text font size, if the body font-size change, it change, too.

Notice that by default <h4> is the same font size as the body font size, and <h5> and <h6> are smaller.

font-family & @font-face

每个 font-family 包含一组有共同特征的字体。共有 5 个字体系列:sans-serifserifmonospacecursivefantasy,每个字体系列都包括大量字体,所以我们看到的只是每个字体系列中很少的几个字体例子。

  • sans-serif 无衬线,清晰、可读性好
  • serif 有衬线,高雅,传统
  • monospace 等宽,适合代码、像打印机打出来的
  • cursive&fantasy 有趣、像手写

通常,你指定的 font-family 包含一个候选字体列表(字体优先列表),它们都来自同一个字体系列。而最后总是放一个通用的字体系列名(如 sans-serif)(如果指定的前几个字体都无法找到,浏览器就会选择一个实际的字体来代替 serifsans-serif. 取代它的字体是浏览器定义的该字体系列的默认字体)。

1
2
3
body {
font-family: Verdana, Geneva, Arial, sans-serif;
}

@font-face,这个规则允许你定义一种字体的名字和位置,然后可以在你的页面中使用。

web 开放字体格式(Web open font format)woff。

@font-face 规则不论看起来还是从表现上讲都不像一个 CSS 规则,我们可以认为 @font-face 是一个内置的 CSS 规则,而不是一个选择器规则。
利用 @font-face 规则可以获取一个 Web 字体,并为它分配一个 font-family 名。最前面的 @ 就是一个很好的线索,说明这不是一个普通的 CSS 规则

类似的内置 CSS 规则还有:

  • @import: 允许导入其他 CSS 文件(而不是 HTML 中通过一个 link 导入)
  • @media : 允许创建特定于某些”媒体”类型的 CSS 规则,如手机等

How to specify web colors

Specify color by name

1
2
3
body {
background-color: silver;
}

Specify color in red, green, and blue values

1
2
3
body {
background-color: rgb(80%, 40%, 0%);
}

You can also specify the red, green, and blue values as a numeric value between 0 and 255. So:

1
2
3
body {
background-color: rgb(204, 102, 0);
}

Specify color using hex codes

Each set of two digits of a hex code just represents the red, green, and blue component of the color.

So the first two digits represent the red, the next two the green, and the last two represent the blue.

1
2
3
body {
background-color: #cc6600;
}

The two-minute guide to hex codes

  • Step one: Separate the hex color into its three components.
1
#cc6600 -> cc: red, 66: green, 00: blue
  • Step two: Convert each hex number into its decimal equivalent.
1
2
3
because c: 12, so cc = 12 * 16 + 12, cc = 204
66 = 6 * 16 + 6, 66 = 102
00 = 0 * 16 + 0, 00 = 0

Q&A

  • I’ve seen hex codes like #cb0; what does that mean?

You’re allowed to use shorthand if each two-digit pair shares the same numbers.

So, for instance, #ccbb00 can be abbreviated #cb0, or #11eeaa as #1ea. However, if your hex code is something like #ccbb10, then you can’t abbreviate it.

  • I like the linethrough decoration. Can I use it on text I’m editing to indicate things that need to be deleted?

You could, but there’s a better way. HTML has an element <del> that marks content in your HTML as content that should be deleted. There is a similar element called <ins> that marks content that should be inserted.

By using <del> and <ins>, you are marking the meaning of your content in addition to styling it.

最基本的文本颜色搭配原则:对于文本和背景,要使用对比度最大的颜色,这样能帮助提高可读性。

The box model

(*)What is it

CSS treats every single element as if it were represented by a box.

content -> padding -> border -> margin

padding margin Q&A

  • So other than size, it sounds like I can’t really style padding and margins?

That’s basically right. Both are used to provide more visual space, and you can’t give the padding or margin a direct color or any kind of decoration.

But because they are transparent, they will take on the color of any background colors or background images.

One difference between padding and margins is that the element’s background color (or background image) will extend under the padding, but not the margin. You’ll see how this works in a bit.

  • Is the size of the content area determined solely by the size of the content in it?

Browsers use several rules to determine the width and height of the content area.

The short answer is that while the content is the primary way the size of an element is determined, you can set the width and height yourself if you need control over the size of the element.

background-image

If you need to get that image into your paragraph element, so you’ll be using an <img> element, right?

There is another way. Using CSS, you can add a background image to any element using the background-image property. Let’s give it a try and see how it works:

1
2
3
4
.someClass {
...
background-image: url(images/background.gif);
}

background-image Q&A

  • Wait a sec, it seems like we have two ways to put images on a page. Is background-image a replacement for the <img> element?

No, the background-image property has a very specific purpose, which is to set the background image of an element.

It isn’t for placing images in a page—for that, you definitely want to use the <img> element.

  • A background image is pure presentation, and the only reason you would use a background-image property is to improve the attractiveness of your element.
  • An <img> element, on the other hand, is used to include an image that has a more substantial role in the page, like a photo or a logo.

background-position & background-repeat

The background-image property places an image in the background of an element. Two other properties also affect the background image: background-position and background-repeat.

By default, background images are repeated, we can use background-repeat: no-repeate to handle this.

Also, by default, browsers position a background image in the top left of the element which is where we want it, but let’s also add a background-position property just to give it a try.

1
2
3
4
5
6
.someClass {
...
background-image: url(images/background.gif);
background-repeat: no-repeat;
background-position: top left;
}

media query

1
2
3
4
5
<link href="lounge-mobile.css" rel="stylesheet" media="screen and (max-device-width: 480px)">

// Likewise, we could create a query that matches the device if it is a printer, like this:

<link href="lounge-print.css" rel="stylesheet" media="print">

Add media queries right into your CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@media screen and (min-device-width: 481px) {
#guarantee {
margin-right: 250px;
}
}
@media screen and (max-device-width: 480px) {
#guarantee {
margin-right: 30px;
}
}
@media print {
body {
font-family: Times, "Times New Roman", serif;
}
}

So, the way this works, only the CSS rules that are specific to a media type are included in an @media rule. All the rules that are common to all the media types are included in the CSS file below the @media rules, so that way you don’t have any unnecessarily repeated rules.

And, when a browser loads the page, it determines through the media queries the rules that are appropriate for the page, and ignores any that don’t match.

(*)media query Q&A

  • Is it better to use <link> or @media to specify different CSS rules for different media types and characteristics?

Either one will work.

But notice that if you put all your rules in one file and split them up using @media rules, your CSS could get pretty big.

By using different <link> elements for different media types, you can keep your CSS organized in different files depending on the media type. So, if your CSS files are fairly large, we recommend using <link> elements to specify different stylesheets.

Div and span

When use div and when not

div just like a container.

You want to add structure where it has a real purpose, but don’t add structure for structure’s sake.

Always keep your structure as simple as possible to get the job done.

width, height Q&A

  • Which one does width means

The content, only the content.

  • If I don’t set the width of an element, then where does the width come from?

The default width for a block element is “auto”, which means that it will expand to fill whatever space is available.

  • What are the different ways I can specify widths?

You can specify an actual size(200 px)—or you can specify a percentage(50%).

If you use a percentage, then the width is calculated as a percentage of the width of the container the element is in (which could be the <body>, a <div>, etc.).

  • What about the height?

In general, the height of an element is left at the default, which is auto, and the browser expands the content area vertically so all of the content is visible.

You can explicitly set a height, but you risk having the bottom of your content overflow into other elements if your height isn’t big enough to contain it.

So in general, leave your element heights unspecified so they default to auto.

(*)text-align Q&A

  • Why does the text-align property affect the alignment of the images? Shouldn’t it align only text? Seems like it should be called something else if it aligns images too.

The truth is that text-align will align all the inline content in a block element.

So in this case, we’re setting the property on the <div> block element, and all its inline content is nicely centered as a result.

Just remember that text-align, despite its name, works on any kind of inline element One other thing to keep in mind: the text-align property should be set on block elements only. It has no effect if it’s used directly on inline elements (like <img>).

  • I noticed the text inside the <div> is all inside other block elements, like <h2>, <h3>, and <p>. So, if text-align is aligning inline elements in the <div> block element, how is the text in these nested block elements getting aligned?

That’s because these block elements inherit the text-align property from the <div>.

So here’s the difference: rather than the <div> itself aligning the text in the headings and the paragraphs (which it won’t do because these are block elements), the headings and paragraphs are inheriting the text-align value of “center”, and then aligning their own content to center.

This gives you a lot of leverage when you use a <div>, because you can wrap a section of content in a <div> and then apply styles to the <div> rather than each individual element.

Of course, keep in mind that not all properties are inherited by default, so this won’t work for all properties.

select descendants

1
2
3
#elixirs h2 {
color: teal;
}
  • Is there a way to select a direct child?
1
2
3
#elixirs > h2 {
color: teal;
}

shorthand

1
2
3
4
5
6
7
8
9
10
{
padding-top: 0px;
padding-right: 20px;
padding-bottom: 30px;
padding-left: 10px;
}

{
padding: 0px 20px 30px 10px;
}

The border shorthand is even more flexible than margins or padding because you can specify them in any order you like.

1
2
3
4
5
6
7
8
9
10
{
border-width: thin;
border-style: solid;
border-color: #007e7e;
}

{
border: solid thin #007e7e;
border: #007e7e solid thin;
}

You can also use shorthand for backgrounds:

1
2
3
4
5
6
7
8
9
{
background-color: white;
background-image: url(images/cocktail.gif);
background-repeat: repeat-x;
}

{
background: white url(images/cocktail.gif) repeat-x;
}

(*)inline vs block: width/height/padding/margin Q&A

  • Can I set properties like width on <span> elements? Actually, what about inline elements in general?

You can set the width of inline elements like <span>, <em>, and <strong>, but you won’t notice any effect until you position them.

You can also add margin and padding to these elements, as well as a border. Margins and padding on inline elements work a little differently from block elements—if you add a margin on all sides of an inline element, you’ll only see space added to the left and right.

You can add padding to the top and bottom of an inline element, but the padding doesn’t affect the spacing of the other inline elements around it.

  • What about img?

img are a little different from other inline elements. The width, padding, and margin properties all behave more like they do for a block element.

If you set the width of an image using either the width attribute in the <img> element or the width property in CSS, the browser scales the image to fit the width you specify.

The a element and its multiple personalities

1
2
3
4
5
6
7
8
9
#elixirs a:link {

}
#elixirs a:visited {

}
#elixirs a:hover {

}
1
2
3
#elixirs a:focus {

}

The focus state occurs when the browser focuses on your link.

What does that mean? Some browsers allow you to press your Tab key to rotate through all the links on your page.
When the browser comes to a link, that link has the “focus”.

Setting a value for the focus pseudo-class is helpful for accessibility because those who need to use a keyboard to access a link (as opposed to a mouse) will know when they’ve got the right link selected.

1
2
3
#elixirs a:active {

}

The active state occurs when the user first clicks on a link.

  • Can’t my links be in multiple states at the same time? For instance, my link could be visited, have the mouse hovering over it, and the user could be actively clicking on it all at once.

They sure can. You determine which style is applied by the ordering of your rules. So, the right ordering is generally considered to be:

  1. link
  2. visited
  3. hover
  4. focus
  5. active

(*)What is Pseudo-class

Pseudo usually means something that looks like the real thing, but isn’t.

Everyone knows what a CSS class is. It’s a grouping you create to place elements in so you can style them together.

Put “pseudo” and “class” together and you have a pseudo-class: it acts like a class, but it isn’t a real class.

And yet, a:link, a:visited, and even a:hover all allow you to specify style, just like they were classes.

In other words, you can style pseudo-classes, but no one ever types them into their HTML.

(*)Pseudo-class Q&A

  • How does Pseudo-class work?

The browser goes through and adds all your <a> elements to the right pseudo-classes.

  • If a link’s been visited, no problem; it goes into the :visited pseudo-class.
  • Is the user hovering over a link? No problem, the browser throws it in the :hover pseudo-class.
  • Oh, now the user isn’t hovering? The browser yanks it out of the “hover pseudo-class.

  • Can Pseudo just do links?

No, I do other elements too. Modern browsers already support pseudo-classes like :hover on other types of elements. And there are some other pseudo-classes, too.

For instance, the pseudo-class :first-child is assigned to the first child of any element, like the first paragraph in a <blockquote>. And you can even select the last paragraph of a <blockquote> with the :last-child pseudo-class.

(*)Layout and positioning

(*)Flow

Flow is actually what the browser uses to lay out a page of HTML elements.

The browser starts at the top of any HTML file and follows the flow of elements from top to bottom, displaying each element it encounters.

  • Considering the block elements, it puts a linebreak between each one.

So the first element in a document is displayed first, then a linebreak, followed by the second element, then a linebreak, and so on, from the top of your file to the bottom. That’s flow.

  • What about the inline elements?

Inline elements are flowed next to each other, horizontally, from top left to bottom right.

float

Floated elements are ignored by block elements, while inline elements know they are there.

当设置浮动时,该元素会脱离普通文档流,浮上去。这时候其余块元素会忽视掉产生浮动的元素,该怎么排还是怎么排,但内联元素会考虑已浮动元素的外边框围绕着边框排列

As you’re going to see, there are many ways to do things in CSS, and each method has its own strengths and weaknesses.

What’s important to you is that you understand the techniques so that you can apply them when and where you need to.

float Q&A

  • Can I float to the center?

No.

But if you think about it, if you were to float to the center, then the inline content under the floated element would have to be flowed around both sides of your element which would be quite tricky to get to work in a browser.

  • Do margins collapse on floated elements?

No, they don’t, and it’s pretty easy to see why.

Unlike block elements that are flowed on the page, floated elements are just, well, floating.

In other words, the margins of floated elements aren’t actually touching the margins of the elements in the normal flow, so they can’t be collapsed.

  • Can I float an inline element?

Yes, you sure can. The best example —and a common one—is to float images.

Give it a try—float an image left or right in a paragraph and you’ll see your text flow around it.

How absolute positioning works

When an element is absolutely positioned, the first thing the browser does is remove it completely from the flow.

The browser then places the element in the position indicated by the top and right properties (you can use bottom and left as well).

Because the sidebar is out of the flow, the other elements don’t even know it is there and they ignore it totally.
Elements that are in the flow don’t even wrap their inline content around an absolutely positioned element. They are totally oblivious to it being on the page.

absolute position Q&A

  • What is the position property set to by default?

The default value for positioning is static.

With static positioning, the element is placed in the normal document flow and isn’t positioned by you—the browser decides where it goes.

You can use the float property to take an element out of the flow, and you can say it should float left or right, but the browser is still ultimately deciding where it goes.

Compare this to the absolute value for the position property. With absolute positioning, you’re telling the browser exactly where to position elements.

  • Can I only position block elements?

You can absolutely position any element, block or inline.

Just remember that when an element is absolutely positioned, it is removed from the normal flow of the page.

  • Do I have to specify a width for an absolutely positioned element just like the floated elements?

No, you don’t have to specify a width for absolutely positioned elements.

But if you don’t, by default, the block element will take up the entire width
of the browser, minus any offset you specify from the left or right.

This might be exactly what you want, or it might not. So set the value of the width property if you want to change this default behavior.

  • Do I have to use pixels for positioning?

No. Another common way to position elements is using percentages.

If you use percentages, the positions of your elements may appear to change as you change the width of your browser.

For example, if your browser is 800 pixels wide, and your element’s left position is set to 10%, then your element will be 80 pixels from the left of the browser window. But if your browser is resized to 400 pixels wide, then the width will be reduced to 10% of 400 pixels, or 40 pixels from the left of the browser window.

Another common use for percentages is in specifying widths.

If you don’t need specific widths for your elements or margins, then you can use percentages to make both your main content area and your sidebars flexible in size. You’ll see this done a lot in two-column and three-column layouts.

  • Do I have to know how to use z-indexes to use absolute positioning?

No, z-indexes tend to be used most often for various advanced uses of CSS, especially when web page scripting is involved.

为什么不用表格布局

If you tell me that you can easily do the same with a table-based layout (remember - the HTML isn’t changing) then by all means use tables for layout.

Two other important things are accessibility and SEO.

Both care about in what order information is presented. You cannot easily present your navigation at the top of the page if your table-based layout puts it in the 3rd cell of the 2nd row of the 2nd nested table on the page.

So your answers are maintainability, accessibility and SEO.

postion Q&A

  • position VS float, which one is better

It just depends on what you need.

If you really need an element to appear at a precise position in the page, then absolute positioning is the way to go.

But if you want to have text flow around an image, you’ll definitely want to use float.

  • Is there a way I can change which one absolutely positioned element is on top?

Use z-index, only work for positioned element.

1
2
3
4
5
6
7
8
9
10
11
12
13
#div1 {
position: absolute;
top: 30px;
left: 30px;
z-index: 0;
}

#div2 {
position: absolute;
top: 30px;
left: 30px;
z-index: 1;
}
  • Is there a maximum z-index value?

Yes, but it’s a very large number, and practically, you’ll never need your z-index values to go that high.

  • Can any element have a z-index?

    No, only elements that have been positioned with CSS using absolute, relative, or fixed positioning.

文章标题:Head First HTML And CSS 小记

文章作者:RayJune

时间地点:上午 10:11,于又玄图书馆

原始链接:https://www.rayjune.me/2017/11/25/Head-First-HTML-And-CSS-note/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。