What exactly is the collapse problem in CSS? How should margin and padding be distinguished

Front end Stark 2021-09-15 09:08:46
exactly collapse problem css margin

css The basic chapter ( Third articles )


In the last article, we basically understood css in background Comprehensive writing and css Weight priority problem in , In this lecture, we will know a more important padding and margin, And will learn css Collapse in , This is an essential part and even quite important in future work and study . If you don't know or are not familiar with css Basic words , I suggest you take a look at the previous space , This one goes on css Let's start .

See through the essence of web pages

In modern times html Layout , We basically use the box model to layout , In short, use div Layout , So the control of the whole box is a key point in the future . The most important thing is to learn “ Have a plan in mind ”, When you get the design draft , You must think before you write , Thinking is a very important thing .

Box model

The box model is generally divided into three parts

  • padding ————padding
  • Margin ————margin
  • Frame ————border

Box frame

Now let's talk about the frame of the box , Borders are also very important in the future , Basically, boxes use borders .

  • border-width: Define border thickness , The unit is px
  • border-style: The style of the border
    1. solid: Solid line
    2. dashed: Dotted line
    3. dotted: Dotted line
  • border-color: Border color
  • Comprehensive writing :border:2px solid red;( There is no order )

Be careful : Comprehensive writing is very important , In the future work is the most used habit . So we must learn to write comprehensively , Write more and you'll get familiar with it .

besides , The box can also set lines in different directions , for example : You can set the upper line and the lower line, etc . As shown in the figure below


 // Structure code
