Home > Web Front-end > HTML Tutorial > Why is CSS widely used?

Why is CSS widely used?

零下一度
Release: 2017-06-27 10:16:57
Original
1931 people have browsed it

Previous words

In the CSS learning directory, how to use CSS has been introduced in detail. To know what it is, you also need to know why it is so. This article will introduce the reasons for the emergence of each part of CSS. It is limited to personal understanding. If there is anything wrong, please feel free to communicate

Why CSS

Most early website tags were almost completely It is composed of tables and font elements, and cannot convey any actual meaning to the content to be displayed, making the document less usable and difficult to maintain. So in 1995, W3C released a CSS draft in an attempt to solve the problem of mixed structure and style

1. If you consider the complete separation of structure and style, and the style sheet may be used in multiple HTML files, use an external style sheet

 2. If the style sheet is only used for the current page and to reduce the number of HTTP requests, use the internal style sheet

 3. If you just want to specify some styles for a single element, you can use the HTML style attribute To set an inline style

Why Selector

Apply certain rules to a set of element types in the document through CSS selectors

1. The wildcard selector selects all elements

2. The element selector selects elements according to HTML tags

3. The class selector selects a type of element by defining the class name

 4. The ID selector selects elements with specific IDs

 5. The attribute selector selects elements based on their attributes and attribute values

 6. The descendant selector selects elements through HTML hierarchical relationships Element

 7. Group selector combines elements with the same rules and sets

Why Cascading

 CSS (cascading style sheets) Chinese translation is The most basic feature of cascading style sheets is cascading. Conflicting declarations are sorted through cascading to determine the final document representation

In the example below, both the element selector div and the class selector .test can select

, a conflict occurs. Since the class selector is more specific than the element selector, it is sorted through cascading. The final style of the element is {height: 200px;}. If the rule .test{height: 200px;} is removed, the style of the element is {height: 100px;}

<style>div{height: 100px;}.test{height: 200px;}    </style><div class="test"></div>
Copy after login

Why Hack

CSS Hack is a foolproof method to achieve browser style compatibility. Try not to use it if you can. use. However, for some browser bugs, such as bugs in older versions of IE, sometimes using CSS Hack is a last resort

For example, for IE6-the browser mainly uses underscore_ and underscore-this Two characters implement hack. As shown below, in the IE6 browser, the text color of the div is blue, and in other browsers it is red

<span style="color: #000000;">div{<br>  color:red;<br>  _color:blue;<br>}</span>
Copy after login

Why Pseudo-classes and pseudo-elements

Personally believe that pseudo-classes and pseudo-elements are an extension of HTML elements, through which they can enrich the style expression of elements

Pseudo-classes are fake classes, similar to adding an actual class To achieve effects, such as the common hover mouseover effect

a:hover{background-color:lightblue;}/*浅蓝,鼠标悬停*/
Copy after login


Pseudo elements are fake elements, similar to adding an actual element. achieve. Of course, what is added is not the element, but the generated content. The generated content mainly refers to the content created by the browser, such as :before and:after

Why Unit

Broadly speaking, unit is a relative concept, which is an abstract concept that can constitute an individual in the coordinate axis of the coordinate system of things. The length unit refers to the basic unit for measuring spatial distance. It is the basic unit developed by CSS to standardize length.

In order to better measure and express the length of the page, CSS specifies absolute length units, font-related length units, and viewport-related length units

[Absolute length units]

Absolute length units represent a physical measurement, including pixels px (pixels), inches in (inches), inches in (inches), inches in (inches), inches in (inches), 1/4 millimeter q (quarter- millimeters), points pt (points), picas pc (picas)

On the web, pixel px is a typical unit of measurement, and many other length units are directly mapped to pixels. Finally, they are processed according to pixels

1in = 2.54cm = 96px 
1cm = 10mm = 96px/2.54 = 37.8px
1mm = 0.1cm = 3.78px
1q = 1/4mm = 0.945px
1pt = 1/72in = =0.0139in = 1/72*2.54cm = 1/72*96px = 1.33px
1pc = 12pt = 1/6in = 1/6*96px = 16px
Copy after login

