New knowledge storeFront end from entry to groundFor attention, star and suggestions, update from time to time ~

If you think it’s good, please give it a thumbs up

Highlight: All the examples in this article are hand-typed HTML examples, and you can directly select the examples and debug them on the console for easy verification of ideas. If you find the sample easy to debug, I’m here for a thumbs up

Margin overlap

Margin overlap is margin-collapse. The margins of two adjacent boxes (which may be siblings or ancestors) can be combined to form a single margin. This merging of margins is called folding, and the combined margins are called folded margins.

The folding results follow the following calculation principles:

  • When two adjacent outer margins are positive, the result of folding is the greater of them;
  • When two adjacent margins are both negative, the result of folding is the greater value of their absolute values;
  • When two margins are positive and negative, the result of folding is the sum of them;

Some of you might look at this and think, oh, I’ve had this happen to me while making lists.

Other people might be thinking, what the hell is this? I’ve never seen this before. Isn’t this a CSS bug?

So let’s talk about what happens when you don’t get margin overlap

  1. Horizontal margins never overlap.
  2. If one of the adjacent box models is floating, the vertical margins do not overlap, nor do the vertical margins between the floating box model and its children.
  3. The margin between the element with overflow set and its children is not overlapped (unless overflow is visible).
  4. With the box model set to position: Absolute, vertical margins do not overlap, nor do they overlap with their children.

Wait, let’s not enumerate this, but why do these conditions look so familiar? B: well… That’s the condition for generating a BFC…

What is BFC?

Block formatting context (BFC). It is a separate rendering area, with only block-level box participation, which dictates how the internal block-level box is laid out and has nothing to do with the outside of the area.

We often say that the document flow is actually divided into location flow, floating flow, common flow three kinds. Normal flow is the FC of BFC. FC(Formatting Context) is a rendering area on a page that has a set of rendering rules that determine how its sub-elements are positioned and how they relate to and function with other elements.

Introduce Box and Formatting Context first.

Box: basic unit of CSS layout

Boxes are the object and basic unit of CSS layout. In plain English, a page is composed of several boxes. The element type and display attribute determine the type of the Box. Different types of boxes are involved in Formatting the Context (a container that decides how to render the document), so elements inside the Box are rendered in different ways.

  • block-level box:displayElements with attributes block, list-item, or table generate block-level boxes. And participate in the Block fomatting context;
  • inline-level box:displayAn element with attributes inline, inline-block, or inline-table generates an inline-level box. And participates in inline formatting context;
  • run-in box: CSS3 is available, but I won’t talk about it here.

Formatting Context

Formatting context is a concept in the W3C CSS2.1 specification. It is a rendering area of the page with a set of rendering rules that determine how its children will be positioned and how they will interact with other elements. The most common Formatting contexts are Block fomatting context (BFC) and Inline Formatting context (IFC).

Elements with BFC characteristics can be viewed as separate containers, the elements inside the container do not affect the layout of the elements outside, and BFC has some characteristics that normal containers do not have.

BFC layout restriction rules

  • The internal boxes will be placed vertically, one on top of the other.

  • The vertical distance of the Box is determined by margin. Margins of two adjacent boxes belonging to the same BFC will overlap.

  • The left side of the margin box of each box (block box vs. row box) touches the left side of the border box containing the block (for left-to-right formatting, otherwise the opposite). This is true even if there is a float. That is, a BFC neutron element does not exceed its inclusion block.

  • The region of the BFC does not overlap with the float box.

  • A BFC is a separate container on a page, and the child elements inside the container do not affect the outside elements. And vice versa.

  • When calculating the height of the BFC, floating elements are also involved.

BFC trigger mode

  1. The root element, the HTML tag
  2. Float elements: Float values are left and right
  3. The overflow value is not visible, but auto, Scroll, and hidden
  4. The display value is inline-block, table-cell, table-caption, table, inline-table, flex, inline-flex, grid, inline-grid
  5. Positioning elements: Position values are Absolute and fixedNote: display: tableThe BFC can also be generated because the Table generates an anonymous table-cell by default. This anonymous table-cell generates the BFC.

Landing the role of

The BFC is a separate container on the page, and the child elements inside the container do not affect the outside elements and vice versa. We can do a lot with this feature of the BFC.

