HTML Element

Tag Description
<!--...--> Defines a comment
<!DOCTYPE> Defines the document type
<a> Defines a hyperlink
<link> defines the relationship between the current document and an external resource.
Most often used to link to external style sheets (.css).
<h1> to <h6> headings
<img> image
<figure> mark up a figure in a document
<figcaption> define a caption for the figure
<div> Defines a division.
The <div> tag is used as a container for HTML elements - which is then styled with CSS or manipulated with JavaScript.
The <div> tag is easily styled by using the class or id attribute.
<span> An inline container used to mark up a part of a text, or a part of a document.
The <span> tag is easily styled by CSS or manipulated with JavaScript using the class or id attribute.
The <span> tag is much like the <div> element, but <div> is a block-level element and <span> is an inline element.
<hr> a horizontal rule that is used to separate content
<script> To embed a client-side script (JavaScript). Either contains scripting statements, or it points to an external script file through the src attribute.
<strong> use boldface for enclosed text, show importance
<em> use italic font, show emphasis
<u> underline text
<tt> monostyle/typewriter, commonly used for codes
<mark> highlight text
<del> strikethrough
<ins> insert text, show underline
<sub> for subscript
<sup> for superscript
<span> an inline container used to mark up a part of a text. The <span> tag is much like the <div> element, but <div> is a block-level element and <span> is an inline element.
<code> Inline code element. Equivalent to backticks, `code`. Use font-family: monospace.

References:

https://developer.mozilla.org/en-US/docs/Web/CSS/border

https://html.com/tables/rowspan-colspan/

https://www.w3.org/TR/CSS2/text.html#alignment-prop

Force line break

In html, <br/> (or <br /> with a space before /, or simply <br>) and \ (single backslash) give a single line break.

  • If it doesn’t work, add a black line above and below.
  • </br> is nonsense. Don’t use that.

Add a blank line

use &nbsp; (followed by a blank line) or <p>&nbsp;</p>.

Adjust vertical space

<p style="margin-top:-1cm;">&nbsp;</p>

<link rel="stylesheet" href="mystyle.css">

  • rel stands for “relationship”. It is one of the key features of the <link> element — the value denotes how the item being linked to is related to the containing document.
  • href path to the stylesheet.

Add an image

  • no caption

    <!-- only need the "img" tag -->
    <img src="https://drive.google.com/thumbnail?id=1nxfdIKXgZvOqXVSeA3h_hf0yxmsM361l&sz=w1000" alt="Phi_b" style="display: block; margin-right: auto; margin-left: auto; zoom:80%;" />
    

    zoom: 80% here refers to the original size of the image, scale to 80%.

  • with caption

    <!-- need to surround the "img" tag with "figure" and "figcaption" -->
    <figure style="text-align: center;">
    <img src="https://drive.google.com/thumbnail?id=1nxfdIKXgZvOqXVSeA3h_hf0yxmsM361l&sz=w1000" alt="Phi_b" style="display: block; margin-right: auto; margin-left: auto; zoom:80%;" />
    <figcaption>The $\Phi$ and $\phi$ functions (CDF and pdf of standard normal).</figcaption>
    </figure>
    
  • inline image

    <img src="https://drive.google.com/thumbnail?id=1Ec_oVF6wwb-nnGt-EDkqLrzg88DR3qZm&sz=w1000" alt="巡航" style="zoom:40%;" />
    

Q: How to resize img?

A: Using the height and widthattributes on the img tag. These values specify the height and width of the image element in pixels.

When you specify both height and width, the image is forced to fit the requested dimension. It could change the original aspect ratio.

Q: How to preserve the aspect ratio while resizing images?

A: Specify only width and set height to auto. Or the other way around, specify height and set width as auto.

img {
  width: 400px,
  height: auto
}

Website Fonts

Q: How to specify fonts for your website?

A: Start with the font you want, and end with a generic family. The font names should be separated with a comma.

In CSS there are five generic font families: serif, sans-serif, monospace, cursive, and fantasy.

To use non web-safe fonts on your website, two options:

  1. To embed your selected fonts into a webpage, copy this code into the head of your HTML document. Here, we want to use a font named “Helvetica Neue”.

    <head>
    <link href="https://fonts.cdnfonts.com/css/helvetica-neue-5" rel="stylesheet">
    <style>
    body {
      font-family: "Helvetica Neue", sans-serif;
    }
    </style>
    </head>
    

    Note that “Helvetica Neue” is pre-installed on Mac. However, Windows users will need to manually load the font file, which may affect your website’s performance, making it slow.

  2. Could use @import to load the font into your style sheet.

    @import url('https://fonts.cdnfonts.com/css/helvetica-neue-55');
    

@import allows you to import a style sheet into another style sheet.

  • The @import rule must be at the top of the the stylesheet, before any other at-rule (but after any @charset and @layer) and style declarations. Othewise it will be ignored.

Syntax:

@import url("navigation.css"); /* Using a url */
@import "navigation.css"; /* Using a string */
  • url is a <string> or a <url> type representing the location of the resource to import. The URL may be absolute or relative.

Web safe fonts are fonts that are universally installed across all browsers and devices.

However, there are no 100% completely web safe fonts. There is always a chance that a font is not found or is not installed properly.

Therefore, it is very important to always use fallback fonts.

This means that you should add a list of similar “backup fonts” in the font-family property. If the first font does not work, the browser will try the next one, and the next one, and so on. Always end the list with a generic font family name.

body {
  font-family: "Helvetica Neue", , Helvetica, Arial, SimSun, sans-serif;
}

Arial is a web safte font that is available across all browsers.

Attributes

The id attribute is used to give a unique name or identifier to an element within a document. This makes it easier to select the element using CSS or JavaScript.

Like id attribute, the class attribute is also used to identify elements.

  • But unlike id, the classattribute does not have to be unique in the document.
  • This means you can apply the same class to multiple elements in a document.

You can apply one or more CSS classes to various document entities including headings, images, divs, and spans.

Specify typesetting for tags. Universally applicable as long as the tag supports the attribute.

Global attributes are attributes that can be used with all HTML elements.

Attributes define additional characteristics or properties of the element such as width and height of an image. Attributes are always specified in the start tag (or opening tag) and usually consist of name/value pairs like name="value". Attribute values should always be enclosed in quotation marks "<value>".

  • Attributes must be separated from each other by one or more space characters.

Style

style attribute specifies an inline style for an element, such as color, font, size. It allows you to specify multiple attributes at one time. It is equivalent to use font-size="12px". 冒号赋值,分号分隔 properties。

It overrides any style set globally, e.g. styles specified in the <style> tag or in an external style sheet.

  • Now we run into the usage of the word property. Each property consists of a property-key and it’s associated VALUE, separated by a colon :. The syntax is property-key:value. If you have more then one property you use the semi-colon ; as separator. E.g.,
    • font-size: 12px sets font size to be 12px.

    • height: 500; width: 500; set the width and height in pixels.

      • it’s useful to set heigh: auto; so that the aspect ratio of the image is maintained.
    • style = “font-size:12px; background-color:blue;” to sepecify multiple properties.

      It is equivalent to font-size="12px" background-color="blue" .

      Note that if specify properties one-by-one: 等号赋值,值要放在引号内;空格分隔 properties。

      • key and value are connected using equal sign key="value";
      • value is quoted using double quotes "value";
      • multiple properties are separated by spaces.
    • text-align: left | right | center | justify specify the horizontal alignment of text.

      • justify each line is stretched so that every line has equal width, and the left and right margins are straight.
    • margin-bottom: 20px controls the space outside of an element. Specify one side. Also have margin-top, margin-left, and margin-right.

    • margin: 25px 50px 75px 100px; top=25px, right=50px, bottom=75px, left=100px, clockwise;

    • margin: 25px 50px; top-bottom 25px; left-right 50px;

    • margin: 25px all four margins are 25px;

    • padding-bottom: 20px controls the space inside of an element. Same way to specify as margin. Can specify one side, or can use a sequence to specify all sides.

    • border: solid red 2px; red box four sides.

margin

padding 在框里面

margin 在框外面

border 定义框本身

/* one simplest box */
.boxed {
    border: 1px solid #535353;
    padding-bottom: 20px;
}

Rem units

Rem (short for “root-em”) is a relative unit in CSS. Rem units set an element’s font size relative to the font size of the root element.

If no font size is set for the <html> element in CSS, it defaults to 16px in most browsers. Therefore, if the root element’s font-size is 16px, any element on the page with a font-size of 1rem will also be 16 pixels. An element on the page with a font-size of 2rem will be 32 pixels, and so on.

Why should you use rem unit?

  • Scalability
  • Accessibility: Absolute units like pixels create accessibility barriers. Pixels override the document’s root font size, meaning the user’s preferences are ignored if they have their root element set to a larger font size for accessibility reasons.

Center and bold

<div class = "boxed">
<p style="text-align:center; font-weight:bold;">Linear CEF Model</p>

$$
\begin{aligned}
y &=  \boldsymbol{x}'\boldsymbol{\beta} + u \\
\mathbb{E}(u|\boldsymbol{x}) &= 0
\end{aligned}
$$
</div>

box

Properties

font-weight sets how thick or thin characters in text should be displayed.

p.normal {
  font-weight: normal;
  font-style: italic;
}

p.thick {
  font-weight: bold;
}

p.thicker {
  font-weight: 900;
}

font-style 斜体

font-weight 加粗

Value Description
normal Defines normal characters. This is default
bold Defines thick characters
bolder Defines thicker characters
lighter Defines lighter characters
100 200 300 400 500 600 700 800 900 Defines from thin to thick characters. 400 is the same as normal, and 700 is the same as bold

async specifies that the script is downloaded in parallel to parsing the page, and executed as soon as it is available (before parsing completes).

