A deep understanding of the CSS box model and a deep understanding of the css box

Source: Internet
Author: User

A deep understanding of the CSS box model and a deep understanding of the css box

Http://www.chinaz.com/design/2010/1229/151993.shtml.

Source: http://www.sitepoint.com/web-foundations/css-box-model/

Links mentioned in this article: Floating and Clearing in CSS Collapsing Margins

When I was working on a project a few times ago, I encountered a small problem in page layout, so I went to stackoverflow for help. While helping me solve my problem, ifaou also recommended that I read an article about The CSS Box Model, The CSS Box Model, which has benefited a lot since reading it, only then can I know that my knowledge about the box model is still so lacking. At the end of the semester, the project is temporarily suspended and there is no time to spare. So I want to translate this article. On the one hand, I will give myself some more challenges and exercises, and on the other hand, I will give you some reference to help more people benefit.

This article is suitable for beginners of web design and gives you a closer understanding of the box model. However, before reading this article, you should have a certain understanding of basic knowledge such as the box model html. Otherwise, it will only make you more confused. This article does not describe the concept of the inner margin, outer margin, and how to locate the box model in an orderly manner like many Chinese tutorials. This article is more about how to control the width of the box, how to locate the box in the most appropriate way, and how to solve the box bugs in IE.

The reason why I translated this foreign article is that, during my study, I also found that foreign tutorials teach people to fish and give others to fish, compared with internal tutorials. Different from the Chinese tutorials, there are chapters, sections, and some entries. Their narration method is closer to the conversation style ...... All in all, the goal is to provide more beginners with some inspiration and help, without having to take many detours like me.

This is my first translation. please correct me if you have any shortcomings. I try my best to make it easy to understand and understand. I also added some of my own language experiences and diagrams to help me understand the translation. (In order to read smoothly, I will not express it any more ). Attached original address: http://reference.sitepoint.com/css/boxmodel

Deep understanding of The CSS Box Model)

If you understand the concept of the box model and how it determines the final size of an element, it will help you understand how an element locates on a webpage. The box model is mainly applicable to block-level elements. By the way, a related concept is introduced: inline layout model (inline layout model), which defines how to locate the element in the row. The InlineFormatting format is described in detail in this article.

Calculation of the box size (Calculating BoxDimensions)

In CSS2.1, block-level elements can only be rectangular. When we need to calculate the overall size of a block-level element, we also need to set the length and width of the content area [comment 1] together with the outer and inner margins of the element, and the border is included.

[NOTE 1]: the two concepts of content and content area are frequently mentioned in this Article. Although they can be literally understood as the content area in the box ), however, from the subsequent descriptions, the two concepts are still different. Until the publication of this article, I am still confused about the differences between the two concepts, I hope my friends who are interested in reading the original article can leave a message to tell me the difference between the two so that I can learn more about the errors in the text.

We can define the width and height of the content of an element by declaring the width and height. If no declaration is made, the default value of width and height will be auto)

The following figure shows the Box Model on w3schools:


Important: When you specifythe width and height properties of an element with CSS, you are just settingthe width and height of the content area. that is to say, when we design the width and height attributes of a block-level element in css, for example. in box {width: 100px; height: 100px}, the width and height are only set for the content section, that is, the length and width of the area in the dotted box under padding are defined. Instead of content, padding, and border sum (but in earlier versions of IE including IE6, the width and height of the box model were exactly defined in this way, although it is in line with the logic of people's thinking, but does not comply with the specifications, which may cause serious problems)

For static positioning elements (I .e. no positioning) whose width is automatic, and relatively positioned, remove the width of the contained block [comment 2] from all the outer margins, inner margins, borders, and scroll bars of this element. That is to say, the remaining value is to remove the horizontal margin, inner margin, border, and scroll bar (if any) of the element from the width of the contained block.

[NOTE 2]: contain block ). If you know the implementation principles of absolute positioning and relative positioning, this comment can be ignored. The inclusion block can be understood as a rectangle, which serves as a reference for the elements contained in it, the calculation of the size and position of an internal element is usually determined by the contained block of the element. For example, in absolute positioning, the ancestor element closest to it (position is fixed, relative or absolute) is the inclusion block. This is a relatively preliminary concept. I will not go into it. Please refer to Baidu.

Positioning attributes and dimensions of the included blocks are used as references for positioning and dimension calculation of child element. Although the positioning of elements must follow their block-level elements, they are not limited by it. The child element can also overflow the inclusion block. In most cases, generated boxes [Comment 3] usually plays the role of a child element containing blocks. To fully understand the details of the contained block, click ContainingBlock.

[NOTE 3]: I do not know how to translate the generated boxes. If you have any idea, please let me know. Thank you.

For floated and absolute positioning (absolutelypositioned) elements (including fixed positioning (fixed) elements), the width of the automatic status will shrink the generated box to keep close to its content size.

