Monthly Archives: 九月 2015

BFC: Block formatting context

Sources:

Summary

A block formatting context is a part of a visual CSS rendering of a Web page. It is the region in which the layout of block boxes occurs and in which floats interact with each other.(当涉及到可视化布局的时候,Block Formatting Context提供了一个环境,HTML元素在这个环境中按照一定规则进行布局。一个环境中的元素不会影响到其它环境中的布局。为了让我们有个感性的认识,举个不太合适的例子。你可以把一个页面想象成大的集装箱,这个集装箱里装的货物就是HTML元素。在现实生活中为了避免不同人的货物相互混淆,都是把货物打好包装再装入集装箱,这样的话无论你包装里面的货物怎么摆放,都不会影响到其他人的货物。那么这个包装就可以被想象成Block Formatting Context。)

A block formatting context is created by one of the following:

  • the root element or something that contains it
  • floats (elements where float is not none)
  • absolutely positioned elements (elements where position is absolute or fixed)
  • inline-blocks (elements with display: inline-block)
  • table cells (elements with display: table-cell, which is the default for HTML table cells)
  • table captions (elements with display: table-caption, which is the default for HTML table captions)
  • elements where overflow has a value other than visible
  • flex boxes (elements with display: flex or inline-flex)

A block formatting context contains everything inside of the element creating it that is not also inside a descendant element that creates a new block formatting context.

Block formatting contexts are important for the positioning (see float) and clearing (see clear) of floats. The rules for positioning and clearing of floats apply only to things within the same block formatting context. Floats do not affect the layout of things in other block formatting contexts, and clear only clears past floats in the same block formatting context.

Blocking Formatting Context在生产中的作用

Block Formatting Context可以阻止边距折叠(margin collapsing)

我们知道在一般情况下,两个上下相邻的盒子会折叠它们垂直方向接触到的边距,这种情况只会发生在同一个Block Formatting Context中。换句话说,在同一个布局环境中(Block Formatting Context)是边距折叠的必要条件。这也就是为什么浮动的元素和绝对定位元素不会发生边距折叠的原因(当然还有很多种情况也不会折叠)。

Block Formatting Context可以包含内部元素的浮动

考虑一下下面的例子(请用标准浏览器查看):

在上面的代码本意是做一个两行两列的布局,但是由于#red, #orange, #yellow, #green这四个div同在一个布局环境中,即便通过#c1, #c2这两个div划分,浮动之后它们还会一个接着一个排列,并不会换行。我们要做的就是把这四个div两两划分到不同的布局环境之中,从而闭合浮动。通过上面的分析,让#c1形成新的Block Formatting Context就可以解决问题。

我做了个实验,如上所示,其实这个时候你会发现#c11和#c21里的元素全部浮动之后,#c11和#c21的高度都变成0,宽度仍然撑满了父容器。这四个彩色方框纷纷脱离了他们的父容器

Block Formatting Context可以阻止元素被浮动覆盖

在标准浏览器下可以看到,普通的#right元素被浮动的#left元素所覆盖了。要想避免这种情况,有一种方法就是让#right形成新的Block Formatting Context。但是这里一定要注意的是,浮动不会覆盖的只是Block Formatting Context的border-box。换句话说,形成Block Formatting Context元素的margin还是会被浮动所覆盖掉的。

如下,我们给#left添加overflow: hidden以创建一个block formatting context,看看效果如何吧。另外我还加了margin以证明margin会被浮动元素覆盖掉,但是需要注意,如果黄框的宽度为0,也就是黄框的margin-left和margin-right直接相连的时候,左边那个红框也只是覆盖住黄框的margin-left而已,并不会覆盖掉黄框的margin-right。

Other Notes

未完待续

float

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

Summary

The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container, where text and inline elements will wrap around it.

A floating element is one where the computed value of float is not none.

The float can be applied to all elements, but has no effect if the value of display is none.

As float implies the use of the block layout, it modifies the computed value of the display values in some cases:

