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 practical CSS codes for HTML5 beginners?

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

Share

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

This article mainly introduces "what is the practical CSS code for HTML5 beginners". In daily operation, I believe that many people have doubts about the practical CSS code for HTML5 beginners. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "what are the practical CSS codes for HTML5 beginners?" Next, please follow the editor to study!

1. Pay attention to the outer margin folding

Unlike most other properties, the vertical outer margin margin of the top and bottom occurs when it exists at the same time. This means that when the lower edge of one element touches the upper edge of another element, only the larger of the two margin values is retained. For example:

HTML

CSS

.square {

Width: 80px

Height: 80px

}

.red {

Background-color: # F44336

Margin-bottom: 40px

}

.blue {

Background-color: # 2196F3

Margin-top: 30px

}

The distance between the red square and the blue square is 40px, not 70px. There are many ways to solve the outer margin folding. For beginners, the easiest way is to use margin in only one direction for all elements. For example, we use margin-bottom for all the upper and lower margins.

two。 Use flex for layout

There is a reason for the emergence of flex flexible layout. Floats and inline-block can also achieve a lot of layout effects, but they are essentially tools for the layout of text and block elements, rather than for the entire web page. Flex can easily create layouts in the way we expect.

Flex has a set of properties for "elastic containers" and a set of properties for "elastic projects", and once you learn them, any responsive layout is a piece of cake. At present, there is no problem with the support of flex in the latest versions of various browsers, so you should use more flex layouts.

.container {

Display: flex

}

3. Reset the CSS style of an element

Although it has improved a lot over the years, the default styles for various elements vary greatly from browser to browser. The best way to solve this problem is to set the common CSS Reset reset code for all elements at the beginning of CSS, so that you layout without any default inner and outer margins, so the effect is uniform.

There is already a mature CSS code base on the web to solve browser inconsistencies, such as normalize.css, minireset and ress, which you can refer to in your project. If you don't want to use a third-party code base, you can use the following styles to do a very basic CSS reset:

* {

Margin: 0

Padding: 0

Box-sizing: border-box

}

The above code looks a little bossy, setting the inner and outer margins of all elements to 0, and without the influence of these default inner and outer margins, it will be easier for us to set up the CSS later. At the same time, box-sizing: border-box is also a great setting, which we'll introduce shortly.

4. All elements are set to Border-box

Most beginners don't know about the box-sizing attribute, but it's actually very important. The box-sizing property has two values:

Content-box (default)-when we set the width or height of an element, we set the size of its contents. All padding and border values are not included. For example, if the width of a div is set to 100, the padding is set to 10, so the element will occupy 120 pixels (100 pixels, 2 pixels, 10 pixels).

Border-box-padding and borders are contained in the width or height of the element, with one set to width: 100px and box-sizing:

The div element of border-box, whose total width is 100px, regardless of its inner margin and border.

Setting all elements to border-box makes it easier to resize elements without having to worry about padding or border values that stretch out elements or wrap them.

5. Use the picture as the background

When adding a picture to a page, especially if the picture is responsive, it is best to use the background property to introduce the picture instead of

Label.

It may seem more complicated to use a picture, but it actually makes it easier to style the picture. With background-size, background-position and other properties, it is more convenient to maintain or change the original size and aspect ratio of the image.

For instance

HTML

Img element

bicycle

Div with background image

CSS

Img {

Width: 300px

Height: 200px

}

Div {

Width: 300px

Height: 200px

Background: url ('')

Background-position: center center

Background-size: cover

}

Section {

Float: left

Margin: 15px

}

One disadvantage of introducing images by background is that the Web accessibility of the page is slightly affected because screen readers and search engines cannot get the images correctly. This problem can be solved through the CSS object-fit attribute, and so far all browsers except IE can use object-fit.

6. Better table borders

Tables in HTML are always ugly. They are difficult to make responsive, and it is generally difficult to change the style. For example, if you want to add a simple border to a table and its cells, the most likely result is:

As you can see, there are a lot of repetitive borders that don't look good. Here's a quick way to delete all the double borders: border-collapse: collapse, just set this property, and the border of the table looks much more pleasing to the eye:

7. More friendly comments

CSS may not be a programming language, but its code still needs to be documented. Adding some simple comments can classify the code and make it easier for yourself and your colleagues to maintain later.

The following annotation styles can be used for large zoning or important components:

Header {}

Header nav {}

.slideshow {}

You can use single-line comments for details and less important styles:

.footer button {}

.footer button:hover {}

Also, remember that there are no / / comments in CSS, only comments:

P {

Padding: 15px

}

P {

Padding: 15px

/ / border: 1px solid # 222

}

8. Short dash naming

When class or ID contains more than one word, use a hyphen (-). CSS is case-insensitive, so you cannot use hump naming. Similarly, underscore concatenation naming is not recommended in CSS.

.footer-column-left {}

.footerColumnLeft {}

.footer _ column_left {}

When it comes to naming, you can also consider BEM, which follows a set of principles that provide a component-based and consistent approach to development.

9. Do not repeat the settings

The values of most CSS attributes are inherited from elements one level up in the DOM tree, so they are named cascading style sheets. Take the font attribute, for example-it always inherits from the parent, and you don't have to set it separately for each element on the page.

Simply add the font styles you want to set to the or element and let them automatically inherit down.

Html {

Font: normal 16px/1.4 sans-serif

}

Then we can change all the text styles on the page at one time. Of course, not all attributes in CSS are inheritable, and we still need to set them separately on each element.

10. Use the transform property to create an animation

It's best to use the transform () function to animate the displacement or size of an element, and try not to directly change the width,height and left/top/bottom/right attribute values of the element.

In the following example, we add a move animation from left to right to the .ball element. It is recommended to use the transform: translateX () function instead of the left attribute.