【字体相关的长度单位】

  字体相关的相对长度单位包括em、ex、ch、rem

  em表示元素的font-size属性的计算值,如果用于font-size属性本身,相对于父元素的font-size;若用于其他属性,相对于本身元素的font-size

  rem是相对于根元素html的font-size属性的计算值

  ex是指所用字体中小写x的高度。但不同字体x的高度可能不同。实际上,很多浏览器取em值一半作为ex值

  ch与ex类似,被定义为数字0的宽度。当无法确定数字0宽度时,取em值的一半作为ch值

【视口相关的长度单位】

  视口相关的长度值相对于初始包含块的大小。当初始包含块的宽高变化时,他们都会相应地缩放。然而,当根元素的overflow值为auto时,任何滚动条会假定不存在

  关于视口相关的单位有vh、vw、vmin、vmax4个单位

vh:布局视口高度的 1/100
vw:布局视口宽度的 1/100
vmin:布局视口高度和宽度之间的最小值的 1/100
vmax:布局视口高度和宽度之间的最大值的 1/100
Copy after login

 

Why 盒模型

  盒模型是CSS布局的基础,它描述了一个元素在文档布局中所占的空间大小。而且,每个框影响着其他元素框的位置和大小  

【box-sizing】

  在CSS中盒模型被分为两种,第一种是W3C的标准模型,第二种是IE怪异盒模型。不同之处在于后者的宽高定义的是可见元素框的尺寸,而不是元素框的内容区尺寸。目前对于浏览器大多数元素都是基于W3C标准的盒模型,但对于表单form中的部分元素还是基于IE的怪异盒模型,如input里的radio、checkbox、button等元素,如果给其设置border和padding它们也只会往元素盒内延伸

  在W3C的标准模型下,宽度和高度仅仅包含了内容宽度,除去了边框和内边距两个区域,这样为web设计师处理效果带来了不少麻烦。为了解决这个问题,CSS3新增了一个盒模型属性box-sizing,能够事先定义盒模型的尺寸解析方式


 

Why margin重叠

  在网页布局中,因为margin重叠的原因,我们常常把margin作为一个“问题样式”而尽量少地使用它。但实际上,它是在很大的作用的

  HTML文档创建的初衷只是用来展示信息的。HTML文档只使用默认样式的前提下,如果上下margin不发生重叠,则会出现以下几个问题:1、连续段落或列表之类,如果没有margin重叠,首尾项间距会和其他兄弟元素呈现1:2的关系,排版不自然;2、web中任何地方嵌套或直接放入任何裸div,都会影响原生的布局,与web设计原则相违背;3、遗落的空的任意多个p标签,会影响原来的阅读排版

  所以,我们要善用重叠,可以在列表项中同时使用margin-top和margin-bottom。这样,使页面结构更具有健壮性,最后一个元素移除或位置调换,都不会破坏原生的布局

【-webkit-margin-collapse】

-webkit-margin-collapse: <collapse>(默认重叠) | <discard>(取消) | <separate>(分隔)
Copy after login

This attribute is used to set whether margin overlaps, and acts on one of the two elements where margin overlap occurs. If both use this attribute, one is set to discard and the other is set to separate, the final effect will be overlapping collase


Why auto

Understanding visual formatting can determine whether the resulting effect is the correct one that should be displayed, or whether it is a browser compatibility bug. One of the more important concepts in visual formatting is auto. The auto value is used to make up for the gap between the actual value and the required sum

[Why does the width of a block-level element fill up the parent element by default]

Since the default value of block-level element width is auto, and the default values ​​of margin, border and padding are all 0, according to the calculation formula that the horizontal sum of the block-level element box is equal to the width of the parent element, the width of the block-level element is equal to the default value of included The block is the width of the parent element.

[Why is the block-level element displayed on the left by default after setting the width?]

Because after setting the width for the block-level element, the margin, border and padding default values Both are 0, according to the calculation formula that the horizontal sum of the block-level element boxes is equal to the width of the parent element. This situation is called overconstrained formatting attribute. At this time, margin-right will always be forced to auto, so that it is displayed on the left and margin-right makes up the remaining width.