type specifies the media type of the script.


Font

font-family: Arial, Helvetica, sans-serif; specifies the font for an element. 字体

  • The font-family property can hold several font names as a “fallback” system. If the browser does not support the first font, it tries the next font. Separate each value with a comma.

    • If the font name has a space in between, should enclose in quotes, e.g., "Helvetica Neue".

    • Helvetica Neue is not a web-safe type, so to do this you would have to license the typeface from a foundry like https://myfonts.com. They usually will allow you to use the type for a monthly fee and give you a CSS @font-face to link it to an external site.

      If you are looking for something quick, easy, and cheap I would suggest a fontstack that relies on Helvetica Neue for supported devices and fallsback on Arial for non-supported devices.

      body {
          font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
      }
      
  • There are two types of font family names:

    • family-name: The name of a font-family, like “times”, “courier”, “arial”, etc.
    • generic-family: The name of a generic-family, like “serif”, “sans-serif”, “cursive”, “fantasy”, “monospace”.

    Start with the font you want, and always end with a generic family, to let the browser pick a similar font in the generic family, if no other fonts are available.

    A sans-serif font is more readable especially on lower-resolution screens.

  • If a font name contains white-space, it must be quoted. E.g., p.a {font-family: "Times New Roman", Times, serif;} when you write an external CSS script to define styles. (Inline styles always use quotes.)

https://www.cssfontstack.com/Courier-New

Monospace

  • Use <tt> (simplest way)

    Some regular text before. This text is monospace text. Some regular text after.

    Some regular text before. <tt>This text is monospace text.</tt> Some regular text after. 
    
  • Use <span style="font-family: monospace"> (more refined control).

    Some regular text before. This text is monospace text using default font. Some regular text after.

    Some regular text before. <span style="font-family: monospace">This text is monospace text.</span> Some regular text after. 
    

    Change monospace font family using <span style="font-family:'Courier New', Courier, monospace">.

    Some regular text before. This text is monospace text using the Courier font. Some regular text after.


中文字体

Two general types

  • TC: Traditional Chinese 繁体中文
  • SC: Simple Chinese 简体中文 But they also support both simple and traditional characters. Specify either would do.
.chinese {
  font-family: "KaiTi";
}
<div class="chinese">你好</div>

Issue: 除了黑体之外,Safari 其余中文字显示全都显示为宋体 (2024-Nov)。Fonts show properly in Chrome though.
Haven’t found a fix yet…

字体测试:华文楷体 (STkaiti)

字体测试:华文行楷 (Xingkai SC)

字体测试:楷体 (Kaiti SC)

字体测试:华文宋体 (STSong)


Use @font-face in CSS

The @font-face rule allows custom fonts to be loaded on a webpage. Once added to a stylesheet, the rule instructs the browser to download the font from where it is hosted, then display it as specified in the CSS.

@font-face needs to be put at the very top, before any CSS.

@font-face {
  font-family: "myFont";
  src: 
    url("myFont.woff2") format("woff2"),
    url("myFont.woff") format("woff");
}

Properties:

  • font-family: This line specifies the name you want to refer to the font as. This can be anything you like as long as you use it consistently throughout your CSS.
  • src specify the paths to the font files to be imported into your CSS (the url part), and the format of each font file (the format part)
    • Each of the url() functions points to a font file that we want to import into our CSS. We need to make sure the paths to the files are correct.
    • The format part in each case is optional, but is useful to declare because it allows browsers to more quickly determine which font they can use.
    • Multiple declarations can be listed, separated by commas.
    • The browser will search through them according to the rules of the cascade, it’s best to state your preferred formats, e.g., woff2, at the beginning.

Now you can use these fonts in your font stacks, just like any web safe or default system font.

Without the rule, our designs are limited to the fonts that are already loaded on a user’s computer, which vary depending on the system being used.

Font file types:

  • .ttf / .otf: truetype / opentype
  • svg: scalable vector graphics
  • .woff and .woff2: Web Open Font Format. Mainstream font types now.

    WOFF2 supports the entirety of the TrueType and OpenType specifications, including variable fonts, chromatic fonts, and font collections.

Check compatability of fonts with operating systems
https://www.cssfontstack.com

Using an online font service