Specified value Computed value
inline block
inline-block block
inline-table table
table-row block
table-row-group block
table-column block
table-column-group block
table-cell block
table-caption block
table-header-group block
table-footer-group block
flex flex, but float has no effect on such elements
inline-flex inline-flex, but float has no effect on such elements
other unchanged
Note: If you’re referring to this property from JavaScript as a member of the element.style object, you must spell it as cssFloat. Also note that Internet Explorer versions 8 and older spelled this styleFloat. This is an exception to the rule that the name of the DOM member is the camel-case name of the dash-separated CSS name (and is due to the fact that “float” is a reserved word in JavaScript, as with the need to escape “class” as “className” and escape <label>’s “for” as “htmlFor”).

Syntax

Values
left
Is a keyword indicating that the element must float on the left side of its containing block.
right
Is a keyword indicating that the element must float on the right side of its containing block.
none
Is a keyword indicating that the element must not float.
inline-start
This is an experimental API that should not be used in production code.
inline-end
This is an experimental API that should not be used in production code.

Examples

Styles:

Html structure:

HELLO!

This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.

How floats are positioned

As mentioned above, when an element is floated it is taken out of the normal flow of the document. It is shifted to the left or right until it touches the edge of its containing box or another floated element.

In the image below, there are three red squares. Two are floated left and one is floated right. Note that the second “left” red square is placed to the right of the first. Additional squares would continue to stack to the right until they filled the containing box, after which they would wrap to the next line.

Float Example

Clearing floats

In the example above, the floated elements are shorter vertically than the block of text they’re floated within. However, if the text was not long enough to wrap below the bottom of all the floats, we might see unanticipated effects. If the paragraph above, for instance, only read “Lorem ipsum dolor sit amet,” and was followed by another heading of the same style as the “Floats Example” heading, the second heading would appear between the red boxes. Most likely, we want the next heading to be aligned all the way to the left. To accomplish that, we’d need to clear the floats.

The simplest way to clear the floats in this example is to add the clear property to the new heading we want to be sure is aligned left:

However, this method only works if there are no other elements within the same block formatting context that we do want the heading to continue to appear next to horizontally. If our H2 has siblings which are a sidebars floated to the left and right, using clear will force it to appear below both sidebars, which is probably not what we want.

If clearing floats on an element below them is not an option, another approach is to limit the block formatting context of the floats’ container. Referring to the example above again, it appears that all three red boxes are within a P element. We can set the overflow property on that P to hidden or auto to cause it to expand to contain them, but not allow them to drop out the bottom of it:

Note: Setting overflow to scroll will also contain any floated child elements, but will show scrollbars no matter the height of the content. Here we’re setting height to auto even though that’s the default to indicate that the container should grow to accommodate its content.

Using CSS multi-column layouts

Source: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_multi-column_layouts

The CSS multi-column layout extends the block layout mode to allow the easy definition of multiple columns of text. People have trouble reading text if lines are too long; if it takes too long for the eyes to move from the end of the one line to the beginning of the next, they lose track of which line they were on. Therefore, to make maximum use of a large screen, authors should have limited-width columns of text placed side by side, just as newspapers do.

Unfortunately this is impossible to do with CSS and HTML without forcing column breaks at fixed positions, or severely restricting the markup allowed in the text, or using heroic scripting. This limitation is solved by adding new CSS properties to extend the traditional block layout mode.

Using columns

Column count and width

Two CSS properties control whether and how many columns will appear: column-count and column-width.

The column-count property sets the number of columns to a particular number. E.g.,

will display the content in two columns (if you’re using a multi-column compliant browser):

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

The column-width property sets the minimum desired column width. If column-count is not also set, then the browser will automatically make as many columns as fit in the available width.

becomes:

Lorem ipsum dolor sit amet, onsectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

The exact details are described in the CSS3 specification.

In a multi-column block, content is automatically flowed from one column into the next as needed. All HTML, CSS and DOM functionality is supported within columns, as are editing and printing.

The columns shorthand

Most of the time, the Web designer use one of the two CSS properties: column-count or column-width. As values for these properties does not overlap, it is often convenient to use the shorthand columns. E.g.

The CSS declaration column-width:12em can be replaced by:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