.ball {

Left: 50px

Transition: 0.4s ease-out

}

. ball.slide-out {

Left: 500px

}

. ball.slide-out {

Transform: translateX (450px)

}

Transform and all its functions (translate, rotate, scale, etc.) have almost no browser compatibility issues and can be used at will.

11. Don't DIY, use the code base more.

The CSS community is very large, and new code bases are constantly emerging. They have a variety of uses, from tiny fragments to the overall framework for building responsive applications. Most of them are also open source.

The next time you are faced with a CSS problem, check to see if a solution is available on Github or Codepen before you try to solve it.

twelve。 Keep the weight of the selector low

Not all css selectors are equal. When I first learned CSS, I always thought that the selector would cover everything on it. However, this is not the case, as we illustrate in the following example:

HTML

Button

CSS

A {

Color: # fff

Padding: 15px

}

A#blue-btn {

Background-color: blue

}

A.active {

Background-color: red

}

We hope that the style set in the .active class will take effect so that the button turns red. But it doesn't work because the button has an ID selector on it, which also sets the background-color,ID selector to have a higher weight, so the button's color is blue. The weight size of the selector is as follows:

ID (# id) > Class (.class) > Type (for example, header)

The weights will also be superimposed, so the weight of a#button.active is higher than that of a#button. Using high-weight selectors at the beginning will cause you to continue to use higher-weight selectors in later maintenance, and eventually choose to use! important, which is very deprecated, and the specific reasons will be discussed later.

13. Don't use! important

Seriously, don't use it! important. Now it seems that the problem can be solved quickly, but it may eventually lead to a lot of rewriting. Instead, we should take some time to find out why the CSS selector is not working and change it.

The only place to use important is when you want to override inline styles in HTML, but inline styles are also a bad habit and should be avoided as much as possible.

14. Convert letters to uppercase using text-transform

This article applies to the English environment and is not suitable for Chinese

In HTML, you can write a word in uppercase letters to express the meaning of emphasis. For example:

Employees MUST wear a helmet!

If you need to convert a paragraph to uppercase, we can write it normally in HTML and then convert it through CSS. This keeps the context content consistent.

Star Wars: The Force Awakens

. movie-poster {

Text-transform: uppercase

}

15.Em, Rem and px

Which unit should be used to set the size of the element and text, em,rem or px? There has been a lot of debate all the time. The fact is that all three options are feasible and have their advantages and disadvantages.

There is no final conclusion about when to use which unit in what project. Different developers have different habits and different project requirements, and different units may be used. However, although there are no fixed rules, each unit still has some points to pay attention to:

Em-sets the element to 1em, whose size is related to the font-size attribute of the parent element. This unit is used in media queries and is especially suitable for responsive development, but because em units are calculated relative to the parent element at each level, it is sometimes troublesome to get the PX value of a child element em unit.

Rem-rem makes it easy to uniformly resize the text of all headings and paragraphs on the page relative to the font-size size of the element.

Px-Pixel units are the most accurate, but are not suitable for adaptive designs. Px units are reliable and easy to understand, and we can finely control the size and movement of elements to 1px.

Most importantly, don't be afraid to try, try all the methods and see what works best. Sometimes, em and rem can save a lot of work, especially when building responsive pages.

16. Use preprocessors for large projects

You must have heard of them-Sass, Less, PostCSS, Stylus. Preprocessor is the future of CSS. They provide features such as variables, CSS functions, selector nesting, and many other cool features that make CSS code easier to manage, especially in large projects.

To take a simple example, here is a snippet of SASS code that uses some CSS variables and functions:

$accent-color: # 2196F3

A {

Padding: 10px 15px

Background-color: $accent-color

}

A:hover {

Background-color: darken ($accent-color,10%)

}

The only drawback of preprocessors is that they still need to be compiled into plain CSS. On the other hand, the custom attributes introduced by CSS are real preprocessing.

17. Use AutoPrefixer to achieve better compatibility

Browser prefixes are one of the most annoying things in CSS. The prefixes required for each property are inconsistent, and you never know which one you need. It would be a boring nightmare if you really wanted to manually add it to the stylesheet.

Fortunately, there are tools that automatically provide us with the ability to add browser prefixes and even decide which browsers we need to support:

Online tool: Autoprefixer

Text editor plug-in: Sublime Text, Atom

Code base: Autoprefixer (PostCSS)

18. Compress CSS file

To improve the loading speed and page load of Web sites and applications, you should use compressed resources. A compressed version of the file removes all white space and duplicates, thereby reducing the total file size. Of course, this process also makes the stylesheet completely unreadable, so use the .min version in a production environment while keeping the regular version for development.

There are many different ways to compress CSS code:

Online tools: CSS Minifier, CSS Compressor

Text editor plug-in: Sublime Text, Atom

Code base: Minfiy (PHP), CSSO, CSSNano (PostCSS, Grunt, Gulp)

Depending on your workflow, you can use any of the above.

19.Caniuse

There are still many compatibility inconsistencies in the Web browser, which is the property of CSS. Use caniuse to check whether the properties you are using are widely supported? Do you need a prefix? Or is there something to pay attention to when using it in a browser? With caniuse, you will be better at writing CSS.

20. Verification

Validating CSS may not be as important as verifying HTML or JavaScript code, but it's still useful to run your code through a tool. It will tell you if you have made any mistakes, warn you about the usage of the errors, and provide you with tips for improving your code.

Just like compression and Autoprefixer, there are free tools available:

Online tools: W3 Validator, CSS Lint

Text editor plug-in: Sublime Text, Atom

Code base: stylelint (Node.js, PostCSS), css-validator (Node.js)

At this point, the study of "what are the practical CSS codes for HTML5 beginners" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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