Online font services generally store and serve fonts for you so you don’t have to worry about writing the @font-face code. But most services are not free, with one notable exception of Google Fonts.

  • @import Using a hosted font on an existing server, e.g., Google Fonts.

    The following is an example of using @import to load the Open Sans font, then use it to style elements.

    @import url(//fonts.googleapis.com/css?family=Open+Sans);
    body {
      font-family: 'Open Sans', sans-serif;
    }
    

    A benefit of using a hosted service is that it is likely to include all the font file variations, which ensures deep cross-browser compatibility without having to host all those files ourselves.

  • <link> a stylesheet

    <link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet">
    

Caveats about custom fonts: Custom fonts often cause sites to be slow because the font must be downloaded before it’s displayed.

Install fonts on Mac

Install with the Font Book app.

Do any of the following:

  • In the Font Book app , choose File > Add Fonts to Current User. In the window that appears, double-click the font file.
  • Drag the font file to the Font Book app icon in the Dock, then click Install in the dialog that appears.
  • Drag the font file to the Font Book window.
  • Double-click the font file in the Finder, then click Install in the dialog that appears.

When you install a font, Font Book automatically validates or checks the font you’re installing for errors. Font Book also checks for duplicate fonts.

Font Size

converter

pt point size. A point is about 0.3515 mm .

px pixel size; 16 px = 12 pt = 1em = 100%; use px whenever possible for best screen display;

em roughly the width of an ‘M’ (uppercase) in the current font (it depends on the font used)最大,对应当前字体大小;px 最小;1pt=1.3px.

  • If your font is 11px, then 1em equals 11px.

ex roughly the height of an ‘x’ (lowercase) in the current font (it depends on the font used)

color: red for text colors

background-color: powderblue for background color

Ways to specify colors in html:

  • hexadecimal color codes, e.g., #FF0000 for red or #00FFFF for cyan

  • named colors, provide a more intuitive way to set common colors, like blue, green, or gold.
  • RGB (RGBA, with opacity option alpha) or HSL values.

<img src="img_girl.jpg" alt="Girl in a jacket" width="500" height="600"> insert an image.

  • src Specifies the path/URL to the image.
  • alt Specifies an alternate text for the image, if the image for some reason cannot be displayed.

<img src="img_girl.jpg" alt="Girl in a jacket" style="display: block; margin-right: auto; margin-left: auto; zoom:80%;" /> you could put all style attributes in one quote, property: value pairs are separated by ;.

  • display controls the alignments of html elements. The default value is block or inline.

    Value Meaning
    inline An inline element DOES NOT start on a new line and only takes up as much width as necessary.
    Examples of inline elements: <span>, <a>.
    block A block-level element ALWAYS starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).
    Add a line-break after the element;
    Examples of block-level elements: <div>, <h1>-<h6>.
    inline-block Allows to set a width and height on the element;
    The top and bottom margins/paddings are respected;
    Does not add a line-break after the element, so the element can sit next to other elements;
    One common use for display: inline-block is to display list items horizontally instead of vertically.

<div> defines a division, used as a block container for any other block or inline elementsm including other DIV elements.

Difference from <p>

  • <p> wraps text paragraphs
  • <p> can go in a <div> but the reverse is not true.
  • The major web browsers will render a <p> tag with margin above and below the paragraph. A <div> tag will be rendered without any margin at all.
<!DOCTYPE html>
<html>
<head>
<style>
.myDiv {
  border: 5px outset red;
  background-color: lightblue; 
  text-align: center;
}
</style>
</head>
<body>

<div class="myDiv">
  <h2>This is a heading in a div element</h2>
  <p>This is some text in a div element.</p>
</div>

</body>
</html>

The <a> tag defines a hyperlink, which is used to link from one page to another.

The most important attribute of the <a> element is the href attribute, which indicates the link’s destination.

By default, links will appear as follows in all browsers:

  • An unvisited link is underlined and blue
  • A visited link is underlined and purple
  • An active link is underlined and red
a:link, a:visited {
  color: (internal value);
  text-decoration: underline;
  cursor: auto;
}

id attributes is used to specify a unique id for an html element.

  • point to a specific style declaration in a style sheet

    Style a specifc id using #, then define the CSS properties within curly braces{}. The id name is case sensitive.

    Difference between class and id:

    • class can be used by multiple html elements, while an id name must only be used by one html element within the page.
    • class css is styled with the start of .<class>, whileid starts with #<tag>.
    <!DOCTYPE html>
    <html>
    <head>
    <style>
    #myHeader {
      background-color: lightblue;
      color: black;
      padding: 40px;
      text-align: center;
    } 
    </style>
    </head>
    <body>
      
    <h1 id="myHeader">My Header</h1>
      
    </body>
    </html>
    
  • point to a JavaScript and manipulate the element with the specific id in order to perform some tasks.

    Use the id attribute to manipulate text with JavaScript. JavaScript can access an element with a specific id with the getElementById() method

    <script> 
      function displayResult() {   
        document.getElementById("myHeader").innerHTML = "Have a nice day!"; 
      } 
    </script>
    

<link href="main.css" rel="stylesheet">

  • rel stands for “relationship”, and is one of the key features of the <link> element — the value denotes how the item being linked to is related to the containing document. Possible values:

    • stylesheet

    • icon

      <link
        rel="apple-touch-icon"
        sizes="114x114"
        href="apple-icon-114.png"
        type="image/png" />
      

      Link to an icon. The sizes attribute indicates the icon size, while the type contains the MIME type of the resource being linked. These provide useful hints to allow the browser to choose the most appropriate icon available.

    • preload indicates that the browser should preload this resource.

  • href a URL or path that specifies the location of the linked document.