<div class="content">
<div class="content-a"></div>
<div class="content-b"></div>
<div class="content-c"></div>
<div class="content-d"></div>
// Style code
.content {
display: flex;
.content div {
width: 200px; height: 200px;
margin-left: 20px;
/* There is only one line above the box */
.content-a {
border-top: 1px solid red;
/* There is only one line below the box */
.content-b {
border-bottom: 1px solid red;
/* There is only one line on the left in the box */
.content-c {
border-left: 1px solid red;
/* There is only one line on the right in the box */
.content-d {
border-right: 1px solid red;
 Copy code 

Another one is also more important , If the boxes are adjacent , There must be a line in the middle of the two boxes that overlaps , So if you want to eliminate this overlapping line , If the box lines are the same, you need to use

// Indicates that adjacent borders are merged
 Copy code 


padding : The distance between the content and the border

  • padding-left: Left inner margin
  • padding-right: Inside right margin
  • padding-top: Top inner margin
  • padding-bottom: Bottom inside margin

about padding There are still short forms , This is also used in more ways in daily work .

  • padding:20px Express : The top, bottom, left and right inner margins are 20px
  • padding:10px 20px Express : Up and down 10px, about 20px
  • padding:10px 20px 30px Express : On 10px about 20px Next 30px
  • padding:10px 20px 30px 40px Express On 10px、 Right 20px、 Next 30px、 Left 40px
Size calculation of the inner margin of the box

After setting the inner margin, the distance between boxes must be calculated , If you give the box a width and height , Give again padding value , The box will expand , If you want the size of the original box , You have to subtract padding Value Here's the picture


  • At this time, there is no setting padding The value box is displayed normally

Let's now add a... To the box padding-left:20px Let's see what happens Here's the picture

1631029381802_EC228F40-F673-4158-9A52-55C033D86342.png in summary , It can be seen that , If width and height are set , Plus padding value , The box will appear to increase unnecessary values , So you need to subtract the corresponding padding value , Let the box return to its previous size . For example, in padding Add... To the left and right 20px, Then the width of the box needs to be corresponding from 200px Subtract to 180px, To ensure that the size of the box remains the same , But if you don't want to use this way , You don't add width or height , Then add... To the box padding Attribute words , It won't open the size of the initial box


The outer margin refers to the outer margin of the box , use margin To express , and padding The usage of is basically the same , It's just padding It refers to the inner margin of the box , and margin It's about the outside distance of the box .

  • margin Except for the right outer margin of the box , You can also center the box , There are generally three ways to write
  1. margin-left:auto,margin-right:auto
  2. margin:auto
  3. margin:0 auto( The most commonly used )

So be sure to remember the following two ways to center , This will be used quite a lot in future work

  • text-align:center———— Center text
  • margin:0 auto———— Indicates that the box is centered

Difference between insert picture and background picture

Background pictures and insert pictures are also used very much in our future work , Because the demand for mixed layout of graphics and text is very much , Moreover, it is often necessary to perform pixel level restoration against the design draft .

  • The background picture must be in background-position:30px 30px; To move the position
  • Insert pictures through margin Mobile

Initialize and clear the inner and outer margins of the element

Remember in the previous article that , Because the browser initialization will have a default padding and margin, Most front-end people don't need these original styles , Because it's hard to control when restoring the design draft , So it will initialize a css file , Clear all the default styles inside, and set some styles you like, etc . And that's where it comes in * , Initialization will padding and margin Set to 0

// Initialization will padding and margin Set to :0
* {
 Copy code 

Outer margin merge ( Also known as : Collapse )

This problem is a long-standing problem , And it is a pain point that every front-end personnel must experience , yes css The most ridiculed question in history .

- Two outer margins , If one is set to the bottom , One set the top , There will be an outer margin merge . Take a merge , Let's take a look at it in detail as shown in the figure below


As you can see from the diagram first and second Two div They are all set 20px Outside distance of , It is reasonable to say that the last thing is 40px, But there is the problem of outer margin merging , The two outer margins will be merged to take Maximum value , So the last two boxes are apart 20px.

The outer margins of nested relationships are merged

Nest a sub box in a box , If the sub box is set margin Words , Then the parent box will fall down with the child box , This leads to the problem of collapse . As shown in the figure below

1631112358798_F2A0F962-6BB1-4fcd-85E1-CF004D714CA0.png If you want to solve this problem, the most common way is Add a... To the parent element overflow:hidden after , Is a normal display , Here's the picture .

1631112529599_EE7700EC-7FCE-4eb7-ACD8-23259EE03FCB.png In addition, there are two ways to solve the problem of collapse :

  1. You can define an upper border for the parent element to solve
  2. You can define an upper and inner margin for the parent element to solve
  3. Add... To the parent element overflow:hidden( The most commonly used )

Okay , Outer margin merge / That's basically the problem of collapse , You can go down and try it in the code yourself , We will often encounter these problems in our future work , The foundation must be skilled .


Rounded border

Before css There is no concept of fillet in , So it is very troublesome for front-end programmers to write rounded corners , But since css In the border-radius Then it saved the problem of no fillet . As shown in the figure below


Set... In the figure The box , After setting border-radius:50%, It will show that the whole box has become a circle , In the second, if you want the subsequent search box or button, also known as a circle, to look closer to the user experience , You can set Half the height , An oval will appear . This is also often used in work , You can practice in your own code .

Box shadow

Box shadow is also an important knowledge point , Because the style in the front end will certainly be similar to reality , Therefore, the problem of box shadow will also appear in the page .

  • grammar :box-shadow: Horizontal shadow Vertical shadows A fuzzy distance ( Deficiency and excess ) Shadow size Color (rgba(0,0,0,0.3))
  • for example :box-shadow:2px 2px 2px 2px rgba(0,0,0,0.3)

1631114296141_3128BF3C-FB71-49d8-B48C-2640574D6DFC.png down , You can practice more in your code

Okay , Today's css The third part is over , Welcome to leave a message ~

本文为[Front end Stark]所创,转载请带上原文链接,感谢

  1. Vue learning -- watch listener
  2. Learn more about nexttick in Vue
  3. JavaScript genrator generator
  4. La dernière réponse à l'entrevue de développement Android, l'hiver froid de l'industrie
  5. Maserati's motorcycle has less than 10 in the world. It is definitely a work of art
  6. 2021 partage des questions du dernier examen écrit d'entrevue Android, pas d'accord
  7. Programmation asynchrone Java scirp, développement frontal de base
  8. 2021 dernier examen écrit d'entrevue Android, écrit trop bien
  9. Quels aspects doivent être pris en considération dans le tableau principal du distributeur libre - service?
  10. He inherited his mother's hundreds of millions of property for his boyfriend to squander. Unexpectedly, he was ruthlessly abandoned when he had 100 yuan left
  11. The fuel cost is half less than that of fuel vehicles at the same level. Is it really cheap to use song Pro DM?
  12. Le dernier résumé de l'expérience d'entrevue d'embauche de l'école Android de l'usine est nécessaire pour l'usine
  13. Le dernier dictionnaire avancé de programmeurs d'usine, l'expérience d'entrevue d'embauche de l'Agence de développement Android
  14. La dernière collection d'entrevues Android Golden nine Silver ten
  15. L'expérience d'entrevue de l'Ingénieur d'algorithme de saut d'octets, 2 mois d'entrevue Tencent, station B, Netease et ainsi de suite sur 11 entreprises résumé!
  16. La dernière collection d'entrevues d'Android Golden nine Silver ten recommande un projet github
  17. Yuan Li's recent situation revealed that he was obsessed with public welfare, dressed simply and fearless, grew fat, and married an 11-year-old husband
  18. Initial experience of template tool plop of [front end Engineering]
  19. Dernière question d'entrevue avancée et réponse d'Alibaba Android, Alibaba P8 vous apprendra en personne
  20. Partage des dernières questions d'entrevue pour Android haute fréquence, Introduction aux compétences d'entrevue pour le développement d'Android
  21. Partager les dernières questions d'entrevue Android haute fréquence avec quelques conseils
  22. About JavaScript modules
  23. Iteratable object and class arrays
  24. Function realization of Vue elementui exporting excel form
  25. Use canvas to realize a small screenshot function
  26. Object oriented programming (2)
  27. Several common value transfer methods between Vue components
  28. Démarrer avec le serveur de base zéro: Hello World
  29. J'a I construit un escalier pour aller sur la lune, combien de façons puis - je poursuivre la sœur Chang'e?
  30. CSS implémente la fonction d'expansion et d'arrimage du Texte multiligne
  31. Varlet CLI | vue3 Component Library Quick Prototyping Tool
  32. Belle vue sur les trois rivières Xiapu
  33. La partie Web qui déploie SharePoint ajoute son propre module de fonctionnalité
  34. React Native (mise à jour à long terme)
  35. La conception et le codage de l'arbre binaire requis pour chaque entrevue d'embauche de la société Java millet;
  36. 10 jours pour obtenir l'offre d'emploi Android d'Alibaba, entrevue Android
  37. A remporté avec succès Byte, Tencent, Pulse offer, 7 ans Java une expérience d'entrevue de baise,
  38. 10大前端常用算法,web应用与开发
  39. Nginx - minimum configuration! You deserve it
  40. Les questions d'entrevue couramment utilisées pour le cadre Java sont - elles prometteuses pour le développement Java?
  41. 10 algorithmes communs de première ligne, applications Web et développement
  42. 10大前端常用算法,移动web开发教程
  43. 10大前端常用算法,新手学web前端开发
  44. After brushing: wireless routing + USB offline Bt + remote management!
  45. Le vrai problème de l'entrevue Android d'Alibaba pour les années civiles 2019 - 2021, le tutoriel d'apprentissage Android
  46. 10 principaux algorithmes de première ligne couramment utilisés, nouveaux apprenants développement de première ligne Web
  47. 118页Vue面试题总结,web中间开发
  48. 118页Vue面试题总结,HTML列表标签
  49. Use vscode snippets to work with project members to improve development efficiency
  50. CentOS + Jenkins + nginx + gitlab front end automation deployment full record
  51. Build applet architecture from scratch
  52. Uni app series (V): hbuilderx runs the uniapp project to the page, views the preview and solves NPM: the error that the file cannot be loaded
  53. Front end interview daily 3 + 1 - day 877
  54. Understand the react lifecycle function
  55. 2020-2021前端面试题合集,web开发敏捷之道
  56. CSS - redraw reflow
  57. 90 lines of code to implement the module packer
  58. Front end internship interview preparation -- react others
  59. 118 page vue sommaire des questions d'entrevue, onglet liste HTML
  60. Vue sommaire des questions d'entrevue, développement intermédiaire du Web, 118 pages