Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the HTML/CSS/JS coding specifications?

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the HTML/CSS/JS coding specifications". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what HTML/CSS/JS coding specifications have.

1. HTML coding specification 1. Img tags should write alt attributes

According to the W3C standard, the img tag should write the alt attribute, and if not, write an empty one. But it is generally necessary to write something with content, according to the meaning of the picture, because alt is the text that is displayed when the picture cannot be loaded. The following is not a good way to write:

ABC Company Logo

A better way to write:

ABC Company

There is no need to tell the user that it is a Logo, just tell it that it is ABC Compay. Another example is:

User Portrait

Can be changed to:

Bolynga Team

If the picture cannot be displayed, the user's name is directly displayed.

Some people just write an empty alt when they are lazy, but they still have to write it in some important places. After all, it is good for SEO.

two。 Do not write a closed label for a single label

Why? Because it is useless to write, it also shows that you do not understand the html specification, we are not writing XHTML. Common single tags are img, link, input, hr, br, which are not well written as follows:

It should be changed to:

If you write jsx templates in React, it requires that every tag be closed, but it is never native html.

3. Custom properties should start with data-

The non-standard attributes you add should start with data-, otherwise W3C validator will consider it non-standard, as follows:

It should be changed to:

4. Td should be in tr, li should be in ul/ol.

It is written in the following bad ways:

More often, td is not written in tr:

If you don't write properly, some browsers will correct it for you, but some may not be so lucky. Because the standard does not say what to do if the writing is not standardized, each browser may have its own way of dealing with it.

5. The direct child element of ul/ol can only be li.

Sometimes you may write a div or span directly in ul, thinking it's okay:

123 a b

It's not standard to write this way, too. You can't write span,ol directly in ol. Span,ol is a list, and its child elements should be display: list-item, and suddenly a span pops up, how you want the browser to deal with itself. So non-standard writing will lead to different performance in different browsers.

Similarly, the direct child element of tr should be td, so if you write tr in td, it will be a mess.

6. There should be a title tag in the section

If you use the section/aside/article/nav tag, you need to write a title tag such as h2/h3/h4 in it, because these four tags can be divided into chapters, they are all separate chapters, and you need to have a title. What if there is no title in the UI? Then you can write a hidden title tag, if for SEO purposes, you can not directly display: none, but to use some special processing, such as the next set of a hidden-text class:

.hidden-text {position: absolute; left:-9999px; right:-9999px} Listing Detail 7. Enhance SEO with section tags

The advantage of using section is that it can be divided into chapters, as follows:

Listing Detail House Infomation LOCATION

BUILDING

Listing Picture

It will be outline's outline like this:

Listing Detail

House Infomation

LOCATION

BUILDING

Listing Picture

We can experiment with html5 outliner, and we can see that we have used multiple H2 tags willfully, which is illegal in html4.

8. Block-level elements cannot be used in inline elements

For example, the following words are illegal:

The a tag is an inline element with a div tag inside it, which may cause the a tag not to be clicked properly. Or span contains div, in which case you need to explicitly set display to block for the inline element, as shown in the following code:

That's normal.

9. Every page should be written

Set the rendering mode of the page to standard mode. What happens if you forget to write it? Forget to write will become a weird mode, weird mode of rendering a lot of things will be different, weird mode input/textarea default box model will become border-box, the document height will become the height of the visual window, get the height of the window is not the desired document height. Another difference is that the parent container line height will not affect the child elements in weird mode, as shown in the following code:

In standard mode, there will be some space below the div, while in weird mode it will. This reminds us that we need to add it at the top when writing mail templates, because we write html fragments when developing mail templates locally, and without this, it will become a weird mode.

10. To write an email template with a table layout

Due to the variety of mail clients, you do not know what the user is using to read the mail, it may be the web mailbox, or the gmail/outlook/ NetEase mailbox master and other clients. There are a variety of clients and support for html/css, so we cannot use advanced layouts and typesetting, such as flex/float/absolute positioning. Using a more rudimentary table layout can achieve the best compatibility and scalability.

In addition, the mail template can not write media queries, can not write script, can not write outreach style, these will be filtered out by the e-mail client, the style must be inline style, you can first write into outreach, and then use some tools to help you generate inline html.

After writing the actual test, you can use QQ Mail to send, it supports sending text in html format, after sending it, open it in different clients to see if there are any problems, such as mobile phone client, computer client, and browser.

Since you don't know whether the user opens it with a mobile phone or a computer, you can't write down the width of the email, but 100% is not good either. It may look too big on the PC screen, so you can generally write:

Content 1 content 2

The outermost table is 100% wide, and the inner table has a max-width:600px, which is centered relative to the outer table. The maximum width is 600px on PC and 100% on mobile clients.

However, some clients, such as older outlook, do not recognize the properties of max-width, resulting in too wide on PC. But there is no way to do this, because we can't just write down the width or it will slide left and right on the phone, and we can't write methods like script to judge ua. Therefore, it is not compatible with older versions of outlook.

11. Html should be concise and do not cover too many layers

