search
HomeWeb Front-endCSS TutorialDetailed explanation of the special usage skills of CSS margin

This time I will give you a detailed explanation of the special usage techniques of CSS margin, and a detailed explanation of the special usage techniques of CSS margin. What are the precautions? The following is a practical case, let's take a look.

1. Introduction

marginWe are generally used to calling it margins. We can set the margins in four directions respectively. No more details here. Describe the assignment syntax in detail.

Actually, the margins we usually set are physical-level settings, and margins also include start, end, before, after, etc. These are mainly logical-level settings. If you are interested, Google it yourself. .

When setting margin, we must know:

  • For block-level elements, how effective is margin in four directions;

  • For inline elements, margin is only effective in the horizontal direction.

2. Box model

Speaking of margin, I have to talk about the box model :

1. From the inside and outside content => padding => border => margin

The reason why the box model must be understood from the end is mainly because the standard of the box model is not The same, it also determines what the width we set in CSS is. At this time, everyone will think of those calculation formulas. In fact, with the arrival of CSS3, we can set the standard of the box model through box-sizing:

2. border-box: width is calculated from border;

3. content-box: width is calculated from content;

4. padding-box : Removed from the standard.

Here’s another picture, are you already aware of it?

##3. Margin overlap problem

This kind of problem mainly occurs on block elements and not floating elements (it is not described clearly here, and will be discussed in detail later). Let's take a look at what happened.

1. Margin overlap that occurs between adjacent sibling elements

    .a {
        margin: 50px 0;
    }
    .b {
        margin: 100px 0;
    }

##Margin overlap between adjacent sibling elements


In this case, margin overlap occurs. The distance between adjacent sibling nodes is the maximum margin value. The best way to avoid this situation is to set only margin-top or

margin- in the vertical direction. bottom

.

2. Margin overlap occurs at parent-child nodes

    p(class="b")
    p(class="a")
        p(class="c") C
    .a {
        margin: 20px 0;
    }
    .b {
        margin: 100px 0;
    }

Margin overlap occurs at parent-child nodes


Follow the following here Our understanding should be that a is 20 pixels away from b, and c is 100 pixels away from a. But this is not the case. Here we can solve the overlapping problem through the following methods:

    The parent element sets the border;
  • The parent element sets the padding ;
  • The parent element sets overflow to hidden or scroll, others are not applicable;
  • The parent element sets position to fixed or absolute, others not applicable.

4. Magical negative margin valueWe set the margin in four directions for a block element What happens:

    Setting negative values ​​for top and left will move the element up or left by the corresponding pixel distance;
  • setting bottom and right Negative values ​​will move adjacent elements up or to the left.
  • There is another point here. When I checked the information, I found that many people said that negative margin can change the width of the element. I would like to correct it here. This is not a characteristic of negative margin. , but the characteristics of margin. For example, the following CSS can completely set the width of block-level elements.
    .item {
        margin: 0 200px;
        height: 200px;
    }

对于margin赋值在布局的应用很广泛,比如我们已知一个元素的宽高,你可以通过margin负值居中。

    .item {
        position: absolute;
        background: red;
        width: 200px;
        height: 200px;
        top: 50%;
        left: 50%;
        margin-top: -100px;
        margin-left: -100px;
    }

五、margin与float

对于这两个让人头疼的属性混到一起,我只想说,真的很爆炸。上面我说过“这种问题主要发生在block元素上并且不是浮动元素”,这里要再补充两点:

  • 相邻兄弟元素,如果两者多是浮动元素,则不发生margin重叠;

  • 父子元素,如果其中一个是浮动元素,则不会发生margin重叠;

主要还是由于浮动元素不在正常的文档流中,所以还是用上清除浮动的方法比较好。(一下为bootstrap的实现方式)

    .clearfix::before, .clearfix::after {
        content: " ";
        display: table;
    }
    .clearfix::after {
        clear: both;
    }

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

你不知道的冷门CSS属性

href和src、link和@import有什么区别

css的绝对定位怎么兼容所有的分辨率

The above is the detailed content of Detailed explanation of the special usage skills of CSS margin. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Modern Scroll Shadows Using Scroll-Driven AnimationsModern Scroll Shadows Using Scroll-Driven AnimationsMay 07, 2025 am 10:34 AM

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

Revisiting Image MapsRevisiting Image MapsMay 07, 2025 am 09:40 AM

Let’s run through a quick refresher. Image maps date all the way back to HTML 3.2, where, first, server-side maps and then client-side maps defined clickable regions over an image using map and area elements.

State of Devs: A Survey for Every DeveloperState of Devs: A Survey for Every DeveloperMay 07, 2025 am 09:30 AM

The State of Devs survey is now open to participation, and unlike previous surveys it covers everything except code: career, workplace, but also health, hobbies, and more. 

What is CSS Grid?What is CSS Grid?Apr 30, 2025 pm 03:21 PM

CSS Grid is a powerful tool for creating complex, responsive web layouts. It simplifies design, improves accessibility, and offers more control than older methods.

What is CSS flexbox?What is CSS flexbox?Apr 30, 2025 pm 03:20 PM

Article discusses CSS Flexbox, a layout method for efficient alignment and distribution of space in responsive designs. It explains Flexbox usage, compares it with CSS Grid, and details browser support.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.