官术网_书友最值得收藏!

  • Practical Web Development
  • Paul Wellens
  • 436字
  • 2021-07-16 13:14:09

Adding styles to our documents

So how do the CSS rules become part of our document? There are three ways:

  • External style sheets
  • Internal CSS
  • Inline styles

External style sheets

This is the recommended way to add CSS to your site. It should be your goal for all style sheets of the production version of your site to be external. Simply add a line to the <head> section of your site, which should look like the following:

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

<link> is an HTML element we had not yet introduced. Its attributes are listed below:

  • rel, to indicate the relationship between the HTML document and the linked file.
  • type specifies the MIME type of the document so the browser knows how to load it.
  • href is used to specify the location of the file. You may expect a src attribute here, like is used for <img> tags, but the attribute to specify the file name in a <link> element is href. For the file name, we recommend that you always use relative pathnames. We suggest that you collect all your style sheets together in a folder with a meaningful name, like css or styles. Of course, the file itself should have a meaningful name too.

When the file does indeed exist, it will be loaded. That is why it is important that your <link> element resides in the <head> section of the document so all the CSS rules are read before the body of your document.

Internal CSS

For small projects, or projects you would like to limit to a single HTML file so that it is easy to email to someone, you can use internal CSS. All the CSS rules can then be placed inside the <head> section of your document, inside a <style> tag. That tag needs to, at a minimum, include a type attribute, as in the following example:

<style type="text/css">
p.red {
color:red;
}
</style>

Inline styles

Styles can be given to an inpidual HTML element by using the style attribute inside the HTML element itself, as in the following example:

<h3 style="color:green;">Congratulations</h3>

We do not recommend using this in your final product, but it is extremely useful to instantly see the effect of a change during development. If, for some reason, you leave one of the inline style attributes inside a page, it might take you forever to find out why your cool style sheet is not doing what it is supposed to be doing, on this one line of this one page.

On the other hand, I use it everyday, as I introduce and test new elements on a page while not disturbing anything else on the site, as modifying the external .css file would.

主站蜘蛛池模板: 抚州市| 威信县| 高阳县| 宽城| 河南省| 巴里| 申扎县| 青岛市| 宜宾县| 永宁县| 抚州市| 江源县| 依兰县| 锦州市| 南皮县| 阿拉善盟| 分宜县| 池州市| 乌海市| 韶关市| 洛阳市| 明溪县| 丽水市| 阳原县| 南漳县| 蓬莱市| 襄汾县| 隆德县| 瑞金市| 莎车县| 扶风县| 济源市| 黑山县| 杂多县| 潞西市| 杨浦区| 罗城| 保康县| 新竹市| 遂昌县| 三亚市|