Need to set a lot of layers, there are generally two cases, one is not very good at cutting, need to set a lot of layers to maintain typesetting, the second is to cut the picture, but the UI is disassembled too fine. Like the following layout:

I would write like this:

Because it is a list, ul/li is used as a container on the outside, with two div inside, one float: left of an image, and another container of text, and that's fine. Do not need to set a lot of layers, but some are necessary, if you write too simple, scalability is not good, for example, it is a list then you should use ul/ol, if you want to clear floats, then you may need to set a clearfix container.

If a piece is a whole and it is typeset to the right as a whole, then this piece should also be covered with a container. Sometimes, in order to achieve some effects, you may need to set an additional container, such as float the outer container and display: table-cell the inner container. But you should set these containers with value, and if you just want to look uniform in function, the distinction obviously doesn't seem to make much sense.

twelve。 Only write script and style in html under special circumstances

Generally speaking, it is a bad practice to write script and style directly in html, which mixes style, structure and logic together. But sometimes in order to avoid the problem of the splash screen, you may directly keep up with the adjusted script after the corresponding html. This kind of script looks a bit ugly, but it is very practical, and there is no way.

13. The style should be written in the head tag

The style cannot be written in body. Writing in body will lead to rendering twice, especially the lower the writing is, there may be a splash screen. For example, the above one has been rendered and suddenly encounters a style tag, which causes it to render again. It flashes a bit. Whether it is from the programmer's pursuit or the user's experience, writing style in body is a bad policy after all.

Similarly, script should not be written in the head tag, which will hinder the loading of the page.

CSS also recommends that the style tag be directly embedded on the page, because if you create an outer chain, the browser needs to resolve the domain name first, then establish a connection, and then download it, which may have passed 0.5s/1s, or even 2 or 3 seconds. While the CSS written on the page can not be cached, but it itself will not be very large, plus gzip compression, basically within 50k.

14. Add the attribute of lang to html

As follows, if it is an English web page, it should be written as follows:

The first indicates that it is an English page, and the second means that it is an American English page. In addition, this benefit is beneficial to SEO and screen reader users, who can quickly know what language the page is in. If it is in Chinese, it can be written as follows:

15. To write the charset meta tag at the front of the head tag

As follows, the meta tag of a general charset should be written after the head tag:

One reason is to avoid garbled when displaying unicode symbols on a web page, written in front of it because the W3C stipulates that the language should be encoded in the first 1024 bytes of the html document. If you don't write it, there will be a hidden danger of utf-7 attacks in the old browsers. You can consult the data on your own, but the current browsers have basically removed the support for utf-7 coding.

The label of charset can be written in the relatively concise way of html5, and there is no need to write as long as html4:

As far as I can tell, even IE6 supports that short way of writing, even though it's not a html5 browser.

16. Special symbols use html entities

Instead of copying the special symbols of Unicode directly into the html document, use its corresponding entity Entity, as shown in the following table:

| | symbol | entity coding |

| | ©| ©|

| | ¥|

| | ®| ®|

| | > | > |

| |

< | < | | & | & | 特别是像©这种符号,不要从UI里面直接拷一个unicode的字符过去,如果直接拷过去会比较丑,它取的是用的字体里面的符号。 17. img空src的问题 有时候可能你需要在写一个空的img标签,然后在JS里面动态地给它赋src,所以你可能会这么写:

But writing this will be problematic. If you write an empty src, it will cause the browser to think that src is the current page link, and then request the current page again, just like you write an empty href for a tag. If it is background-image, there will be similar problems. What should I do at this time? If you write a url that doesn't exist, the browser will report a 404 error.

There are two solutions I know. The first is to write src as about:blank, as follows:

In this way, it will load a blank page, which has no compatibility issues, will not load the current page, and will not report an error.

The second way is to write a transparent pixel base64 of 1px, as shown in the following code:

The second may be more specification-compliant, but the first is simpler and has no compatibility issues.

18. On the influence of intra-line element spaces and line wrapping

Sometimes a space may be introduced for line breaks, as shown in the following code:

Email:

There will be a space between label and input, which may cause the input to wrap when the sum of width of lable and width of input equals form. Sometimes you check for a long time without finding out the reason, and finally you may find that there is an extra space, and this space is caused by a line break. At this point, you may have a question: why is the line wrapping between and and why no spaces are introduced? This is because the blank text at the beginning of the block-level element will be ignored, as described in the Chrome source code:

/ / Whitespace at the start of a block just goes away. Don't even

/ / make a layout object for this text.

Also, the blank text node after the block-level element will not participate in the rendering, that is, like this:

There is a textNode text node between the two div, but will not participate in the rendering.

Note that the comment tag is also a normal page tag, and a corresponding node is created for it, but it does not participate in the rendering.

19. Class naming is concatenated with lowercase letters and an underscore

Use-connect as follows, do not use hump style:

20. Custom tags are not recommended

Whether you can use custom tags, such as angular, as shown in the following code:

Custom tags are generally not recommended, and angular also has switches to control whether or not to use custom tags. Although it is legal to use a custom tag, as long as you give him display: block, it is like a div, but whether from a SEO or normalization point of view, the custom tag is still a bit different, although you may think its semantics is better.