Center Images

  1. Add HTML:

    img src="paris.jpg" alt="Paris" class="center">
    
  2. Set left and right margin to auto and make it into a block element:

    .center {
      display: block;
      margin-left: auto;
      margin-right: auto;
      width: 50%;
    }
    

class attribute is mostly used to point to a class in a style sheet.

<html>
<head>
<style>
h1.intro {
    color: blue;
}

p.important {
    color: green;
}
</style>
</head>
<body>

<h1 class="intro">Header 1</h1>
<p>A paragraph.</p>
<p class="important">Note that this is an important paragraph. :)</p>

</body>
</html>
  • Multiple classes can be applied to a single element in HTML. Then the classes can be either styled individually using .class_1 and .class_2 or that element could be styled only that contains both of the classes using .class_1.class_2. This is called “multiple class selectors”.

    <style>
      .class_1{
        /* some styles, specify independently */
        font-size: larger; 
        margin-bottom: 35px; 
        background-color: lightgreen; 
      }
        
      .class_2{
        /* some styles */
        color: red; 
      }
        
      .class_1.class_2{
          /* or specify simultaneously */
       	  /* note that there is no space between the class names */
      }
    </style>
        
    <body> 
      <!-- 调用两个class的时候用空格隔开 -->
      <p class="class_1 class_2"> Hello there </p>
    </body>
      
      
    

CSS

CSS is the language we use to style a Web page.

A CSS rule consists of a selector and a declaration block. Declaration block enclosed by {}.

/* This is a comment */ defines a comment in CSS.

E.g. all <p> elements will be center-aligned, with a red text color:

/* This is a comment */
p {
  color: red; /* This is a property: value definition; seperated by semicolons */
  text-align: center;
}

CSS selectors are used to “find” (or “select”) the HTML elements you want to style. Can select elements based on name, id, class, etc.

Selector Example Example description
#id #firstname Selects the element with id=”firstname”
.class .intro Selects all elements with class=”intro”
element.class p.intro Selects only <p> elements with class=”intro”
* * Selects all elements
element p Selects by element names. This selects all <p> elements.
element,element,.. div, p Selects all <div> elements and all <p> elements.
Elements 之间用逗号隔开。

Type Selector

Syntax:

element { style properties }
  • element name based on the element name.

    span {
      background-color: red;
    }
    

    highlight all <span> elements in red.

  • element1, element2 grouping selector, separated by comma.

    /* define style for h1, h2, and p elements */
    h1, h2, p {
      text-align: center;
      color: red;
    }
    

ID Selector

An ID selector selects an element based on its ID attribute. For example, #toc will select the element that has the ID toc. Please note that this selector only works if the value given in the selector matches the element’s ID attribute exactly. ID is case-sensitive.

Syntax:

#idname { style properties }
  • id uses the id attribute of an HTML element. To select an element with a specific id, write a hash (#) character, followed by the id of the element.

    #para1 {
      text-align: center;
      color: red;
    }
    

    Example: Change the color and alignment of the element with the id hubspot.

    <head>
    #hubspot {
      color:orange;
      text-align:right;
    }
    </head>
      
    <body>
    <h1 id = "hubspot"> #id selector</h1>
    <body>
    

Class Selector

Syntax

.classname { style properties }
  • class To select elements with a specific class, write a period (.) character, followed by the class name.

    <head>
    .center {
      text-align: center;
      color: red;
    }
      
    /*  only <p> elements with class="center" will be red and center-aligned: */
    p.center {
      text-align: center;
      color: red;
    }
    </head>
      
    <body>
    /*  <p> element will be styled according to class="center" and to class="large": */
    <p class="center large">This paragraph refers to two classes.</p>
    </body>
    
  • Pseudo-class Selector A pseudo-class selector applies CSS to a selected element or elements only when in a special state. For example, :hover will only style an element when a user hovers over it.

    Other common examples are :active, :visited, and :invalid.

    The syntax of a pseudo selector is:

    selector:pseudo-class { style properties }
    

    Example: change the color of links that

    • the user has already visited: green.
    • the user hasn’t visited: blue.
    • when a user hovers over them: fuschia color
    <head>
    a:link {
      color: blue;
    }
    a:visited {
      color: green;
    }
    a:hover {
      color: fuschia;
    }
    </head>
      
    <body>
    <p>So you've already visited <a href="http://hubspot.com">blog.hubspot.com</a>. Why not check out our home site at <a href="http://blog.hubspot.com">hubspot.com</a>?</p>
    </body>
    

Group Selector

You could combine different types of selectors into a selector list. To create a selector list, you just have to list multiple selectors and separate them by commas.

h2, .spacious {
  color: green;
}

You can also place selectors on their own line if that makes the code easier to read.

h2, 
.spacious {
  color: green;
}

Attribute Selector

An attribute selector selects all elements that have a given attribute or an attribute set to a specific value.

a[target] ([attribute]): Selects all <a> elements with a target attribute:

a[target] {
  background-color: yellow;
}

a[target="_blank"]([attribute="value"]): Selects all <a> elements with a target="_blank" attribute:

a[target="_blank"] {
  background-color: yellow;
}

[title~="flower"]([attribute~="value"]): Selects all elements with a title attribute that contains a space-separated list of words, one of which is “flower”.

[title~="flower"] {
  border: 5px solid yellow;
}

The example above will match elements with title=”flower”, title=”summer flower”, and title=”flower new”, but not title=”my-flower” or title=”flowers”.

Universal Selector

  • * selects all HTML elements on the page.
/* affect every HTML element on the page: */
* {
  text-align: center;
  color: blue;
}

Case Sensitiveness

In short, some are case-sensitive, some are not.

Sensitive:

  • Selectors. The HTML elements, classes, and IDs that you reference in your CSS file are case-sensitive.

    For example, if you have an element with id="example", you must reference it in your CSS file as #example and not #Example.

Insensitive:

  • Properties.

    E.g., background-color and BackGround-COLOR are considered the same. That being said, it is recommended to use lowercase for property names to maintain readability and consistency.

  • Property Values. In general, property values are case-insensitive, except for font names and URLs.

    So, redand RED are considered the same color.

    However, the values of the font-family, url, and attr are case-sensitive.


Style Sheet

There are three ways of inserting a style sheet:

  • External CSS — by using a <link> element to link to an external CSS file
  • Internal CSS — by using a <style> element in the <head> section
  • Inline CSS — by using the <style> attribute inside HTML elements
  1. With an external style sheet, you can change the look of an entire website by changing just one file!

    Each HTML page must include a reference to the external style sheet file inside the <link> element, inside the head section.

    <!DOCTYPE html>
    <html>
    <head>
    	/* example of external CSS */
    	<link rel="stylesheet" href="mystyle.css">
    </head>
    <body>
       
    <h1>This is a heading</h1>
    <p>This is a paragraph.</p>
       
    </body>
    </html>
    
  2. An internal style sheet may be used if one single HTML page has a unique style.

    The internal style is defined inside the <style> element, inside the head section.

    <!DOCTYPE html>
    <html>
    <head>
      <style>
        body {
          background-color: linen;
        }
       
        h1 {
          color: maroon;
          margin-left: 40px;
        } 
      </style>
    </head>
       
    <body>
       
    <h1>This is a heading</h1>
    <p>This is a paragraph.</p>
       
    </body>
    </html>
    
  3. An inline style may be used to apply a unique style for a single element.

    <!DOCTYPE html>
    <html>
    <body>
       
    <h1 style="color:blue;text-align:center;">This is a heading</h1>
    <p style="color:red;">This is a paragraph.</p>
       
    </body>
    </html>
    

Developer Tool

Right-clicking Inspect Element is your good friend. Say you say on a website something really appealing, and you want to use the same styling in your website, right click and see its CSS.

  • One neat thing about the developer tools is that you can click and temporarily edit the CSS properties in this very window and simlutaneously see the changes take effect on the page. These edits only happen in your browser, so nothing in your R Markdown document will change (in fact, your edits will be lost as soon as you refresh the page in your browser), but editing here is a fast way to test out any CSS ideas.

  • Another thing you can do is to pull up your site and change the attributes using the developer tool. It allows you to have a sense of how your site would look like after the changes have taken effect.

    Note that these edits only happen in your browser, so nothing in your Rmd document will change (in fact, your edits will be lost as soon as you refresh the page in your browser), but editing here is a fast way to test out any CSS ideas.

Change color

If you don’t see the color changing on your site, then it means you either have the wrong selector OR it means that something else is overriding your color choice (a strikethrough line means sth is overriden). You can force it to go with your choice by adding !important to the end of line you added, right before the ;.

.navbar {
  background-color: #fcfcfc !important;
}

Footnote

Markdown does not have explicit footnote support, so I use HTML* instead. Personally, I prefer using * or for footnote markers, but you can use numbered[1] markers if you really want.

* This is the footnote text
[1] Number them any way you like

Markdown does not have explicit footnote support, so I use 
HTML<sup>*</sup> instead. Personally, I prefer using `*` or `†` for 
footnote markers, but you can use numbered<sup>[1]</sup> markers if 
you really want.

<sup>*<sub> This is the footnote text</sub></sup>  
<sup>[1]<sub> Number them any way you like</sub></sup>

Recommended practice:

  1. Use <sup>1</sup> for the footnote references. Using numbers is a lot easier to remember than a list of symbols, and looks nicer, since their heights will always be equal (as opposed to * and , for example).
  2. Use a horizontal line to separate the footnotes section, making it clear that it’s not just a continuation of the body.
  3. Use a <sup> tag to render the footnote definitions in small text, again making it clear that it’s a footnote section. Don’t use <sub> as it won’t wrap as nicely.
  4. Use a second <sup> tag for each number in the footnote section, again making it clear that it’s a footnote definition and not part of the body.
  5. Use double spaces to separate footnote lines, so that the definition numbers line up.