[Why fixed width Setting margin:auto for block-level elements can achieve horizontally centered display】

Similarly, according to the calculation formula that the horizontal sum of block-level element boxes is equal to the width of the parent element, border and padding are 0. After setting a fixed width, margin -left and margin-right divide the remaining width equally

[Why the height of block-level elements defaults to the height of the element itself]

Personally, I think this is related to the browser first moving from left to right, and then from Related to the top-to-bottom rendering mechanism. This rendering mechanism determines that the width value is determined, and the height value is the height of the element itself. If the height value is also determined, that is, the viewport height, each time a block-level element is rendered, it will occupy the entire screen size, which is undoubtedly a disaster; therefore, the browser needs to be as small as possible while ensuring that it is wide enough. Height, this height as small as possible is the height of the element itself

[Why block-level elements cannot be displayed vertically when setting margin:auto]

The browser sets margin-top and margin-bottom to auto , it will be automatically reset to 0. If you want to achieve vertical centering, you can use calc() to calculate it yourself. If the height is 100px, the border is 0, the padding is 10px, and the height of the containing block is 200px, then margin-top = calc((200px - 100px - 10px -10px) / 2)

 [Note] The problem of margin overlap in the vertical direction must be considered

[Why the picture setting margin:auto cannot achieve horizontal center display]

The picture cannot be horizontal Centered, similar to block-level elements that cannot be vertically centered. Because the width of the picture defaults to its own width, the left and right margins are set to auto and will be reset to 0; if you want to achieve horizontal and centered display, set the picture display to block

Why line height and vertical alignment

Under normal circumstances, the layout of block-level elements is mainly based on the box model, while the layout of inline elements (including inline-block elements) mainly relies on line-height andvertical-align

 line-heightLine height refers to the distance between the baselines of lines of text. vertical-align is used to set the vertical alignment. All vertically aligned elements will affect the row height

[Why inline-block elements have bottom gaps]

 inline- The block element leaves a gap in the block-level element because the default vertical alignment of the image is baseline alignment (in principle, baseline alignment is equivalent to aligning the bottom edge of the image with the bottom edge of the uppercase English letter X of the anonymous text); while anonymous text has lines High, inherits the line height set by the parent element, the default is normal (1.334 times the font-size under chrome), so there is a distance between the bottom edge of the X and the bottom edge of the line box, and this distance is left by the image Gap

Therefore, there are three solutions to solve this problem

1. Set display:block, because the vertical alignment can only be applied to replaced elements and inline elements, change it to block-level elements , which will invalidate the vertical alignment

2. Set the parent's line-height: 0, so that the distance between the anonymous text and the line box is 0

3. Set vertical-align to top /middle/bottom

[Why vertical margin of inline elements is invalid]

Because the vertical layout of inline elements is mainly affected by line-height and vertical alignment, vertical margin does not It won't affect them, so it won't affect the vertical layout. In the display mode, the margin area will not display the element background, so it will not affect the display of its own elements, so the vertical margin of inline elements is invalid

Why float

The earliest use of float comes from , which is used for typesetting of text surrounding images. Floating is now a commonly used layout method in CSS

The floating element breaks away from the normal flow, then moves left or right in the specified direction, and stops when it encounters the parent boundary or another floating element. Floating has the following 4 characteristics:

1. Floating flow: elements in a normal flow are arranged one after another; floating elements also constitute a floating flow

2. Block-level box: floating elements themselves will generate A block-level box, no matter what the element itself is, prevents the margins around the floating element from merging

3. Wrapping: the containing block of a floating element refers to its nearest block-level ancestor element, and descendants of floating elements Elements should not extend beyond the top, left, or right boundaries of the containing block. If the height of the containing block is not set, and the containing block floats, the containing block will extend to include all its descendant floating elements; if the width of the containing block is not set, and the containing block floats, the width of the containing block will be stretched by the descending floating elements.

 4. Destructiveness: The floating element breaks away from the normal flow and destroys its own line box attribute, causing the height of the block element it contains to collapse, causing the line box next to the floating box to be Shorten, thereby leaving space for the floating box, and the line boxes are rearranged around the floating box

[Why you need to clear the float]

 Clearing the float is actually to solve the height of the containing block of the floating element. The problem of collapse

# For standard browsers, there are actually two methods for clearing floats. One is to add a new element below the floating element and set the clear attribute; the other is Is to trigger the BFC of the containing block to contain floating elements

Why BFC

Often, we use BFC to clear floats, but in fact There are many other uses for BFC

Before explaining BFC, let’s talk about document flow. The document flow we often talk about is actually divided into three types: positioning flow, floating flow and ordinary flow. The ordinary flow actually refers to the FC in BFC. FC is the abbreviation of formatting context, which literally means formatting context. It is a rendering area on the page. It has a set of rendering rules that determine how its sub-elements are laid out and the relationship with other elements. effect. Common FCs include BFC, IFC, GFC and FFC. BFC is block formatting context, which is a block-level formatting context. It is a rendering area used to layout block-level boxes If the following conditions are met BFC

can be triggered in one step 1. The root element is the HTML element

2. The value of float is not none

3. The value of overflow is not visible

4. The value of display is inline-block, table-cell, table-caption

5. The value of position is absolute or fixed

BFC is a Isolated independent container, the child elements inside the container will not affect the outer elements, and vice versa

. BFC is often used to achieve the following three purposes 1. Prevent elements from being covered by floating elements

 By changing the attribute value of the box whose content is BFC and whose background is red, it becomes BFC, to prevent being covered by green floating boxes

## 2. Containing floating elements

 By changing the height of the collapsed black border The attribute value of the box makes it a BFC to contain the green floating box

 3.
Two adjacent block-level children belonging to the same BFC The upper and lower margins of the elements will overlap (when writing-mode:tb-rl is set, the horizontal margins will overlap). So when two adjacent block-level child elements belong to different BFCs, you can prevent margin overlap

 The block-level box two with a light red background is wrapped with a div , by changing the attributes of this div so that the red box and the green box belong to two different BFCs, to prevent margin overlap


Why Positioning

CSS has three basic layout mechanisms: normal flow, floating flow and positioning flow. Positioning allows you to define exactly where an element's box should appear relative to its normal position, or relative to a parent element, another element, or even the browser window itself

When an element is absolutely positioned, will be completely removed from the document flow. An element is positioned relative to its nearest positioned ancestor. If the element has no positioned ancestors, then its position is relative to the original containing block document, whose boundaries are placed according to the offset property. The element generates a block-level box after positioning, regardless of what type of box it originally generated in the normal flow. Positioned elements do not flow into the content of other elements, and vice versa

When an element is relatively positioned, it is moved from its normal position, however, the space it originally occupied does not So it disappears. Relatively positioned elements create a new containing block for all of their child elements. This containing block corresponds to the original location of the element

  固定定位与绝对定位很类似,元素会完全从文档流中去除,但固定元素的偏移是相对于视窗

【为什么clip属性无效】

  绝对定位或固定定位元素才可以使用clip属性。绝对定位元素常配合clip属性达到元素隐藏的效果

.hide{
    position:absolute;
    clip: rect(0,0,0,0);
}
Copy after login

【为什么静态位置的元素会发生跳动】

  对于居中对齐的行内元素来说,将元素设置为absolute或fixed会发生静态位置跳动问题。而relative或static则不会有此问题。这是因为元素默认的居中对齐是元素的内容中线对应父级块级元素中线,而当元素绝对定位或固定定位之后,定位元素左边界将与其父级块级元素的中线对齐


【为什么overflow属性会失效】

  当overflow在绝对定位元素和其包含块之间时,绝对定位元素不会被父级overflow属性剪裁


  解决办法就是有两种, 一种是让overflow元素自身成为包含块,给父级设置position:absolute或fixed或relative;另一种是设置overflow元素的子元素为包含块,在绝对定位元素和overflow元素之间增加一个元素并设置position:absolute或fixed或relative

 

Why z-index

  对于所有定位,最后都不免遇到两个元素试图放在同一位置上的情况。显然,其中一个必须盖住另一个。但,如何控制哪个元素放在上层,这就引入了属性z-index

  利用z-index,可以改变元素相互覆盖的顺序。这个属性的名字由坐标系统得来,其中从左向右是x轴,从上到下是y轴。从屏幕到用户是z轴。在这个坐标系中,较高z-index值的元素比较低z-index值的元素离用户更近,这会导致较高z-index值的元素覆盖其他元素,这也称为堆叠或叠放

  对于CSS2.1来说,页面元素的堆叠规则如下图所示

For positioned elements (elements whose position is not static), if the z-index is not set or the z-index is the same, the following elements cover the previous elements; for elements of the same level in the same stacking context, the default z -Higher values ​​of index override smaller values ​​of z-index

Once a z-index value (not auto) is specified for an element, the element will establish its own local stacking context. This means that all descendants of an element have their own stacking order relative to the ancestor element

[Note] The auto value means that the stack level generated in the current stacking context is the same as the level of its parent box. This box No new local overlay context is created. The values ​​of z-index:auto and z-index:0 are equal, but z-index:0 will create a new local stacking context

The emergence of CSS3 has challenged many rules in the past. The impact on the z-index of the cascading context is more significant, mainly including the following 8 attributes

1. Flex items whose z-index value is not auto (parent element display: flex | inline-flex)

 2. The element’s transparency opacity value is not equal to 1

 3. The element’s transform transform is not none

 4. The element’s mix-blend-mode value is not normal

5. The filter value of the element is not none

6. The isolation value of the element is isolate

7. The attribute value specified by will-change is any of the above

8 , the element's -webkit-overflow-scrolling is set to touch

Setting any of the above eight attributes is similar to setting absolute, the cascading context z-index will take effect

Why Overflow

When an element is fixed to a specific size, but the content cannot fit in the element. At this time, you can use overflow(overflow) to control this situation

The attributes of overflow-x and overflow-y were originally IE browsing The properties developed by the browser alone were later adopted and standardized by CSS3. overflow-x is mainly used to define the shearing of horizontal content overflow, while overflow-y is mainly used to define the shearing of vertical content overflow


BFC can be triggered when overflow is set to auto or scroll or hidden, so that overflow can implement some related applications

[Why scroll bars appear]

Scroll bars and overflow are closely related of. Only when the value of the parent's overflow is auto or scroll, and the content of the element exceeds the element area, the scroll bar may appear


 No matter In any browser, the default scroll bar comes from , not . Because the element has a margin of 8px by default. If the scroll bar comes from the element, there should be a gap of 8px between the scroll bar and the page. In fact, there is no gap, so the scroll bar comes from the element

 chrome/firefox/ The default scroll bar width of IE browser is 17px, and that of Safari browser is 21px

Why flex

CSS3 introduces a new layout model-flex layout . Flex is the abbreviation of flexible box, generally called the flexible box model. Flex layout provides a more efficient way to layout items within a container to adapt to various types of display devices and screens of various sizes

Flexible containers exist by default Two axes: horizontal main axis and vertical cross axis

[Note] The main axis direction is not necessarily horizontal, it mainly depends on the justify-content attribute

The starting point of the main axis is called main start, and the end point of the main axis is called main end; the starting point of the side axis is called cross start, and the end point of the side axis is called cross end

By default, telescopic items are arranged along the main axis. The main axis space occupied by a single telescopic project is called main size, and the side axis space occupied is called cross size

[Note] The main size and cross size of a telescopic project are mainly determined by the width or height

Using flex Various layout forms can be easily implemented. The details are here

Why multi-column layout

Floating as a common typesetting method is only a last resort. Initially, it was just It is used to realize the mixed arrangement of images and text, and it is best to only use it for the mixed arrangement of images and texts, rather than a more complex layout structure

Positioning is used to accurately position the layout of elements

In my opinion, The flexible layout provided by flex layout can be used to replace the widely used floating layout

, while the multi-column layout provides a typesetting method similar to newspapers and magazines

CSS has added many new Column layout features that allow the browser to determine when to end one column and start the next without any additional markup. To put it simply, CSS3 multi-column layout can automatically arrange content according to the specified number of columns. The layout effect achieved by this feature is very similar to newspaper and magazine typesetting


The above is the detailed content of Why is CSS widely used?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
css
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template