I think it is necessary for me to summarize the meaning of the first two paragraphs here. The first two paragraphs are all about auto when the width defaults ), the box model automatically sets the width in two ways.

We know that when we place a block-level element on a page, and do not set its location attribute (relative, absolute, fixed), that is, position: static, or set the position: in the case of relative, the block width is the extended width area automatically filled with its parent Element

For example:

.box1{ background:black; color:white; height:100px; padding:10px; border:20px solid red; margin:30px; }

Note: box1 does not set any position attribute or width attribute. This is for relative or non-positioning of the experiment.

Html code:

Result:


That is, the block width is the extended width area of the parent element that is automatically filled with it.

So when we calculate the width of a wrapped element, we only need to subtract the outer margin, border, inner margin, and scrollbar of the element from the parent element, the rest is its width because it is automatically filled. Although there is basically no practical application ......

But floating floated elements and absolute positioning elements have the opposite effect. They contract to keep the package close to the content.

.box2 { background:black; color:white; height:100px; padding:10px; border:20px solid red; margin:30px; position:absolute;}

The width is not set here, but the absolute positioning is performed. The html code is as follows:

Result:


Floating element and width

Previously, in CSS2, float elements with no declared width would not contract and stay close to them (shrink to wrap), on the contrary, they will constantly extend to be equal to the maximum width of their parent element. This behavior is replaced by contraction closeness in CSS2.1. However, in IE6 and earlier browser versions, a floating element with no declared width will still shrink its contents as a default setting, unless the child element has its own layout (has a layout) [Comment 3], for example, in this case, the parent element will stretch to adapt to the width of available content in the parent Element

[NOTE 3]: "One of the reasons why IE is different from other browsers is that the Display engine uses an internal concept called layout ...... On windows, IE uses the Layout Concept to control the size and positioning of elements. The "layout" elements are responsible for the size setting and positioning of themselves and their child elements. If an element "has no layout", its size and position are controlled by the closest ancestor element that owns the layout ...... Layout is the root cause of many IE display bugs. "-- from CSS Mastery Advanced WebStandards Solutions (Second Edition) by Andy Budd, Simon Collision, and Cameron Moll) (proficient in the second edition of CSS advanced Web standard solutions)

As mentioned above, for floating elements with no declared width, both IE6 and earlier versions adopt the behavior of shrinking close to content, so this statement cannot be proved, I also tested it in IETest.

It should also be noted that when a floating element (with no declared width) contains a child element floating to the right, it will also automatically extend and fill, to adapt to the width of available content of the parent element. This situation exists in earlier ie browsers, including IE7 (this bug exists in earlier Firefox versions, including version 2.0, but this problem has been solved in Firefox3.0 Alpha 6 ).

I also wrote an example for the above section:

<div class="parent">          <div class="containing-block">                 <div class="box">For floated or absolutely positioned </div>           </div>            </div>

In contrast: the first is a floating element containing-block, which contains a child element box floating to the right. The parent element is parent ......

.box { background:black; color:white; height:100px; padding:10px; border:20px solid red; margin:30px; float:right; }.containing-block { background:blue; height:250px; float:right; }.parent { background:gray; height:300px; width:500px; }

The running result in Firefox is:


However, in IETester, IE5.5 is used to run:


Therefore, to avoid the bug mentioned above, it is always safer to specify a specific width value for a floating element if possible. In any case, as long as you always pay attention to the problems mentioned above, you may find that the float without width is very useful in some cases, such as the layout menu of the horizontal flow (fluid-width ).

Regardless of how the content area is located, if the height, min-height, and max-height are not declared, the content area height is the same as the content height [Note 4].

[NOTE 4]

Therefore, to determine the size of an element on a page, add the declared padding, border, and margin values to the content area. Of course, if an element has no padding, border, or outer margin, its size is determined only by its content.

If an element only contains floating or absolute positioning elements, and it does not have any content, its height will be 0. We will discuss more in Floating and Clearing

Implement the Box Model

The best way to illustrate the box model is to use a short example. Let's take a look at the size required to place an element on the page (ignore the overlay effect of the outer margin first-the following will be a more detailed description of this ):

Total width = left margin + left border + left padding + width +

Right padding + right border + right margin

Total height = top margin + top border + top padding + height +

Bottom padding + bottom border + bottom margin

Here is our CSS sample -- declare the attributes of the box for an element named 'box:

.box {width:300px;height:200px; padding:10px; border:1px solid #000; margin:15px;}

The total size calculated for the above elements is:

Total width = 15 + 1 + 10 + 300 + 10 + 1 + 15 = 352px

Total height = 15 + 1 + 10 + 200 + 10 + 1 + 15 = 252px

The above computation is described in figure 1, which is taken from the Firebug element layout display,


In Figure 1, we can clearly see that the content area is in the center around the content area's padding area, border area, and margin area. The outer edge of the content area is referred to as the content edge or the inner edge. The outer edge of the inner edge is referred to as the padding edge ); the outer edge of the border area is called the border edge; the outer edge of the outer margin area is called-you can guess-the outer margin edge (margin edge) or outer edge)

You can see from this short example that to adapt this element to this page, we need an area of at least 352px width and 252px height. If the available zone is smaller than this, this element will be misplaced or overflow its contained block. Note that in IE6 or earlier browser versions, the extra height of the contained block will be stretched to accommodate the content area, which will obviously disrupt the layout of the webpage. However, browsers of other versions may expose elements to their boundaries and ignore the content.

This Bug is translated as: "If the content of an element is larger than that of the element itself, we want the content to flow out of the element. However, in IE6 and earlier versions, layout elements may be incorrectly expanded to adapt to the content size ...... This error means that the width in IE on the Window is actually more like min-width "-- Andy Budd, Simon Collision, Cameron Moll's CSS Mastery Advanced Web Standards Solutions (Second Edition) (proficient in the second edition of CSS advanced Web standard solutions). It is very simple:

<div class="IEbug">       <p>Your understanding of the box model concept, and how it relates to the way in which an element,  final dimensions are determined, </p></div>

.IEbug { background:yellow; width:100px; height:100px; }

Test results of Firefox:


Test results in IE6:


Margin overlay Effect

Although the preceding example of calculating the area size required by the element is included in the calculation, note that the vertical non-location (static) the adjacent outer margin of an element is combined into a larger value of the outer margin, not the sum of the two. This means that when the calculation actually needs to store the area of an element, it is not counted from the edge of the outer margin, only the widest margin will take effect, and the narrow margin will overlap with a large margin. Read CollapsingMargins to learn more about this complicated topic.


Actual Box Model Application

It is worth noting that when the width of an element is set to 100% (that is, the content width of the parent element is 100%), it should not have any margin or padding, or border, which only requires a larger area for the area to be placed. This is often ignored by designers and seriously disrupts the page layout. In this way, the content will either overflow or make the elements wider than they should be.

<div class="contain">     <div class="box"></div>     </div>

There is no margin or padding, and only the CSS in the case of width:

.box { background:black; width:100%; height:100px; }.contain { background:yellow; height:120px; width:200px; }

Effect:


It can be seen that, without margin and padding, 100% of the content can be filled with the parent element properly.

After adding margin and padding (margin: 10px; padding: 10px ;),


Layout diagram in firebug:


After adding margin and padding, the elements are misplaced and only the left-side margin can be displayed.

The solution is to avoid adding specific values to the width attribute (not automatically) In most cases, and apply only the outer margin, inner margin, and border. The width of the element without positioning is automatically set by default. Even if the padding, border, and outer margin are defined, it still considers the available content width to be full.

Of course, this method may not work for some examples. For example, when an element is not a non-locating element, and it does need a specified width (just as the floating element does not automatically fill its parent element ). In these cases, you have two options.

If the available area is fixed in width, you can simply add the width of each attribute element (such as margin and padding) to match the available fixed width. For example, if the available area width is PX and you need an element with an internal margin of 20 PX, you can simply set the width of this element to PX, the padding is 20px (20 + 460 + 20 = 500 ). In this method, the prerequisite is that the width value and the element box attribute use the same measurement unit, because you do not want to add the mixed unit (200px + 10%, just for example, this method is meaningless in the content ).

When the width of the available content area is unknown-for example, in fluid layout-this method does not work, because the percentage (percentages) and pixel (pixels) cannot be added together. In this case, the solution should be to declare a 100% width value for the required elements, and set the padding, border, the value of the outer margin is set to an element nested in it. This nested element does not have any width value declaration, and can display the expected padding, border, and margin without interfering with the parent element. [Note 5]

[Note 5] Well, I have not understood this paragraph ......

Now you should be able to clearly understand the CSS box model.

Note: Due to my limited level, translation may not be very popular in many places. I only hope that I can play a leading role and have more friends to improve it, pointing out that my translation and understanding are incorrect. If time permits, I will continue to translate some column articles (links in this article) related to this ).

Finally, I would like to recommend the CSS Mastery Advanced Web Standards Solutions (Second Edition) written by Andy Budd, Simon Collision, and Cameron Moll (proficient in the Second Edition of CSS Advanced Web standard Solutions ), when translating this article, I have referenced many of the content. This is also an advanced CSS book and is not suitable for beginners. For more information, see.






CSS box theory?

You can refer to this article
Thoroughly understand the CSS box mode

Understanding the CSS Box Model

What is the CSS box mode? Why is it a box? First, let's talk about the attribute names that we often hear in web design: content, padding, border, and margin all have these attributes.

Css, for the Box Model

According to the W3C box model, the last is 120 = 100 + 10 + 10
In IE6, 100 is displayed.
When no DTD document is declared, the IE series browsers also display this width as 100 (compatible/weird mode ).
Of course, the error message "100" is only an incorrect explanation of IE ......

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.