21. Heavy complex id and duplicate attributes

We know that if you write two identical id on the page, only the first one will be taken when you check the DOM, and only the first attribute will be taken if the same attribute is repeated, as follows:

The second class will be ignored, so what if the className is repeated? Repetition is also invalid. The main point here is to note that if you directly manipulate native className, you should pay attention to avoid className duplication, as shown in the following code:

Var input = form.books; input.className + = "valid"

If repeated, className will have duplicate valid classes.

twenty-two。 Property styling is not recommended

For example, if you want to set the width and height of a picture, you might write:

This is not supported on ios's safari and can be tested on its own.

Or there are some settings for table:

But this can be set with CSS to use CSS, but one exception is that the width and height of canvas needs to be written on html, as follows:

If you set it with CSS, it will stretch and become blurred.

23. Use the appropriate label

Don't be too monotonous in the use of labels:

(1) if the content is a table, using table,table has the advantage of self-adaptation; if it is a list, use the ol/ul tag, which has better expansibility.

(2) if it is an input box, use input instead of writing a p tag, and then set contenteditable=true, because this cursor positioning on the IOS Safari is prone to problems. Except if special effects are needed.

(3) if it is bold, use b/strong instead of setting font-weight yourself.

(4) if it is a form, use the form tag. Note that form cannot be used in form.

(5) if it is a jump chain, use the a tag instead of writing the onclick jump yourself. You can't put an a tag in the a tag.

(6) use html5 semantic tags, such as navigation using nav, sidebar using aside, top and tail using header/footer, and more independent parts of the page can use article, such as user comments.

(7) if it is a button, you should write a button or instead of a tag to set the style, because you can use button to set disabled, and then use CSS's: disabled, as well as pseudo-classes such as: active, for example, to set the feeling that the button is pressed when: active

(8) if it is a title, you should use the title tag h2/h3/h4 instead of writing one yourself.

On the contrary, do not use the title tag if the content is not a title

(9) when using the select tag on the mobile phone, there will be a native drop-down control. The drop-down effect of the native select on the mobile phone is often better, whether it is IOS or android, and the keyboard that will play a phone number on the phone will play the corresponding keyboard.

(10) if it is a separator, use the hr tag instead of writing a border-bottom style. It is easy to check with hr.

(11) if it is a newline text, you should use the p tag instead of writing br, because the p tag can use margin to set line spacing, but if it is long text, use div, because the p tag cannot be included in the p tag, especially when the data is given at the back end, there may be a p tag, so the container cannot use the p tag at this time.

24. Don't write http pictures in https links.

As long as the https web page requests a http image, it will cause the mini lock on the left side of the browser's address bar to disappear. Generally, do not write it dead, but load it according to the protocol of the current domain name, starting with / /:

2. CSS coding specification 1. File name specification

The file name is recommended in lowercase letters with a centerline. Why? Because this is more readable and looks refreshing, links are also used in this way, such as stackoverflow's url:

Https://stackoverflow.com/questions/25704650/disable-blue-highlight-when-touch-press-object-with-cursorpointer

Or the address of github:

Https://github.com/wangjeaf/ckstyle-node

Then why do variable names not use lowercase letters with underscores, such as family_tree, but recommend hump-style familyTree? C language likes to name variables in this way, but because underscores are more difficult to type (shift + -), most of them are named humps.

The link that introduces the CSS file does not need the type= "text/css", as shown in the following code:

Because the most important attribute in link is rel, you can do without type, but you can't do without rel.

The same is true for JS. You can use the following code without type:

There are no compatibility issues.

two。 Attribute writing order

The order in which the attributes are written makes no difference to the browser, except for priority overrides. However, if the order is consistent, you can quickly see at a glance what types of properties of the selector affect it, so it is common to put the more important attributes first. The recommended order is as follows:

You may think that this is almost what I usually write, which shows that you have a better accomplishment. And I think the rule is not dead, sometimes it can be flexible, just like you might use transform to write in the middle, and then write left/top/transform next to each other. I think this is understandable, because it gives people a glimpse of what you are going to do.

3. Do not use style features to name

Some people may like to be named after the characteristics of the style, such as:

.red-font {color: red;} .p1 {font-size: 18px;} .p2 {font-size: 16px;}

Then you will see in its html set a large number of p1/p2/bold-font/right-wrap and other class names, this is not desirable, suppose you made a red-font, the next time UI to change the color, then you write this class name is useless, or in the response inside the right typesetting in the small screen will run to the following, then you take a right is useless. Some people first took a look at the UI as a whole and found that UI used about three font sizes 18px/16px/14px, so they wrote three classes p1/p2/p3, and different font sizes set different classes. At first glance, it seems to be quite general-purpose, but when you look at his html, you go crazy. These p1/p2/p3 classes add up to 20 or 30, densely packed. I think if you want to write it this way, you might as well use the title tag as follows:

.house-info h3 {font-size: 18px;} .house-info h4 {font-size: 16px;}

Because the font size is increased, it is likely to be a title, so why not just use the title tag, you can't just worry because the title tag will have a default style.

