preface

HTML is too fragmented, and over time, some of the details will be forgotten, so I want to summarize the memo in this article.

If this article is out of date or contains error information, please correct it.

Basic concept correlation

The element

1. What is the difference between inline and block elements?

Multiple inline elements are placed side by side, exceeding line breaks. Width, height, and upper and lower margins cannot be set

Inline elements cannot contain block elements, otherwise rendering errors will result in different results for each browser.

<span>Hello</span>

<style>
  .inline {
    padding: 4px;
    margin: 8px;
    height: 50px;
    width: 80px;
    line-height: 80px;
    border: 1px # 000 solid;
  }
</style>
Copy the code

As shown in figure width, height, margin-top and margin-bottom are invalid

Even if the block element is not wide enough, it will occupy a single line. Vertical-align is not supported

<div class="block">World</div>
<style>
  .block {
    width: 100px;
    height: 100px;
    line-height: 80px; //picture2
    border: 1px # 000 solid;
    margin: 10px;
    padding: 10px;
  }
</style>
Copy the code

There is also a special type, inline-block elements, which are usually replacement elements (more on that next)

It is inline, but you can set width, height, margin-top, margin-bottom

<style>
  .inline-block {
    display: inline-block;
    padding: 4px;
    margin: 8px;
    height: 50px;
    width: 80px;
    line-height: 80px;
    border: 1px # 000 solid;
  }
</style>
<span class="inline-block">Hello</span>
Copy the code

2. What are replacement elements and non-replacement elements

The replacement element is usually an empty element, and after the HTML code executes, the replacement element will be replaced with something else, whose content is not affected by the current document style sheet, and CSS cannot style the replacement content.

  • Common replacement elements: img, input only image type, video, iframe, textarea, etc

  • These are replaced in specific cases: Canvas, Audio, Option, Object

Replaceable elements can set the style of the replacement element, limit the width, height and position of its content display box, and set the content with the following two properties:

  • Contain, cover, None, fill, scale-down
  • Object-position: The position of the element to be replaced in the box

3. Important global properties

Common attributes:

  • Title: Hover over, a prompt will be displayed.

  • Data -* : user-defined attribute type

  • Accesskeys: Select a shortcut key for an element. You are advised to use javascript to set the shortcut key depending on the browser implementation.

  • Contenteditable: Whether content is editable, supported by the latest browsers and mobile

  • Spellcheck: Whether spellcheck is enabled, supported by the latest browser

  • Slot and IS: used to create template elements (custom element tags). For details, see Using templates and slots

  • Lang: language support

  • Nonce: indicates the content security policy

  • TabIndex Uses the TAB shortcut to select a sequence

  • Draggable: Whether to enable the drag and drop Api

  • Inputmode: Sets the inputmode (virtual keyboard type). It can also be used for elements that are contenteditable true

For rich applications and accessibility:

  • Aria -* : Provides support for barrier-free access, including multiple parts
  • Role: Sets the type of the element, for example<div role="button">

4. Muddle global events

The mouse events

  • Onmousedown and onmouseup: Listen for mousedown and release
  • Onclick and ondblClick: Triggered after onMouseDown and onMouseup, listens for mouse clicks and double-clicks
  • Onauxclick: Triggers an event using a non-(primary) left-click (experimental feature), which can be implemented using Mouseevent in javascript
  • Oncontextmenu: listens for the right-click menu and disables it if false is returned
  • Onmouseenter and onmouseOver: Mouse entry events. The difference is that mouseEnter does not support bubbling. Mouseover bubbles, so mouseEnter is triggered only when entering, and mouseover is triggered when entering child elements
  • Onmousemove: mouse movement event
  • Onmouseleave and onmouseout: Mouse away events. The difference is that mouseleave does not support bubbling and is triggered when you leave an element and all its descendants. Mouseout bubbles when you leave the offspring of the element but still fires
  • Onwheel: scroll event, different from onScroll, for scroll
  • Onscroll: content scroll event, different from onwheel for content

Element specific correlation

1. Prevent label A from redirecting by default

  • onclickIn the eventreturn false
  • href="javascript:;".href="javascript:void(0)"
  • href="#"Default jump back to the top,href="##"Resolve the jump back to the top, but still modify the URL
  • usejavascriptBlocking default events
    <a href="http://www.baidu.com" id="link"> Click Me </a>
    <script type="text/javascript">
        const a = document.getElementById('link')
        const stopDefault = (e) = > {
            if ( e && e.preventDefault ) {
                e.preventDefault();
            } else {
                window.event.returnValue = false; / / compatible with IE
            }
        }
        a.onclick = (e) = > {
            stopDefault(e);
        }
    </script>
    Copy the code

2. A label target=”_blank” security policy

First, review the target attribute of the A tag:

  • _blank opens a new page
  • _top Open page of the current top-level frame
  • _parent The current parent frame is open
  • _self The current frame is open

When we open page B with _blank on page A, page B can access the window object of page A through window.opener. If there is malicious code on page B, page A can be modified, and phishing attacks may be carried out

So we set the ref attribute for the A tag:

<a ref="noopener"></a>
Copy the code

After noopener is set, window.opener of page B will be null, which improves security and performance on the one hand.

After page A is opened with _blank on page B, if page B executes high load code, it will spread to page A and cause stagnation. Using 'noopener' will cut off the connection without affecting each other.Copy the code

On the other hand, we also need to optimize for the existing browser (noopener is not supported):

<a href="/ 123" onclick="return openURL('https:\/\/www.baidu.com')">111</a>
<script>
  function openURL(url) {
    var newTab = window.open();
    newTab.opener = null;
    newTab.location = url;
    return false;
  }
</script>
Copy the code

In addition, there are several other properties we should know:

  • Noreferrer: HTTP sends the Referer header by default, which contains page A information, via settingnoreferrerYou can disable sendingRefererTo prevent page B from tracing back to page A, exposing user privacy
  • Nofollow: When we link to the third party platform, we can tell the crawler that there is no need to continue tracing, so as to optimize SEO.

Best practices:

<a href="https://an.evil.site" target="_blank" rel="noopener noreferrer nofollow">Enter an "evil" website</a>
<script>
  function openURL(url) {
    var newTab = window.open();
    newTab.opener = null;
    newTab.location = url;
    return false;
  }
</script>
Copy the code

3. A Tag Download attribute

The Download property allows you to set the recommended name of the resource to download

Condition: codomain case is executed

In addition, the Download attribute only supports Google and Firefox browsers, not Internet Explorer. In the Internet Explorer environment, pictures and TXT documents are preview effects

<a href="'+fileurl+'" download="'+filename+'">FileName is the name of the file to be downloadedCopy the code

HTML5

1. The semantic

Meaning:

  • Code structure: Provides good content structure without CSS
  • SEO: crawlers rely on tags to determine the weight of keywords, so they can establish good communication with search engines and help crawlers capture more effective information
  • Improve user experience: For example, title and Alt can be used to explain names or image information, and label can be flexibly used.
  • Easy for team development and maintenance: Semantematization makes your site code more readable and allows other developers to better understand your HTML structure and reduce differentiation.
  • Easy accessibility for reading and parsing of other devices: screen readers, blind readers, mobile devices, etc., rendering web pages in a meaningful way.

Semantic tags:

The label describe
header The head area
footer The tail region
nav navigation
section Chapter, area
article The content area
aside Sidebar content
detailes Describes the details of a document or part of a document
summary The title that contains the Details element
dialog dialog

Defect:

  • Error nesting, such as placing div inside p can cause rendering problems, and is very stealthy, p > article section

  • Need to adapt to older browsers (do not support new tabs)

    The role attribute is used to replace the semantic tag when old IE compatibility is not required. See ARIA.

2. Enhance forms

Input supports more types:

Email, tel, search, image(submit), url, number(support Max,min,step),range(Max,min,step),time, datetime(deprecated), color(IE not support)

The new element

output

attribute

  • For: Can point to multiple form control ids that affect output
  • Form: If output is not in the form, the form needs to be set. The form that displays the result
  • Name: indicates the attribute name
<form oninput="result.value=parseInt(a.value)+parseInt(b.value)">
    <input type="range" name="b" value="50" /> +
    <input type="number" name="a" value="10" /> =
    <output name="result"></output>
</form>
Copy the code

Keygen (deprecated)

datalist

With options, set the input’s list of options, binding the input’s list attribute to the datalist ID

<label for="ice-cream-choice">Choose a flavor:</label>
<input list="ice-cream-flavors" id="ice-cream-choice" name="ice-cream-choice" />

<datalist id="ice-cream-flavors">
    <option value="Chocolate">
    <option value="Coconut">
    <option value="Mint">
    <option value="Strawberry">
    <option value="Vanilla">
</datalist>
Copy the code

The new attribute

  • Placehoder: A default message in the input box, which disappears after a user enters the placehoder
  • Required: Requires whether the input is allowed to be null
  • Pattern: The value is a regular expression used to validate the value of the input element
  • Min and Max: Sets the minimum and maximum values of elements
  • Step: Specifies a valid number interval for the input field
  • Height and width: The height and width of the image used for an input of type image.
  • Autofocus: Specifies whether the page is automatically focused when it loads
  • Multiple: input Specifies whether multiple values can be selected.

3. Web Storage

Suitable for storing small data

Type:

  • LocalStorage Local permanent storage
  • SessionStorage Close the browser session window and delete it

Similar APIS for blocking (synchronous) methods:

  • SetItem (key,value) to save data.
  • Read data: localstorage.getitem (key);
  • Delete a single item: localstorage.removeItem (key);
  • Delete all data: localstorage.clear ();
  • Get the index key: localstorage.key (index);

3. Other new functions

  • New parser

    HTML5 has a new parser that supports direct use of SVG and MathML

    Parsing takes place on a new thread without blocking UI rendering

    On the other hand, the new documentation provides a more detailed description of HTML5 functionality, which will be more consistent across browsers

  • Websocket two – end instant messaging solution, new protocol

  • Audio and video media elements

  • Canvas and SVG 2D/3D graphics drawing

  • Drag and drop API

  • geolocation

  • The Web Worker invokes additional threads

  • WebRTC communication solution, instant video voice solution

  • IndexedDB is a browser-built database that stores large amounts of data

  • HistoryAPI

  • requestAnimationFrame

  • Calling the Camera

  • fileReader