1. Margins of the same BFC fold

<div class="container">
  <div class="inner"></div>
  <div class="inner"></div>
</div>
Copy the code
.container{
  display: inline-block;
  border: 1px solid grey;
}
.inner{
  width: 20px;
  height: 20px;
  margin: 20px;
  border: 1px solid grey;
  background: lightblue;
}
Copy the code

In effect, because both div elements are in the same BFC container (here, by setting container to display: Inline-block) so the bottom margin of the first div overlaps the top margin of the second div, so the two boxes are only 20px apart instead of 40px.

First of all, this is not a CSS bug, we can understand it as a specification, if you want to avoid overlapping margins, you can put it in a different BFC container.

<div class="container">
  <div class="inner"></div>
  <div class="container1">
     <div class="inner"></div>
  </div>
</div>
Copy the code
.container{
  display: inline-block;
  border: 1px solid grey;
}
.container1{
  display: inline-block;
}
.inner{
  width: 20px;
  height: 40px;
  margin: 40px;
  border: 1px solid grey;
  background: orange;
  overflow: hidden;
}
Copy the code

Here, put the second div into Container1 and make it generate the BFC by setting the container to display: inline-block. This way, the two inners are under different BFC and the margins do not overlap. The distance between the two boxes is 40px.

Ps: This sample is written in HTML. You can debug it on the console by clicking on the sample

2. BFC can contain floating elements (clear floating)

Floating elements are removed from the normal document flow. Consider the following example

<div class="container">
    <div class="inner"></div>
</div>
Copy the code
.container{
  border: 1px solid grey;
}

.inner{
  width: 20px;
  height: 20px;
  margin: 20px;
  background: orange;
  float: left;
}
Copy the code

Chestnuts, including the line below

Because the elements in the container float out of the document flow, the container is left with a margin height of 2px. If the BFC of the container is triggered, the container will be wrapped with floating elements.

Make the container generate the BFC with Overflow: Hidden

.container{
  border: 1px solid grey;
  overflow: hidden;
}
Copy the code

This example can also be directly click debug oh ~

3. The BFC prevents elements from being overwritten by floating elements

Do you really know how it works? I’ll give you a floating hidden effect, and in exchange, you give me a thumbs-up

Before I explain what that does, let me explain what float is. Okay

What is floating

When the element is floated, it leaves the flow of the document, rises half a level, and moves in the specified direction until it hits the boundary of the parent element or another floating element stops

What is hierarchy

If the entire element is considered a layer, the lower half is the element itself (background style, etc.) and the upper half is the content within the element

For example,

<div class="container">
  <div class="box1">box1</div>
   <div class="box2">box2</div>
   <div class="box3">box3</div>
</div>
Copy the code
.container{
 width: 40px;
 border: 1px solid black;
}
.container div{
  width: 100%;
  height: 30px;
}
.box1 {
  background: yellow;
}
.box2 {
    background: orange; 
}
.box3 {
     background: pink; 
}
Copy the code

When all three boxes are not floating

box1
box2
box3

When you add float:left to box2, the arrangement of three boxes becomes

box1
box2
box3

As Box2 floats out of the document stream, Box3 moves up and is obscured by Box2. But the text box3 in the box3 box has not moved up!!

The little knowledge

  1. Floating elements float between each other and do not form a flow. Floating elements always align their top with the bottom of the element from the previous standard flow (unfloated elements).
  2. Position: absoluteandfloatIt’s going to change implicitlydisplayType, in addition todisplay:noneOutside, as long as set upPosition: absoluteorfloat, will make the elementdisplay:inline-blockThe length and width can be set

With floating effects out of the way, let’s look at an example of an element being covered by a floating element

<div class="container">
  <div class="left">I'm a left floating element</div>
  <div class="right">I'm an element that doesn't set the float and doesn't trigger the BFC, part of me is overwritten</div>
</div>
Copy the code
.left{
  width: 100px;
  height: 50px;
  background: orange;
  float: left;
}
.right{
  width: 200px;
  height: 200px;
  background: lightblue;
}
Copy the code
I’m a left floating element
I’m an element that doesn’t set the float and doesn’t trigger the BFC, part of me is overwritten