In typography, a reference relating to the main body of text, positioned at the bottom of the page. Footnotes are referenced by certain symbols (*, , , etc.), letters, or numbers, most often in superscript form.

The most common sequence of footnote reference marks is: 1. asterisk (*), 2. dagger (), 3. double dagger (††), 4. paragraph symbol (), 5. section mark (§), 6. parallel rules (||), 7. number sign (#).

If more are required, they can be doubled up: double asterisks (**), double single daggers (††), double double daggers (††††), etc. However, when many footnotes are used, it is more practical to use consecutive numbers to identify each footnote.

Typesetting:

  • A footnote begins on the same page as its reference call, but it may be carried over to the bottom of successive pages.

  • A short rule or additional space should separate the footnote from the text.

  • The first line of each footnote is normally slightly indented.
  • Point sizes for footnotes are usually 7- or 8-point, smaller than the text size.

Cross references

Link to the same document

  • If it is a heading

    [click on this link](#my-multi-word-header)
      
    ### My Multi Word Header
    
  • If it is common text

    <a name="tag-here">Common Text</a>
    [link text](#tag-here)
    

Bullet list

<ol style="list-style-type:lower-alpha; line-height:20px">
	<li>Coffee</li>
	<li>Tea</li>
	<li>Milk</li>
</ol>
<!-- alternatively-->
<ol type="a">
	<li>Coffee</li>
	<li>Tea</li>
	<li>Milk</li>
</ol>

Shows the following list:

  1. Coffee
  2. Tea
  3. Milk

Define your own label, e.g., add parentheses around numbering.

References: https://stackoverflow.com/a/76027284/10108921

@counter-style paren-lower-alpha {
  system: extends lower-alpha;
  suffix: ") ";
}
@counter-style paren-decimal {
  system: extends decimal;
  suffix: ") ";
}
@counter-style paren-lower-roman {
  system: extends lower-roman;
  suffix: ") ";
}
[type="pa"] {
  list-style: paren-lower-alpha;
}
[type="p1"] {
  list-style: paren-decimal;
}
[type="pi"] {
  list-style: paren-lower-roman;
}

Parenthesized decimal 1):

<ol type="p1">
    <li>Sublist first.</li>
    <li>Sublist second.</li>
</ol>

show the following

  1. Sublist first.
  2. Sublist second.

Parenthesized letter a):

<ol type="pa">
    <li>Sublist first.</li>
    <li>Sublist second.</li>
</ol>

show the following

  1. Sublist first.
  2. Sublist second.

Parenthesized roman i):

<ol type="pi">
    <li>Sublist first.</li>
    <li>Sublist second.</li>
</ol>

show the following

  1. Sublist first.
  2. Sublist second.

Nested bullet list. <ol> (<ul>) is a child of the <li> it belongs to.

<ol>
<li> Accept the invitation from FactSet. </li>
<li>  Whitelist your IP address. </li>
<li>  Install Microsoft ODBC SQL driver. </li>
<li>  Install Azure Data Studio to connect to the SQL database.
   <ol type="pa"> 
   <li> Alternatively, could use Python Programmatic Access. Need to install `pyodbc` to manage the connection. </li>
   <ol>
</li>
</ol>
  1. Accept the invitation from FactSet.
  2. Whitelist your IP address.
  3. Install Microsoft ODBC SQL driver.
  4. Install Azure Data Studio to connect to the SQL database.
    1. Alternatively, could use Python Programmatic Access. Need to install `pyodbc` to manage the connection.

Unordered nested bullet list:

<ul>
  <li>Coffee</li>
  <li>Tea
    <ul>
      <li>Black tea</li>
      <li>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>
  • Coffee
  • Tea
    • Black tea
    • Green tea
  • Milk

line-height:120% 行间距

Values Meaning
number A number that will be multiplied with the current font-size to set the line height
length A fixed line height in px, pt, cm, etc.
% A line height in percent of the current font size

Tables

Each table cell is defined by a <td> and a </td> tag, stands for table data.

Table headers use <th> tag instead of the <td> tag.

Each table row starts with a <tr> and ends with a </tr> tag, stands for table row.

  • Add border-bottom to table row using style="border-bottom: 1pt solid black;"

    3 arguments: <border-width> <border-style> <border-color>.

    Add <table style="border-collapse: collapse;"> to your table rule when you want all borders for your table. Otherwide, tables will have double-lined borders.
    The default behavor for html tables is no borders. If you specify individual borders mannually, don’t need border-collapse: collapse then.

    Col 1Col 2Col 3
    A1B1C1
    A2B2C2
    A2B2C2
    <table style="table-layout:fixed; width:60%; margin-left: auto; margin-right: auto;">
      <tr style="border-bottom: 1pt solid #D3D3D3;"><th>Col 1</th><th>Col 2</th><th>Col 3</th></tr>
      <tr><td>A1</td><td>B1</td><td>C1</td></tr>
      <tr><td>A2</td><td>B2</td><td>C2</td></tr>
      <tr><td>A2</td><td>B2</td><td>C2</td></tr>
    </table>
    