The CSS declaration column-count:4 can be replaced by:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

The two CSS declarations column-width:8em and column-count:12 can be replaced by:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
Height Balancing

The CSS3 Column specification requires that the column heights must be balanced: that is, the browser automatically sets the maximum column height so that the heights of the content in each column are approximately equal. Firefox does this.

However, in some situations it is also useful to set the maximum height of the columns explicitly, and then lay out content starting at the first column and creating as many columns as necessary, possibly overflowing to the right. Therefore, if the height is constrained, by setting the CSS height or max-height properties on a multi-column block, each column is allowed to grow to that height and no further before adding new column. This mode is also much more efficient for layout.

Column Gaps

There is a gap between columns. The recommended default is 1em. This size can be changed by applying the column-gap property to the multi-column block:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

Graceful Degradation

The column properties will just be ignored by non-columns-supporting browsers. Therefore it’s relatively easy to create a layout that will display in a single column in those browsers and use multiple columns in supporting browsers.

Note that not all browsers supports these properties unprefixed. To make use of this feature in most today’s browsers, each property must be written thrice: once with the -moz prefix, once with the -webkit prefix and once without prefix.

Conclusion

CSS3 columns are a layout primitive that will help Web developers make the best use of screen real estate. Imaginative developers may find many uses for them, especially with the automatic height balancing feature.

总体而言,这块内容非常容易掌握,但是用于兼容性的问题,只能用来渐进增强。相关的属性还有:

column-rule
In multi-column layouts, the column-rule CSS property specifies a straight line, or “rule”, to be drawn between each column. It is a convenient shorthand to avoid setting each of the individual column-rule-* properties separately : column-rule-width, column-rule-style and column-rule-color.
column-span
The column-span CSS property makes it possible for an element to span across all columns when its value is set to all. An element that spans more than one column is called a spanning element.
column-fill
The column-fill CSS property controls how contents are partitioned into columns. Contents are either balanced, which means that contents in all columns will have the same height or, when using auto, just take up the room the content needs.

Layout mode

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

A CSS layout mode, sometimes abbreviated as layout, is an algorithm determining the position and the size of boxes based on the way they interact with their sibling and ancestor boxes. There are several of them:

  • The block layout, designed for laying out documents. The block layout contains document-centric features, like the ability to float elements or to lay them out over multiple columns.
  • The inline layout, designed for laying out text.
  • The table layout, designed for laying out tables.
  • The positioned layout, designed for positioning elements without much interaction with other elements.
  • The flexible box layout, designed for laying out complex pages that can be resized smoothly.
  • The grid layout, designed for laying out elements relative to a fixed grid.
Note: not all CSS properties apply to all layout modes. Most of them apply to one or two of them and have no effect if they are set on an element participating in another layout mode.

这篇文章有几个知识点还不清楚的,需要以后回过头细查下相关的知识点。

Box model

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

Summary

In a document, each element is represented as a rectangular box. Determining the size, properties — like its color, background, borders aspect — and the position of these boxes is the goal of the rendering engine.

In CSS, each of these rectangular boxes is described using the standard box model. This model describes the content of the space taken by an element. Each box has four edges: the margin edge, border edge, padding edge, and content edge.

Each box has four edges

The content area is the area containing the real content of the element. It often has a background, a color or an image (in that order, an opaque image hiding the background color) and is located inside the content edge; its dimensions are the content width, or content-box width, and the content height, or content-box height.

If the CSS box-sizing property is set to default, the CSS properties width, min-width, max-width, height, min-height and max-height control the content size.

The padding area extends to the border surrounding the padding. When the content area has a background, color, or image(我觉得这里应该是background-color和background-image) set on it, this will extend into the padding, which is why you can think of the padding as extending the content. The padding is located inside the padding edge, and its dimensions are the padding-box width and the padding-box height.

The space between the padding and the content edge can be controlled using the padding-top, padding-right, padding-bottom, padding-left and the shorthand padding CSS properties.

The border area extends the padding area to the area containing the borders. It is the area inside the border edge, and its dimensions are the border-box width and the border-box height. This area depends on the size of the border that is defined by the border-width property or the shorthand border.