The second element is partially overwritten by the floating element (but the text message is not overwritten by the floating element, as explained in the floating example above). If you want to avoid overwriting the element, use the BFC feature of the second element and add overflow: hidden to the second element.

I’m a left floating element
I am an element that has no set float, but triggers the BFC, and I am complete again

This method can be used to implement a two-column adaptive layout by setting the width of the Container and removing the width of the right. The width on the left is fixed and the content on the right ADAPTS to the width.

Ps: It is recommended to debug this example on the console

Ps: I usually use display: flex, then set the width on the left and flex: 1 on the right. This method can also be used vertically. I often use this method to set the height of scroll lists

Examples are as follows:

<div class="container">
  <div class="left">The element on the left, constant width</div>
  <div class="right">The element on the right dynamically fills the remaining space</div>
</div>
Copy the code
.container{
  width: 400px;
  display: flex;
  border: 1px solid grey;
}

.left{
  width: 100px;
  height: 50px;
  background: orange;
}
.right{
  height: 200px;
  flex: 1;
  background: lightblue;
}
Copy the code
The element on the left, constant width
The element on the right dynamically fills the remaining space

You can adjust the width of the Container on the console and the elements on the right will fill in automatically

Example of margin overlap

Having talked about BFC and what it does, except for the most intuitive one, where margins fold for the same BFC, let’s look at other examples where margins overlap

1. When an element is contained in another element, there will be overlap between the child element and the parent element. After overlap, the outer space is equal to the largest one

Chestnuts are as follows:

<div class="container">
  <div class="title">This section is easier to see the margin-top of the block below.</div>
  <div class = "content">
    <div class="inner">Child elements margin - top: 20 px;</div>
    <h2>The parent element</h2>Margin-top is not set</div>
</div>
Copy the code
.container{
  width: 400px;
  border: 1px solid grey;
}
.title{
  height:50px;
  background: #eee;
 }
.content{
  height:200px;
  background: #88f;
}
.inner{
  height:100px;
  margin-top:20px;
  background: #0ff;
  width:200px;
}
Copy the code
This section is easier to see the margin-top of the block below.
Child elements margin – top: 20 px;

The parent element

Margin-top is not set

The parent element overlaps the child element margin-top, resulting in the parent element with a margin-top of 20px.

You can set Overflow: Hidden to solve this problem. You can check out the examples and try out other solutions for yourself on the console.

2. If an empty element has no content, its top and bottom margins will overlap.

<div class="container">
  <div class="inner"></div>
</div>
Copy the code
.container{
  width: 200px;
  border: 1px solid grey;
}
.inner{
  margin-top:20px;
  margin-bottom: 20px;
}
Copy the code

The height of this box is only 20px, so a small change to the inner element, such as adding text, or adding a border, will break this phenomenon. Open the console and try out any solutions.

Ok, so that’s the end of margin overlap, BFC, and float. Any thoughts and comments are welcome in the comments. If you learn something new, please give me a like and let me know

This article contains: a journey of large front end foundation building from scratch (simple and profound, constantly updated ~)

Recommended reading:

  • Take you rolled a belongs to own the react project | webpack + Babel + typescript + eslint didn’t ridden a project of the couple must not to be missed, take you unlock fast development tips

  • In a few words with you to understand the “closure” | add usage scenario is very simple to explain why going?

  • Chaohuaxishi, re-introduction of inheritance and prototype chain has a picture of the truth

  • Reflow and Repaint, KFC and MC are mentioned at the same time every time. The relationship is almost as close as MC beside KFC.

  • Viewport and 1 px | tools: this is a 1 px, designer: no, it isn’t

I’m not good at designing, but I’m good at fighting

  • Edible “dry” CSS layout, pure Html example, can debug | horizontal, vertical, multiple columns can watch, adjustable, can be taken away, the only, no branch

  • Front end must master “CSS cascade context” explain | handmade sample, BaoJiao package will sister with cat, what do you want?

Reference Documents:

  1. What is BFC? This one is enough
  2. 10 minutes Understanding the PRINCIPLE of BFC
  3. Important BFC in the CSS
  4. CSS Margin Overlap and prevent method margin overlap solution (BFC)