The class should be named using the logical meaning it represents, such as signup-success-toast, request-demo, agent-portrait, company-logo, and so on.

If there are some styles that you think are really universal, you can think of it as a class, such as clearfix, or some animation effects, there are several places to use, I think this more complex and general-purpose can be used as a separate class. But it still tends to use meaning naming.

4. Do not use hack

Some people use some hack method comments when writing CSS, as follows:

.agent-name {float: left; _ margin: 10px; / / padding: 20px;}

The principle of this method is that the CSS property browser at the beginning of / / or _ does not recognize it, so it is ignored. The semicolon is the property Terminator, and everything from / / to the semicolon is ignored by the browser, but this kind of comment is not recommended. Either change the .css file to .less or .scss file, so you can happily use / / comments.

There are also some hack specific to specific browsers, such as the attribute that begins with * is hack to IE6. Don't use hack no matter what.

5. Performance of selector

Generally speaking, do not write more than 3 selectors. Some people like to write sass or less with many layers, as follows:

.listings-list {ul {li {.bed-bath {p {color: # 505050;}

A container is covered layer by layer, layer by layer, and the bottom layer is covered by seven or eight layers. The performance of such a long selector is relatively poor, because the Chrome uses recursion to match from the last selector to the first one. The more selectors, the longer the matching time, so the time will be longer, and the readability of the code is relatively poor. In order to see which style of the innermost p tag is, I have to look up layer by layer. Let's see where it's from. Indenting 7 or 8 layers in the code also looks tired.

Generally speaking, you only need to write two or three more important selectors, instead of writing in every container, the important target elements are covered with class or id.

The tag of the last selector should be used less, because if you write a .container div {}, then all the div on the page match for the first time, because it matches from right to left, the advantage of this writing is that html does not have to set a lot of classes, but the expansibility is not good, so do not easily use it, if you need to use it carefully, if appropriate, at least can not be abused.

6. Avoid misselection of selector

Sometimes your own style is influenced by other people's style, or your own style accidentally affects others. It may be because the naming of the class is the same as that of others, or the scope of the selector is too wide. For example, someone wrote on his own page:

* {box-sizing: border-box;}

As a result, the public pop-up box style on his page failed. On the one hand, do not write * global matching selector, which is too large in terms of performance and scope of influence, for example, in a selector with 3 sub-selectors:

.house-info. Key-detail .location {} copy the code

In all three containers, * is applicable, and some properties are inherited, such as font-size, which causes all three containers to have font-size, and then overrides layer by layer.

Another situation is abuse: first-child,: nth-of-type selector, the result of using this selector is not good scalability, as long as the html is changed, it will cause the style does not work, or affect other irrelevant elements. But this is not to say that this kind of selector can not be used, as long as it is used well, it is very convenient, for example, to make the margin-left of the last li smaller than that of the last li, you can write:

.listing-list li:last-child {margin-left: 10px;}

This may be better than setting up a class directly. But in any case, you can't abuse it and use it when appropriate, not just to write less class names.

7. Reduce coverage

Overwriting is a common strategy, but also a less elegant way, as shown in the following code, in order to keep the spacing of the 20px in the middle of each house, but not the first house:

.house {margin-top: 20px;} .house:first-child {margin-top: 0;}

In fact, it can be changed to this:

.house + .house {margin-top: 20px;}

Only the .house in front of the .house can hit this selector, because the first .house is not in front of it, so it misses, so the code looks much simpler.

There is also this case, as shown in the following code:

.request-demo input {border: 1px solid # 282828;} .request-demo input [type=submit] {border: none;}

In fact, you can use one: not selector:

.request-demo input:not ([type=sbumit]) {border: 1px solid # 282828;}

In this way, the code looks a lot more elegant.

There is a kind of coverage that is worth it, that is, the response style of the small screen covers the big screen, as follows:

.container {width: 1080px; margin: 0 auto;} @ media (min-width: 1024px) {.container {width: auto; margin: 040px;}}

The style of the large screen can also be written as follows:

@ media (min-width: 1025px) {.container {width: 1080px; margin: 0 auto;}}

This is what I wrote at first, in order to follow the principle of reducing coverage, but later found that this practice is not good, the code is easy to mess, the advantage of writing as coverage is that you can clearly see in the browser, the style of the small screen is covered by which big screen style, and what this is like when the big screen.

8. Use CSS3's selector to perform some advanced functions

As mentioned above: not can make the code concise, and there are other things that are easy to use. For example, when there are only two, one accounts for 50%, and when there are three, one accounts for 33%. This can be achieved with CSS, as follows:

.listing-list li {width: 33%;} .listing-list li:first-child:nth-last-child (2), .listing-list li:first-child:nth-last-child (2) ~ li {width: 50%;}

When li is the first element and the penultimate element, and the li adjacent to it is hit by the second set of selectors, its width is 50%, that is, only two li can meet this condition.

You can also borrow pseudo-class selectors such as hover/:focus/:invalid/:disabled to complete some simple interactions.

9. Use less! important

Important is used to override attributes, especially in CSS to override attributes in style, but it is better to use important less. Sometimes you write an important in order to be lazy, thinking that this is the highest priority, often mantis catches cicadas, and after the yellow sparrow, it is likely that you will have to write a higher priority overwrite soon, which is a little embarrassing. So can you use less or less? If you want to override it, you should first add the weight of the selector.

10. Write more notes

"programmers are most annoyed with two things. The first thing is that they are asked to document their own code, and the second thing is that other people's programs do not leave documentation." The same is true for comments. It is more relaxing when you see a lot of green comment code, and it is more depressing when you see code that is crumpled into a ball without comments. Comments for CSS can include:

(1) comments at the top of the file / * * @ description entire list page style entry file * @ author yincheng.li * / (2) comments for modules / * details page loan calculator * / copy code (3) simple comments / * to remove the gray background when the input box and form are clicked * / input, form {- webkit-tap-highlight-color: rgba (255,255,255,0);} (4) comments for TODO

Sometimes when you look at the source code, you will see some TODO comments:

/ * TODO (littledan): Computed properties don't work yet in nosnap. Rephrase when they do. * / copy the code

Indicates that the code needs to be improved, or that there are some defects that need to be fixed later. This kind of TODO comments editor will highlight the TODO.

Be careful not to write erroneous, misleading comments or nonsense comments, which are better than none, as follows:

/ * the font size of the title should be larger * / .listings h3 {font-size: 20px;} 11. Typesetting specification

Whether it is JS/CSS, indentation is adjusted to 4 spaces, if you use sublime, there is a Tab Size in the lower right corner of the software, select Tab Size 4, and then check the top Indent Using Spaces, so that when you type a tab key indent, it will be automatically converted to 4 spaces. If you use vim, add or edit the ~ / .vimrc file to add a new line:

: set tabstop=4

It will also automatically change the indentation to 4 spaces, and other editors will find their own setting methods. Because the display length is different in different editors, and changing it to a space can keep the format consistent on different people's computers.

Multiple selectors share a style set, with each selector on a row, as follows:

.landing-pop, .samll-pop-outer, .signup-success {display: none;}

Each attribute name colon should be followed by a space, and the ~, >, and + selectors should also be preceded by a space:

.listings > li {float: left;} 12. Attribute value specification (1) if the value is 0, there is usually no unit.

For example:

.list {border: 1px solid 0px; margin: 0px;}

It should be changed to:

.list {border: 1px solid 0; margin: 0;}

However, there is a special case, that is, all time units related to time should be accompanied by seconds, and the following two are illegal:

Transition-duration: 0; transition: transform 0 linear; (2) Color values are in hexadecimal, less rgb

As follows:

Color: rgb (80,80,80)

It should be changed to:

Color: # 505050

Because using rgb is a function, it also calculates the transformation. If it is with transparency, reuse rgba.

If the six numbers of the color value are the same, just write three:

Color: # ccc; (3) Note the difference between border none and 0

The following two meanings are the same:

Border: 0; border-width: 0

And the following two are the same:

Border: none; border-style: none

So you can remove the border with both 0 and none.

You might say that the packing tools will actually help me deal with it in the end, but it's important to maintain a good writing habit.

13. Setting up font-family

Notice that you use the corresponding font-family name of the system font, such as SFUIText Font, which is-apple-system in Safari and BlinkMacSystemFont in Chrome, so font-family can write:

Font-family {font-family:-apple-system, BlinkMacSystemFont, sans-serif;}

For example, Microsoft Acer, many Chinese websites use this font to write as follows:

Font-family {font-family: Microsoft YaHei;}

In addition, font-family cannot be set arbitrarily in the code if a custom font is used. The code is as follows:

.title {font-family: Lato Bold;}

Because if you write a lot of font-family in your code, it will be troublesome to replace the font of the web page as a whole, and the right thing to do should be like this:

H2, strong, b {font-family: Lato Bold; font-weight: normal;}

If you need to bold, use the title tag, or the b/strong tag, and call the font-weight back, because the font itself has a bold effect, and if the font-weight is bold again, the browser will continue to bold with its own algorithm. If it is a fine body, on the one hand, the general fine body is used less, on the other hand, there is no fine body label, you can use the way of nesting class.

14. Do not set too large a z-index

Some people like to set z-index to be very large:

Z-index: 99999

I thought he was the boss, and no one would be taller than him, but after the mantis caught the cicada, the yellow sparrow soon had to write another one:

Z-index: 999999

Usually, the z-index of the business logic of your page should be kept in single digits.

15. Merge attributes

Generally speaking, attributes should be merged in order to improve performance, but in fact, each attribute of Chrome is separate. Even if you put it together, it will also help you disassemble it, such as splitting margin into left/right/top/bottom, but it is recommended to write it together because it can make the code look more concise and have less code, as shown in the following code:

.container {margin-top: 20px; margin-left: 10px; margin-right: 10px;}

It can be written as:

.container {margin: 20px 10px 0;}

But if you write it together, be careful not to overwrite other settings, such as setting margin-bottom to 0. 0.

Another example is:

.banner {background-image: url (/ test.jpg); background-position: 0; background-repeat: no-repeat;}

It can be changed to:

.banner {background: url (test.jpg) 0 0 no-repeat;} 16. Note that float/absolute/fixed positioning will be forced to block.

The code is as follows:

A.btn {float: left; display: block; width: 100px; height: 30px;}

The display: block in the second line is actually useless, because if you float, the target element will have the characteristics of a block-level box model, even if you display: table-cell or inline does not work. If you are display: flex, then float will be ignored.

Similarly, absolute positioning and fixed positioning have the same effect, turning inline elements into block-level elements.

17. Clear float

There are many ways to clear floats, generally using the clearfix big = method. Although this method is flawed, it is relatively simple and suitable for most scenarios. It is compatible with IE8 and above clearfix:

.clearfix: after {content: "; display: table; clear: both;}

Do not add a redundant element at the end of the method to clear the float, although it is also feasible, but compared to low.

18. The use of quotation marks (1) font-family

Generally speaking, font-family does not need to add quotation marks, even if the font name has a space, but there is a situation that you must add quotation marks, that is, the font name happens to be a keyword, the following fonts need to add keywords:

Font-family: "inherit", "serif", "sans-serif", "monospace", "fantasy", and "cursive" (2) urlbackground-url of background: url ("/ / cdn.test.me/test.jpg")

You can add it without adding it, but there is one thing you must add, that is, url contains special characters without escape, as follows:

Background-url: url (/ / cdn.test.me/hello world.jpg)

The above browser will load / / cdn.test.me/hello and report 404. In this case, the image is uploaded by the user, the name of the image has a space, and the url given at the back end does not deal with special characters, so when the url is variable, it is best to put quotation marks:

Background-url: url ('/ / cdn.test.me/hello world.jpg')

In this way, the browser can load the image normally. This situation is best avoided from the source, but we can also make it compatible.

(3) single or double quotation marks

These two are legal, but it is better to unify them, not single quotation marks or double quotation marks at once. The more common recommendation is that html use double quotation marks and css use single quotation marks.

19. CSS Animation Specification

(1) do not use the all attribute for animation

Do not use all the properties of all when animating with transition. There may be some problems in some browsers, as follows:

Transition: all 2s linear

There may be some strange jitters on the Safari. The correct thing to do is to write which attribute you want to animate, and separate it if there are more than one, as shown in the following code:

Transition: transform 2s linear, opacity 2s linear; (2) use transform instead of position for animation

If you can use transform to do animation, you will not use left/top/margin, etc., because transform will not cause redrawing, and the performance is much higher than that of position, especially on the mobile side. Basically, the animation of displacement can be done in transform, without using the properties of CSS2, such as a box that pops up from right to left.

(3) prefer to use CSS animation instead of JS animation

For example, if a box pops up from bottom to top, you can use jQuery's slideUp function or write your own setInterval function, but this is no better than using CSS. With CSS, the initial state can move the box translate off the screen, and then click to add a class with a transformational value of 0, and then animate it with transition.

20. Don't break the words.

English words or numbers are automatically cut to the next line if the current line does not fit, resulting in different lengths of each line, which may sometimes be unattractive, but you cannot use word-break: break-all to split a word into two lines, and the other is to use:

Hyphens: auto

It will split the words into usage-connection forms, which seems reasonable, but because it is not completely broken, some words can not be broken, the phenomenon of different lengths seems obvious, and some words have been split into two lines, so it is better not to add them.

Therefore, do not use disjunctions.

21. Do not set icon font font-family

This is the same as the font-family setting mentioned above. Do not manually set font-family in the code, as follows:

.icon-up:before {content: "\ e950"; font-family: "icon-font";}

The correct thing to do is to add a .icon class to the elements of .icon, font-family and other related settings for icon fonts are unified in this class:

.icon {font-family: "icon-font"; / * Better Font Rendering = * /-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;}

Because we may add some other settings, it is better to have a .icon class unity. Don't manually set up font-family one by one.

twenty-two。 Set common styles reset

Since each browser has its own UA style, and these styles are not quite uniform, you need to do style reset. Common reset includes the following:

/ * IE browser has its own font-family for input controls, which needs to be unified * / input, textarea, button {font-family: inherit;} / * Chrome browser will add a blue outline*/ input:focus, textarea:focus, select:focus {outline: none;} / * remove textarea's resizable function * / textarea {resize: none } / * IOS Safari enlarges the font on the landscape screen, and the second attribute makes the slide smoother * / html {- webkit-text-size-adjust: 100%;-webkit-overflow-scrolling: touch;} / * unifies the edge value of the tag and the line-height*/ body, p, H2, h3, ul, ol, figure, li {padding: 0; margin: 0;} H2, h3, p {line-height: 150% } / * remove the default style of select * / select {- webkit-appearance: none;} / * if there is input, IE will add a big X * / input::-ms-clear {display: none; width: 0; height: 0;} / * remove the small triangle above and below the right side of the number input box * / input::-webkit-inner-spin-button {- webkit-appearance: none } input::-webki-outer-spin-button {- webki-appearance: none;} 23. Picture compression

Whether it is UI directly to the picture or cut out of the picture from the UI picture, you need to compress the picture, it is recommended to use tinypng, it can keep the picture quality reduced low, the picture pressure is very strong, than directly in the PS set compression quality is stronger. If it is a colorful picture to use jpg format, can not use png format, png will be much larger, if it is the kind of logo vector picture, directly use svg format. Generally speaking, the picture should be controlled within 300k, especially the banner header picture, and the size of the picture should also be controlled.

24. Correct use of background and img

There are two ways to display a picture, either by setting the background-image of CSS, or by using the img tag, when and which one?

If the picture is directly displayed such as the head image, you still need the img tag, and if it is used as the background image, use background, because you can use img to write an alt attribute to enhance the SEO, while the background image itself does not need SEO. Although background has a background-position: center center is very good, but the head picture of the use of img, go to the middle, otherwise you can not do SEO.

25. Responsive specification

Responsive development is best not to use hybrid rem, text size either all use rem, or do not use, also do not use transform: scale to reduce, because the reduced font size will look a little strange, others are 14px, and you have become 13.231px, a little smaller. The general principle of response is to keep the distance between the middle or both sides unchanged, and then reduce the width of the main content.

twenty-six。 Appropriate use: before/:after

: before and: after can be used to draw some visual auxiliary elements of the page, such as triangles, short separators, short vertical lines, etc., and can reduce the number of tags that are not used on the page. But don't use before/after to draw normal text and other elements on the page.

twenty-seven。 Use less absolute positioning

First of all, the rendering performance of absolute positioning elements will be higher, because it is independent, the amount of computation will be less, it is OK to use it well. But if the main layout of your page is to use absolute, it is certainly not advisable, because the scalability of absolute positioning is very poor, you can not change the location of each element, you can use more float, although the performance of float is relatively poor, but whether it is practical or compatibility is good.

twenty-eight。 Use less inline-block layouts

Some people like to use inline-block, especially those who are just learning to cut pictures, because block wraps, and inline-block does not break lines and has a box model, so inline-block is easy to use, while float is more complex and has to deal with problems such as clearing floats. The layout is as follows:

You should write li, and then let li float, if you let li display:inline-block can also achieve the goal. But there may be some strange problems when inline-block is used too much. You usually have to put block elements in an inline-block element. Inline-block is an inline element and block is a block element, which is a little different after all. This should be more natural to use float/flex, if you use float easily, you will find that it is much better and more professional than inline-block. If you haven't used flex much, you can try using flex instead, and if you haven't used float much, you can try it. Only when you cut pictures in a variety of ways, can you cut pictures more flexibly.

twenty-nine。 The center and width and height settings of the picture

Generally speaking, the width and height of the picture shown by UI is fixed, but the actual picture length and width is not fixed, most pictures are longer than width, and a small number of pictures grow up. Therefore, you need to center and crop the display, as shown in the following figure:

The black box in the middle is the display area, the short edge of the picture is as big as the edge of the window, the other side is stretched according to the original proportion of the picture, and then displayed in the center. This has to rely on JS, because before the picture is loaded, I don't know whether the long side is bigger or the width is bigger. The code is as follows:

In fact, this is not a good way to write, it is not good for SEO. If it is a jump, you should use the a tag, as follows:

At the same time, change the a tag to block level. Even if you don't have to do SEO, you should try to use this method, because it's more natural, and you can control whether to open a new page or not, and you don't have to worry about the delay of click events on the mobile side.

twenty-two。 Do not use localStorage directly

Because local storage is disabled in Safari's stealth mode, if you try to write data to localStorage, you will report an error that exceeds the usage limit:

QuotaExceededError (DOM Exception 22): The quota has been exceeded.

The invisible window of Chrome is not disabled. Users who use Safari may open invisible windows, especially on mobile phones. This causes the code to throw an exception, so in order to be compatible with Safari, you can't use localStorage directly, you need to be compatible:

Data.hasLocalStorage = true; try {window.localStorage.trySetData = 1;} catch (e) {Data.hasLocalStorage = false;} setLocalData: function (key, value) {if (Data.hasLocalStorage) {window.localStorage [key] = value;} else {util.setCookie ("_ LOCAL_DATA_" + key, value, 1000) }, getLocalData: function (key) {if (Data.hasLocalStorage) {return window.localStorage [key];} else {return util.getCookie ("_ LOCAL_DATA_" + key);}}

The above code is compatible and uses cookie if it does not support localStorage. Note that a domain name of cookie can only have a maximum of 50 key of 4 KB, while local storage is limited to 5Mb.

23. Use simple conversion (1) convert strings to integers you can use the + sign let maxPrice = + form.maxPrice.value; to copy the code

The + sign is equivalent to Number:

Let maxPrice = Number (form.maxPrice.value); copy code

A big difference between parseInt and Number is that the parseInt ("10px") result is 10, while Number ("10px") is NaN,parseInt will be more natural, other programming languages have similar transformations. But Number can still be used in many scenarios.

(2) to convert the decimal Mantissa to an integer, you can use > > 0.

If you calculate the row in which a number is:

Let _ row = Math.floor (index / columns); let row = parseInt (index / columns)

Can be changed to:

Let row = index / columns > > 0

This bit operation will be significantly more efficient than the above two.

(3) convert to boolean value!

The code is as follows:

Let mobile =! ua.match (/ iPhone | iPad | Android | iPod | Windows Phone/) 24. Notice the variable that returns false

Several values in if judgment return false:0, false, "", undefined, null, and NaN are all false, so you can write this to determine whether an array has any elements:

If (array.length) {}

Instead of having to write:

If (array.length! = = 0) {}

To determine whether a string is empty can be written as:

If (str) {}

But to judge whether a variable is defined or not, it should be written as:

If (typeof foo! = = "undefined") {}

Because if you directly if variables, the above possible values will be considered undefined.

25. Using Object.assgin to simplify data assignment

In the following code, you often need to get the value of the form before making a request, and then modify and add the old data submission:

Var orderData = {id: 123, price: 500} orderData.price = 600; orderData.discount = 15; orderData.manageFee = 100

There is actually a more elegant way to use Object.assign:

Var setOrderData = {price: 600,15, manageFee: 15} Object.assgin (orderData, setOrderData)

The advantage of using this is that you can get an Object of setOrderData and write it in curly braces instead of assigning values one by one, which makes it tiring to write and look. Finally, assign and assign a value to the original Object.

twenty-six。 Get rid of irrelevant console after debugging

After debugging, get rid of the print information such as console.log, don't think about deleting it after you finish it, and forget it later. In addition, do not use alert debugging, console/debugger online is all right, ordinary users will not open a console, but alert online is over, especially some people like to use alert ("fuck") and so on to see if the code has run here, this debugging skill is still relatively primary, if really online may have to pack up and leave. This can also be checked statically through the code review tool.

twenty-seven。 Pay attention to the direction of this

The code is as follows:

Let searchHandler = {search () {console.log (this); this.ajax ();}, ajax () {}}; $searchBtn.on ("click", searchHandler.search)

When the click event of searchBtn is triggered, the this in the search function already points to searchBtn, because it is the callback function of click:

SearchHandler.search.call (btn, event); copy code

So the function environment becomes btn, so it's best not to use this for this singleton Object, but to use the variable name of the current namespace:

Let searchHandler = {search () {console.log (this); searchHandler.ajax ();}, ajax () {}}; $searchBtn.on ("click", searchHandler.search)

There will be no problem.

twenty-eight。 Using regular expressions for string processing

Regular expressions can easily handle strings, usually with a single line of code. For example, remove a global character, such as the-connector of a phone number:

PhoneNumer = phoneNumber.replace (/\-/ g, "")

Or vice versa, change the phone number to 3-3-4:

PhoneNumber = phoneNumber.replace (/ ^ (\ d {3}) (\ d {4}) $/, "$1MB / 2MB / 3"); copy the code

Proficiency in regular expressions is a basic skill for every front end.

twenty-nine。 Maintain the concept of reuse modules

When you have to write a function for a long time, such as two or three hundred lines, you consider taking apart the large function, dividing it into several small functions, and then making the logic of the main function clear and concise, while the function of each small function is single and independent, the user only needs to control the input and output, and does not need to care about how the interior works. The following processing functions are used to handle user clicks in the map:

HandleMouseClick (latLng, ajax = true) {var path = this.path; / / here calls a function of closeToFirstPoint to determine whether the click position is close to the first point if (path.length > = 2 & & ajax & & this.closeToFirstPoint (latLng)) {/ / if so, closePath close path this.closePath (ajax); return } path.push ({lat: latLng.lat (), lng: latLng.lng ()}); / / this.drawPoint (latLng) of the point function; / / this.drawSolidLine () of the line function; / / this.drawPolygonMask () of the polygon background; this.lastMoveLine & & this.lastMoveLine.setMap (null); this.$drawTip.hide ();}

The above is divided into many small functions, such as the drawPoint function of drawing points. To use this function, you only need to care about giving it a latitude and longitude of the current point, and it will help you draw a point.

On top of the function, you can continue to abstract, for example, write the module of this drawing function as a DrawTool class, this class is responsible for the entire drawing function, the user only needs to instantiate an object, and then adjust init, pass some parameters.

First, it is extracted into different functions, each function is responsible for a small block, similar functions are gathered together to form a module, and several modules call each other to form a plug-in.

thirty。 Note that the label event is triggered twice

If there is an input in the label, the event listening to the label will be triggered twice, as shown in the following code:

Apple pear {let $form = $("# choose-fruit"); $form.find ("label") .on ("click", function (event) {console.log (event.target);});}

When the span is hit, the click event will be triggered twice, and if there is no input in the label, it will only be triggered once. Why is that? Because in the label container, when the span text is clicked, a click event is sent to the input,input event and then bubbles to the label, so the label will be triggered twice. So if you listen for label events directly, you should pay attention to the situation that triggers twice.

Thank you for your reading, these are the contents of "what are the HTML/CSS/JS coding specifications?" after the study of this article, I believe you have a deeper understanding of what the HTML/CSS/JS coding specifications have, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report