The margin area extends the border area with an empty area used to separate the element from its neighbors. It is the area inside the margin edge, and its dimensions are the margin-box width and the margin-box height.

The size of the margin area is controlled using the margin-top, margin-right, margin-bottom, margin-left and the shorthand margin CSS properties.

When margin collapsing happens, the margin area is not clearly defined since margins are shared between boxes.

Finally, note that, for non-replaced inline elements, the amount of space taken up (the contribution to the height of the line) is determined by the line-height property, even though the border and padding appear visually around the content.

PS:下面这个图是从《CSS设计指南》这本书里截图下来的,感觉这个图挺不错的。

3d_box_model

inheritance

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

Summary

The summary of every CSS property definition says whether that property is inherited by default (“Inherited: Yes”) or not inherited by default (“Inherited: no”). This controls what happens when no value is specified for a property on an element.

Inherited properties

When no value for an inherited property has been specified on an element, the element gets the computed value of that property on its parent element. Only the root element of the document gets the initial value given in the property’s summary.

A typical example of an inherited property is the color property. Given the style rules:

and the markup:

the words “emphasized text” will appear green, since the em element has inherited the value of the color property from the p element. It does not get the initial value of the property (which is the color that is used for the root element when the page specifies no color).

Non-inherited properties

When no value for an non-inherited property (sometimes called a reset property in Mozilla code) has been specified on an element, the element gets the initial value of that property (as specified in the property’s summary).

A typical example of a non-inherited property is the border property. Given the style rules:

and the markup

the words “emphasized text” will not have a border (since the initial value of border-style is none).

Notes

The inherit keyword allows authors to explicitly specify inheritance. It works on both inherited and non-inherited properties.

Specificity

The concept

Specificity is the means by which a browser decides which CSS property values are the most relevant to an element and therefore will be applied. Specificity is only based on the matching rules which are composed of css selectors of different sorts.

Note: Proximity of elements in the document tree has no effect on the specificity.

How is it calculated?

The specificity is a weight that is applied to a given CSS declaration based on the count of each selector type. In the case of specificity equality, the latest declaration found in the CSS is applied to the element. Specificity only applies when the same element is targeted. CSS rules that directly target an element will always take precedence over rules that an element inherits from an ancestor.

Selector Types

The following list of selector types is by increasing specificity:

  1. Universal selectors (i.e., *).
  2. Type selectors (e.g., h1) and pseudo-elements (e.g., :before).
  3. Class selectors (e.g., .example), attributes selectors (e.g., [type=”radio”]) and pseudo-classes (e.g., :hover).
  4. ID selectors (e.g., #example).

Inline style added to an element (e.g., style=”font-weight:bold”) always overwrites any styles in the CSS and thus can be though as having the biggest specificity.

The !important exception

When an !important rule is used on a style declaration, this declaration overrides any other declaration made in the CSS, wherever it is in the declaration list. Although, !important has nothing to do with specificity. Using !important is bad practice and should be avoided because it makes debugging more difficult by breaking the natural cascading in your stylesheets. When two conflicting declarations with the !important rule are applied to the same element, the declaration with greater specificity will be applied.

Some rules of thumb
  • Always look for a way to use specificity before even considering !important
  • Only use !important on page-specific css that overrides site-wide or foreign css (from ExtJs or YUI for example).
  • Never use !important when you’re writing a plugin/mashup.
  • Never use !important on site-wide css.
Instead of using !important, you can:
  1. Make better use of CSS cascading properties
  2. Use more specific rules. By indicating one or more elements before the element you’re selecting the rule becomes more specific and gets higher priority:

No matter what the order, the text will be green because that rule is most specific. (Also, the rule for blue overwrites the rule for red, notwithstanding the order of the rules)

You should use it when:

A) Scenario one:

  1. You have a global CSS file that sets visual aspects of your site globally
  2. ou (or others) use inline styles on elements themselves which is a very bad practice