CSS

1. What is cascading context?

See cascading context for details

Q&A

HTML

Document mode docType

  • Weird mode Without a docTYPE declaration will enter weird mode, IE5.5 as the standard execution browser
  • The quasi-standard pattern declares docTypes as transitions or framesets, and most features are resolved according to the standard (standard pattern is now all used in the specification)
  • The standard mode is declared in strict or HTML5

Modern browsers basically use HTML5 rules for document parsing:

<! DOCTYPEhtml>Represents the use of HTML5 rule parsingCopy the code

If you ignore document declarations, known as docTypes, weird patterns can have a number of effects:

  • The box model in weird mode uses border-box instead of content-box, where element width = content width +border+padding
  • Default inline-block in weird modevertical-alignAlign to bottom and standard mode to baseline
  • Some attributes of fonts in table elements in weird mode are not inherited, such as font size
  • The width and height can be set for non-replacement inline elements in weird mode
  • In weird mode, percentage height can be used, but in standard mode, height must be explicitly declared in the parent element
  • In weird mode, element content overflows will automatically resize the box to fit, exceeding will be considered an extension, and in standard mode element content overflows visible: visible

You can use javascript to determine which mode the browser is currently executing:

  • “BackCompat”: Document in weird mode
  • “CSS1Compat”: The document is not in weird mode, which means the document is in standard mode or quasi-standard mode
document.compatMode == "CSS1Compat" ? "Currently in standard mode." : "Currently in promiscuous mode.");
Copy the code

CSS

Priority order

  • If the priority is the same, the style that appears last is selected. (The lower of the row with high weight, cover the upper)
  • Inline style! Important > External style! Important > Inline style > [id > class > tag]
  • Wildcard selector * with weights of 0 > inherited styles have no weights
  • When the number of tags or classes is too high, reaching an overflow increases priority.

inheritance

  • Inheritable properties: FONT, text, table related, list related, color, visibility, cursor
  • Non-inheritable attributes:
    • Box model correlation (display, margin, border, etc.),
    • Background background – *
    • Locate the position
    • Vertical-align: align the text vertically
    • Text-decoration: specifies decorations to be added to text
    • Text-shadow: text shadow effect
    • White-space: processing of whitespace
  • Non-inheritable styles: border, padding, margin, width, height
  • The inherit property value indicates the value of the parent element, which can be promoted or inherited by uninheritable elements
  • The all attribute name allows you to set all elements, all attribute values, revert(user agent), inherit(inheritance), Initial (initial), and unset

Meaning of different values of line-height

  • Line-height is inherited, but the child inherits the computed value of the parent.

  • Line-height Specifies the value and meaning

    • Normal depends on the user agent and defaults to about 1.2
    • The number depends on the font size of this element, resulting inFont * Number(recommended)
    • Length, in units of em, may yield indeterminate values
    • Percentage, which is related to the font size of the element itself, and the end result, like EM, produces an indeterminate value

Both em and percentage values are computed against font size to produce the PX value, which is then inherited by the quilt element.

Font-size :14px; Height: 1.5em, then the child element’s height is 21px

The numeric value itself is the computed value, and the numeric value itself is inherited.

Sample code:

<style>
  div {
    outline: # 777 1px solid;
    font-size: 16px;
  }
  div h1 {
    color: # 948136;
    font-size: 30px;
  }
  div p {
    font-size: 2rem; /* 36px */
  }
  .em {
    line-height: 1.5 em; /* Parent element font 16px*1.5=24px */
  }
  .number {
    line-height: 1.5; /* Child element font 30px*1.5 */
  }
  .percent {
    line-height: 150%; /* Parent element font 16px*1.5=24px */
  }
</style>
Copy the code

Tips: For accessibility, use 1.5 as the line-height value

HTML/CSS

White space between inline-block elements

This is a common question, but the actual reason is that the inline-block element exists as an inline element, on the same line as the blank text.

For editor beautification, code formatting, etc., Spaces/line feeds between elements are kept.

Common elements: inline-block div, img, input

<div>
____<img>
____<img>
<div>
Copy the code

The resulting img or inline-block divs will have white space between them

Treatment methods:

  • Compress the code to remove white space
    <div><img/><img/></div>
    Copy the code
  • Parent element font size: 0 This method also requires a separate font size for the child element
  • Margin set negative value, offset space (so far the following reference to Zhang Xinxu)
  • No closing label (error may occur)
    <div class="space">
        <a href="# #">melancholy<a href="# #">detachment<a href="# #">The blood</div>
    Copy the code
  • Modify letter-space and word-space with margin

Refer to the article

Target = “_ blank” hidden bug behind

The Hidden Dangers You Have Never Noticed: Target = “_blank” and “opener”

Do you know what a docType is and what a document mode is