<table> attributes

  • border-spacing property sets the distance between the borders of adjacent cells.
  • max-width: 100%; white-space: nowrap; prevent the text from wrapping.
  • margin-left: auto; margin-right: auto; centers the table.
  • table-layout: auto|fixed|initial|inherit; property defines the algorithm used to lay out table cells, rows, and columns.
    • auto: Default value. Browsers use an automatic table layout algorithm.

      The browser analyzes all cells in a column and calculates the optimal width for each column dynamically based on the longest unbreakable content.

      Auto table layout dynamically adjusts column widths based on content, offering flexibility for diverse data lengths but can lead to less predictable table dimensions.

    • fixed sets a fixed table layout algorithm. This makes table render fast.

      The table and column widths are set by the widths of table and col or by the width of the first row of cells. Cells in other rows do not affect column widths.

      If no widths are present on the first row, the column widths are divided equally across the table, regardless of content inside the cells.

      On large tables, users will not see any part of the table until the browser has rendered the whole table. So, if you use table-layout: fixed, users will see the top of the table while the browser loads and renders rest of the table.

  • initial: Sets this property to its default value.
  • inherit: Inherits this property from its parent element.

<td>/<th> attributes for cells and headers

  • <td><div style='width: 150px;'>Text to break here</div></td> let you fix the width of the column containing the cell at 150px.

    • If a percentage is used, then it means the proportion of its parent element.
  • colspan=2 span the width of more than one cell or column.

    • center the text <td colspan="2" style="text-align:center;" >Center on two cols</td>
  • rowspan=2 span the height of more than one cell or row.

    不能放在 style 里面,必须以 property-key=value 的形式赋值,行数可以放在引号内 (rowspan="2"),也可以不要引号。

  • text-align: center | left | right

    • By default, the content of <th> elements are center-aligned and
    • the content of <td> elements are left-aligned.
  • vertical-align: top | bottom | middle vertical alignment

  • padding Cell padding is the space between the cell borders and its content.

    By default the padding is set to 0. That is, cells are only as large as their content requires by default.

  • border-spacing Cell spacing is the space between each cell.

    By default the space is set to 2 pixels.

Change column width

<colgroup> specifies a group of one or more columns in a table for formatting.

Set each col to be 250px wide.
Put the <colgroup>...</colgroup> below <table> and above table data <tr>.

<colgroup style="width: 150px;">
	<col>
  <col>
	<col>
</colgroup>
Col 1Col 2Col 3
A1B1
Name: Anna Fitzgerald
Job Title: Staff Writer
Email address: example@company.com
A2B2C2
A2B2C2

Set width for one column to be 300px.

<colgroup>
	<col>
  <col>
  <col style="width:300px">
</colgroup>
Col 1Col 2Col 3
A1B1
Name: Anna Fitzgerald
Job Title: Staff Writer
Email address: example@company.com
A2B2C2
A2B2C2

Zebra stripes

In css, specify the following properties.

tr:nth-child(even) {
  background-color: rgba(150, 212, 212, 0.4);
}

th:nth-child(even),td:nth-child(even) {
  background-color: rgba(150, 212, 212, 0.4);
}

border property works on table, th, and td elements:

  • To avoid having double borders, set the CSS border-collapse property to collapse.

  • border: width style color; it is a shorthand for the following three CSS properties:

    The border property may be specified using one, two, or three of the values listed below. The properties will be automatically recognized and matched with corresponding properties.

    Separate by space, the order does not matter.

Try html table yourself

Table with headers:

Company Contact Country
Alfreds Futterkiste Maria Anders Germany
Centro comercial Moctezuma Francisco Chang Mexico

Table without headers:

submission March 15
Feedback April 15
  • To center a table, add margin-left:auto; margin-right:auto; to the style attribte in the <table> tag.

Code

  • Code blocks: the <pre> and <code> tags.

    The <pre> tag is a block level element that defines preformatted text. It preserves both spaces and line breaks in the code, making it ideal for displaying computer code. The content inside is displayed in the browser’s default monospace font.
    The <code> tag, on the other hand, is used for inline code within a paragraph or line of text.

    An example:

    <pre>
    <code>
    function hellowWorld(){
    	print ("Hello, World!")
    }
    </code>
    </pre>
    
  • Inline code: <code>


Q: Sometimes a line is very long, how to wrap up code in code blocks?

A: Use CSS to style it as follows.

<style>
  code {
    white-space : pre-wrap !important;
    word-break: break-word;
  }
</style>

white-space : pre-wrap soft-line wrap inside code blocks.

word-break: break-word will avoid breaking the words across lines.

A quick workaround is to quote your codeblocks.

Code inside quote looks like:

this line is very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long

Use the following code:

> ```this line is very long```