In this case you could set certain styles in your global CSS file as important thus overriding inline styles set directly on elements.(!important与specificity无关,不影响specificity的计算,它的出现直接无视各种规则的specificity(当元素内部的inline styles遇到CSS文件里带!important的规则时也会被带!important的规则覆盖掉),除非其他规则也有!important。)

Real world example: Some badly written jQuery plugins that use inline styles.

B) Another scenario

How do you make awesome paragraphs always turn red, even ones inside #someElement? Without !important, the first rule will have more specificity and will win over the second rule.

How to override !important

A) Simply add another CSS rule with !important, and either give the selector a higher specificity (adding an additional tag, id or class to the selector), or add a CSS rule with the same selector at a later point than the existing one (in a tie, the last one defined wins).

Some examples with a higher specificity:

B) Or add the same selector after the existing one:

C) Or rewrite the original rule to avoid the use of !important altogether.

The :not exception

The negation pseudo-class :not is not considered a pseudo-class in the specificity calculation. But selectors placed into the negation pseudo-class count as normal selectors when determining the count of selector types.

Here is a CSS chunk:

when used with the following HTML:

Shall appear on the screen as:

This is in the outer div.

This text is in the inner div.

Form-based specificity

Specificity is based on the form of a selector. In the following case, the selector *[id=”foo”] counts as an attribute selector for the purpose of determining the selector’s specificity, even though it selects an ID.(如果是以属性选择器的形式来选择id,那么就按属性选择器来计算specificity,而不是按id来计算specificity)

The following style declarations:

when used with this markup:

Will end up looking like:

I am a sample text.

Because it matches they match the same element but the ID selector has a higher specificity.

Tree proximity ignorance

The proximity of an element to other elements that are referenced in a given selector has no impact on specificity. The following style declaration:

With the following HTML:

Will render as:

Here is a title!

Because the two declarations have equal selector type counts, but the html h1 selector is declared last.

Directly targeted elements versus inherited styles

Styles for a directly targeted element will always take precedence over inherited styles, regardless of the specificity of the inherited rule.

With the following HTML:

Will also render as:

Here is a title!

Because the h1 selector targets the element specifically, but the green selector is only inherited from the parent.

CSS syntax

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

The basic goal of the Cascading Stylesheet (CSS) language is to allow a browser engine to paint elements of the page with specific features, like colors, positioning, or decorations. The CSS syntax reflects this goal and its basic building blocks are:

  • The property which is an identifier, that is a human-readable name, that defines which feature is considered.
  • The value which describe how the feature must be handled by the engine. Each property has a set of valid values, defined by a formal grammar, as well as a semantic meaning, implemented by the browser engine.

CSS declarations

Setting CSS properties to specific values is the core function of the CSS language. A property and value pair is called a declaration, and any CSS engine calculates which declarations apply to every single element of a page in order to appropriately lay it out, and to style it.

Both properties and values are case-sensitive in CSS. The pair is separated by a colon, ‘:’ (U+003A COLON), and white spaces before, between, and after properties and values, but not necessarily inside, are ignored.

A CSS declaration

There are more than 100 different properties in CSS and a nearly infinitely number of different values. Not all pairs of properties and values are allowed and each property defines what are the valid values. When a value is not valid for a given property, the declaration is deemed invalid and is wholly ignored by the CSS engine.

CSS declarations blocks

Declarations are grouped in blocks, that is in a structure delimited by an opening brace, ‘{‘ (U+007B LEFT CURLY BRACKET), and a closing one, ‘}’ (U+007D RIGHT CURLY BRACKET). Blocks sometimes can be nested, so opening and closing braces must be matched.

A CSS block

Such blocks are naturally called declaration blocks and declarations inside them are separated by a semi-colon, ‘;’ (U+003B SEMICOLON). A declaration block may be empty, that is containing null declaration. White spaces around declarations are ignored. The last declaration of a block doesn’t need to be terminated by a semi-colon, though it is often considered good style to do it as it prevents forgetting to add it when extending the block with another declaration.

A CSS declarations block

The content of a CSS declaration block, that is a list of semi-colon-separated declarations, without the initial and closing braces, can be put inside an HTML style attribute.

CSS rulesets

If style sheets could only apply a declaration to each element of a Web page, they would be pretty useless. The real goal is to apply different declarations to different parts of the document.

CSS allows this by associating conditions with declarations blocks. Each (valid) declaration block is preceded by a selector which is a condition selecting some elements of the page. The pair selector-declarations block is called a ruleset, or often simply a rule.

A CSS ruleset (or rule)

As an element of the page may be matched by several selectors, and therefore by several rules eventually containing a given property several times, with different values, the CSS standard defines which one has precedence over the other and must be applied: this is called the cascade algorithm.

It is important to note that even if a ruleset characterized by a group of selectors is a kind of shorthand replacing rulesets with a single selector each, this doesn’t apply to the validity of the ruleset itself.

This leads to an important consequence: if one single basic selector is invalid, like when using an unknown pseudo-element or pseudo-class, the whole selector is invalid and therefor the entire rule is ignored (as invalid too).

CSS statements

Rulesets are the main building blocks of a style sheet, which often consists of only a big list of them. But there is other information that a Web author wants to convey in the style sheet, like the character set, other external style sheets to import, font face or list counter descriptions and many more. It will use other and specific kinds of statements to do that.

A statement is a building block that begins with any non-space characters and ends at the first closing brace or semi-colon (outside a string, non-escaped and not included into another {}, () or [] pair).

Statements

There are different kinds of statements:

  • Rulesets (or rules) that, as seen, associate a collection of CSS declarations to a condition described by a selector.
  • At-rules that start with an at sign, ‘@’ (U+0040 COMMERCIAL AT), followed by an identifier and then continuing up the end of the statement, that is up to the next semi-colon (;) outside of a block, or the end of the next block. Each type of at-rules, defined by the identifier, may have its own internal syntax, and semantics of course. They are used to convey meta-data information (like @charset or @import), conditional information (like @media or @document), or descriptive information (like @font-face).

Any statement which isn’t a ruleset or an at-rule is invalid and ignored.

There is another group of statements, the nested statements, these are statements that can be used in a specific subset of at-rules, the conditional group rules. These statements only apply if a specific condition is matched: the @media at-rule content is applied only if the device on which runs the browser matches the expressed condition; the @document at-rule content is applied only if the current page matches some conditions, and so on. In CSS1 and CSS2.1, only rulesets could be used inside a conditional group rules. That was very restrictive and this restriction was lifted in CSS Conditionals Level 3. Now, though it still is experimental and not supported by every browser, a conditional group rules can contain a wider range of content, rulesets but also some, but not all, at-rules.

Margin collapsing

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

Top and bottom margins of blocks (y轴方向上的margin、padding、width、height等对行内元素无意义,行内元素的高度可通过line-height来设置) are sometimes combined (collapsed) into a single margin whose size is the largest of the margins combined into it, a behavior known as margin collapsing.

Margin collapsing occurs in three basic cases:

Adjacent siblings

The margins of adjacent siblings are collapsed (except when the later sibling needs to be cleared past floats). For example:

Parent and first/last child

If there is no border, padding, inline content, or clearance to separate the margin-top of a block with the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block with the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.

Empty blocks

If there is no border, padding, inline content, height, or min-height to separate a block’s margin-top from its margin-bottom, then its top and bottom margins collapse.

These rules apply even to margins that are zero, so the margin of a first/last child ends up outside its parent (according to the rules above) whether or not the parent’s margin is zero.

When negative margins are involved, the size of the collapsed margin is the sum of the largest positive margin and the smallest (most negative) negative margin.

Margins of floating and absolutely positioned elements never collapse.

负margin值

让标题出现在内容区的边框上

代码如下:

效果如下:

示例标题
  • 床前明月光,
  • 疑是地上霜。
  • 举头望明月,
  • 低头思故乡。

将有宽度的元素在其容器中水平居中(元素若有高度,可同时垂直居中)

直接来竖直水平同时居中的代码:

效果:

out

in

可实现三栏中栏流动布局

所谓“三栏中栏流动布局”,就是说三栏里左栏和右栏的宽度都是固定的,中栏的宽度自动撑开。代码如下:

效果如下:

B