国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end CSS Tutorial Detailed explanation of margin attribute in css

Detailed explanation of margin attribute in css

Mar 22, 2018 pm 04:55 PM
css margin

This time I will bring you a detailed explanation of the margin attribute in css. What are the precautions for using margin in css? The following is a practical case, let’s take a look.

Before I always thought that the margin attribute was a very simple attribute, but recently I encountered some problems while working on a project, and I discovered that there are still some "pitfalls" in the margin attribute. Below I will introduce the basic knowledge of margin and Those "pits". This blog post is mainly divided into the following parts:

  • margin--Basic knowledge

  • margin--In elements at the same level (non-parent-child Relationships)

  • margin--Apply between parent elements and child elements (emphasis)

  • margin--The unit of margin value Several situations when it is %

##Part 1: margin--basic knowledge

To introduce the basic knowledge of margin, we cannot avoid it Talking about the

css box model (Box Model), generally speaking, the css box model is used for design and layout. It is essentially a box, including: margin, border, padding and the middle content. The picture below is the box model (here we only talk about the standard box model of the W3C specification, not the non-standard box model used in IE5 and IE6 in weird mode):

The margin we are going to introduce is on the outermost layer. Because margin (margin) must be transparent, it can be used to leave a certain gap between different boxes to achieve beautiful layout and other effects. From the box model above, we can see that margins exist all around. We can use margin-top,

margin-right, margin-bottom, and margin-left to set these respectively. Margin values ??in four directions. (Note: Since this part of the knowledge is relatively basic, I will not introduce more in this part)

Part 2: margin--between elements of the same level (non-parent-child relationship) Application

This part mainly introduces the problem of merging horizontal and vertical margins.

(1) Horizontal margins merge

When two horizontal boxes meet, the final distance between them is the right margin of the left box Sum the margins of the box on the right.

Example 1:

The code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
????<meta charset="UTF-8">
????<title>水平方向的兩個盒子</title>
????<style>
????????*{
????????????margin:0;
????????????padding:0;
????????????border:0;
????????}
????????body{
????????????font-size:?0;
????????}
????????.left{
????????????width:?100px;
????????????height:?100px;
????????????background:?red;
????????????display:?inline-block;
????????????margin-right:?50px;
????????????font-size:?20px;
????????}
????????.right{
????????????width:?100px;
????????????height:?100px;
????????????background:?yellow;
????????????display:?inline-block;
????????????margin-left:?50px;
????????????font-size:?20px;
????????}
????</style>
</head>
<body>
????<p class="left">寬為100px,右邊距為50px</p>
????<p class="right">寬為100px,左邊距為50px</p>
</body>
</html>
The effect is as follows:

At this time, the difference between the two The distance is exactly 100px.

Additional explanation: As you can see, in order to make the two p (block elements) out of the normal document flow, I used display:inline-block; Attribute, in addition, I also set the font-size of the body to 0, which can solve the problem of inline-block itself, otherwise the two p examples will be larger than 100px. Of course, using float can also make two p appear on the same line.

(2) Vertical margin merging

When two vertical boxes meet, their vertical distance is equal to the lower outer edge of the upper box The larger of the margin and the top margin of the box below.

Example 2:

<!DOCTYPE html>
<html lang="en">
<head>
????<meta charset="UTF-8">
????<title>水平方向的兩個盒子</title>
????<style>
????????*{
????????????margin:0;
????????????padding:0;
????????????border:0;
????????}
????????.top{
????????????width:?100px;
????????????height:?100px;
????????????margin-bottom:?100px;
????????????background:?red;
????????}
????????.bottom{
????????????width:?100px;
????????????height:?100px;
????????????margin-top:?50px;
????????????background:?green;
????????}
????</style>
</head>
<body>
????<p class="top">高為100px,下邊距為100px</p>
????<p class="bottom">高為100px,上邊距為50px</p>
</body>
</html>
The effect is as follows:

At this time, we can observe it with the naked eye. Examples of both vertical directions It is about 100px (actually 100px) instead of 100+50=150px; this is precisely because when two vertical boxes meet, the vertical distance is equal to the lower margin of the upper box and the upper margin of the lower box The larger one.

Another interesting example is: Suppose there is an element with margin-top and margin-bottom set at the same time, but the content is empty, then the two margin values ????will also be superimposed, and the value will be the largest of the two. , which is similar to the superposition of margin values ????of two boxes in the vertical direction. The code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
????<meta charset="UTF-8">
????<title>水平方向的兩個盒子</title>
????<style>
????????*{
????????????margin:0;
????????????padding:0;
????????}
?
????????.top{
????????????width:?500px;
????????????height:?100px;
????????????background:?red;
????????}
????????.middle{
????????????margin-top:?100px;
????????????margin-bottom:50px;
????????}
????????.footer{
????????????width:?500px;
????????????height:?100px;
????????????background:?green;
????????}
?
????</style>
</head>
<body>
????<p class="top">上面的p,高100px</p>
????<p class="middle"></p>
????<p class="footer">下面的p,高100px</p>
</body>
</html>
The final effect is as follows:

我們發(fā)現(xiàn)這時在上面的p和在下面的p之間的舉例并不是100+50=150px,而是兩者中的最大者,即100px。

那么W3C為什么會設定這樣的標準而不設定和水平方向一樣的標準呢?即margin值的疊加,實際上這也是有一定的道理的。比如我們需要設計一個由若干個段落構成的一個頁面。我們需要設置margin-top和margin-bottom使得第一段和頁面的最上方有一段距離,使得最后一段和最下方有一段距離。下面是不疊加和疊加的效果圖:

我們可以看到左邊的頁面沒有重疊,那么兩個段落之間的舉例就是最上方的兩倍間距了,而右邊的頁面發(fā)生了重疊,則所有的間距都是相等的?;蛟S這就是這樣設定標準的目的吧,誰知道呢?

第三部分:margin--在父元素和子元素之間應用(重點)

第二部分介紹了同級元素之間使用margin,而這一部分將要介紹最有意思的父元素和子元素之間margin的應用。這一部分,我們同樣從兩個方面來討論。一方面是子元素設置水平方向上的margin值,另一方面是子元素設置豎直方向的margin值。

(1)在子元素中設置水平方向的margin值

我們可以設置margin-left來控制子元素的左邊框和父元素的左邊框之間的舉例。

例3:

<!DOCTYPE html>
<html lang="en">
<head>
????<meta charset="UTF-8">
????<title>margin</title>
????<style>
????????*{padding:0;?margin:0;?border:0;}
????????.father{
????????????width:?500px;
????????????height:?500px;
????????????background:?red;
????????}
????????.son{
????????????width:?100px;
????????????height:?100px;
????????????background:?green;
????????????margin-left:?100px;
????????}
????</style>
</head>
<body>
????<p class="father">
????????<p class="son">寬度為100px,margin-left為100px。</p>
????</p>
</body>
</html>

我將子元素的margin-left設置為了100px;效果如下:

即子元素的左邊框和父元素的左邊框之間的距離為100px。與在同級元素之間設置margin不同,因為同級元素之間的margin不會考慮到padding,但是在父元素和子元素就不同了,那么如果父元素中如果有padding,效果會是什么樣的呢?請看下面一個例子:

例4:

下面我們在上面例子的基礎上給父元素添加padding值。

<!DOCTYPE html>
<html lang="en">
<head>
????<meta charset="UTF-8">
????<title>margin</title>
????<style>
????????*{padding:0;?margin:0;?border:0;}
????????.father{
????????????width:?500px;
????????????height:?500px;
????????????padding:100px;
????????????background:?red;
????????}
????????.son{
????????????width:?100px;
????????????height:?100px;
????????????background:?green;
????????????margin-left:?100px;
????????}
????</style>
</head>
<body>
????<p class="father">
????????<p class="son">寬度為100px,margin-left為100px。</p>
????</p>
</body>
</html>

上面的代碼給父元素添加了100px的padding值,效果如下:

我們可以看到子元素舉例上方的距離為100px,因為子元素一定是在父元素的content的部分的,這點毫無疑問。

但是經(jīng)過測量可以發(fā)現(xiàn)子元素的左邊框距離父元素的左邊框之間的距離為200px,因為其中還有100px的左padding值,前面的例子因為我沒有設置padding值,所以沒有觀察出來,因此這就說明了在子元素中設置margin-left,其值實際上是子元素的左邊框距離父元素左padding內(nèi)側的距離。

例5:margin-right的使用和margin-left的使用是相似的,我在這里只舉一個例子。

這個例子在子元素中設置了margin-right值,如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
????<meta charset="UTF-8">
????<title>margin</title>
????<style>
????????*{padding:0;?margin:0;?border:0;}
????????.father{
????????????width:?500px;
????????????height:?500px;
????????????padding:100px;
????????????background:?red;
????????}
????????.son{
????????????float:?right;
????????????width:?100px;
????????????height:?100px;
????????????background:?green;
????????????margin-right:?100px;
????????}
????</style>
</head>
<body>
????<p class="father">
????????<p class="son">寬度為100px,margin-right為100px。</p>
????</p>
</body>
</html>

這個例子與例4的區(qū)別僅在與子元素的位置不同。效果如下:

通過這個例子可以說明margin-right的值是子元素的右邊框和父元素的右padding內(nèi)側的距離。只是前面的幾個例子我沒有使用padding,所以無法觀察出來。

(2)在子元素中設置豎直方向的margin值

按照前面的經(jīng)驗,理論上來說,我們同樣可以通過設置margin-top的值使得子元素的上邊框和父元素的上padding的內(nèi)側留有一定的距離。那么我們就試試吧!

例6:

<!DOCTYPE html>
<html lang="en">
<head>
????<meta charset="UTF-8">
????<title>margin</title>
????<style>
????????*{padding:0;?margin:0;?border:0;}
????????.father{
????????????width:?500px;
????????????height:?500px;
????????????background:?red;
????????}
????????.son{
????????????width:?100px;
????????????height:?100px;
????????????background:?green;
????????????margin-top:?100px;
????????}
????</style>
</head>
<body>
????<p class="father">
????????<p class="son">高度為100px,margin-top為100px。</p>
????</p>
</body>
</html>

這個例子我設置了margin-top為100px,效果如下:

這并不是我們想要的效果啊,我們希望子元素的上部距離父元素的上部為100px,可是我們看到的卻是父元素的上部距離瀏覽器頁面的上部有100px的距離,這是為什么呢?哪里出現(xiàn)問題了呢?

實際上這是因為當父元素沒有設置padding值以及border值時,出現(xiàn)了一個bug--父元素的上方與子元素的上方完全重合在了一起,無法分開。所以才會導致上述這種父元素和子元素同時向下的情況。

對于這種問題解決方法有下面幾種:

  • 方法一:給父元素添加padding-top值

  • 方法二:給父元素添加border值

  • 方法三:給父元素添加屬性overflow:hidden;

  • 方法四:給父元素或者子元素聲明浮動float

  • 方法五:使父元素或子元素聲明為絕對定位:position:absolute;

  • 方法六:給父元素添加屬性 overflow:auto; positon:relative;(注:此方法為后續(xù)添加,感謝博友@小精靈Pawn提供此方法)

方法一:基于例6,在父元素的css代碼中添加padding-top:1px;效果如下:

?方法的唯一缺點就是增加了1px的誤差。

方法二:基于例6,在父元素的css代碼中添加border-top:1px solid transparent;效果如下:

同樣達到了效果, 缺點同方法一。

方法三:基于例6,在父元素的css代碼中添加overflow:hidden;效果如下:

同樣達到了效果,并且沒有任何誤差的存在??胺Qperfect!!!!

方法四:給父元素或者子元素聲明float;基于例6,在子元素css代碼添加float:left;或者在父元素css代碼添加float:left;均達到效果,這里不再展示相同的圖片。

優(yōu)點:沒有像素的誤差。?? 缺點:float有時是不必要的。

方法五:給父元素或者子元素添加position:absolute;屬性。 同樣達到效果。

優(yōu)點:同方法四。? 且只要我們不使用top和left也不會有任何影響,所以這也是一種不錯的方法。

方法六:給父元素添加overflow:auto;和position:relative;同樣達到效果。

第四部分:margin值的單位為%時的幾種情況

之前我舉例子時使用margin,它的值都是以px為單位的,這個理解起來沒有問題。但是如果margin值是以%為單位呢?實際上這時候百分比(%)是相對于該元素的父元素(容器),對于同級元素和父子元素都是如此。(再次感謝 博友@小精靈Pawn 提供的建議?。』诖私ㄗh補充這部分內(nèi)容) 但是在同級元素中使用豎直方向的margin時會出現(xiàn)意想不到的結果,下面舉例說明。

(1)同級元素在水平方向使用值為%的margin

例7:

<head>
????<meta charset="UTF-8">
????<title>margin</title>
????<style>
????????*{
????????????margin:0;
????????????padding:0;
????????}
????????.first{
????????????float:?left;
????????????width:?200px;
????????????height:?200px;
????????????background:?green;
????????}
????????.second{
????????????float:?left;
????????????width:?200px;
????????????height:?200px;
????????????background:?red;
????????????margin-left:?20%;
????????}
????</style>
</head>
<body>
????<p class="first">寬為200,無margin</p>
????<p class="second">寬為200,margin-left為20%;</p>
</body>
</html>

這個例子中,設置兩個元素向左浮動,以便于觀察兩者水平方向的margin。其中左邊p無margin,右邊p的margin-left為20%,效果如下:

從效果圖可以看出兩個p之間的間距始終為父元素(這里右邊p的父元素即為body,其寬度為瀏覽器寬度)的20%。

(2)同級元素在豎直方向使用值為%的margin

根據(jù)例7的啟發(fā),我們可以猜想,如果在豎直方向上使用margin,且值的單位為%,那么最終兩者之間的距離將是父元素(上例中為body)的百分數(shù)。那么究竟是不是這樣呢?看下面的例子。

例8

<head>
????<meta charset="UTF-8">
????<title>margin</title>
????<style>
????????*{
????????????margin:0;
????????????padding:0;
????????}
????????.first{
????????????width:?200px;
????????????height:?200px;
????????????background:?green;
????????}
????????.second{
????????????width:?200px;
????????????height:?200px;
????????????background:?red;
????????????margin-top:?10%;
????????}
????</style>
</head>
<body>
????<p class="first">高為200,無margin</p>
????<p class="second">高為200,margin-top為20%;</p>
</body>
</html>

這里設置上面的p無margin,下面的p的margin-top為10。效果如下:

我們發(fā)現(xiàn),當我在縮小瀏覽器的高度時,豎直方向上的間距并沒有縮?。。?! 而當我縮小瀏覽器的寬度時,豎直方向上的距離縮小了?。。?/p>

這就說明:統(tǒng)計元素之間在豎直方向上使用margin,當值的單位為%時,它是相對于父元素的寬度。

那么這里為什么不是如我們所希望的那樣相對于瀏覽器的高度呢?知乎上有大神是這樣解釋的:

(3)父子元素使用值為%的margin

對于父子元素,如果在子元素中使用單位為%margin,那么這個margin值是相對于父元素的寬度和高度(注意:這時的確是相對于父元素的高度?。┑摹?/p>

例9?

代碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
????<meta charset="UTF-8">
????<title>Document</title>
????<style>
????????*{
????????????margin:0;
????????????padding:0;
????????}
????????.father{
????????????width:?500px;
????????????height:?300px;
????????????background:?red;
????????????overflow:?hidden;
????????}
????????.son{
????????????width:?100px;
????????????height:?100px;
????????????background:?green;
????????????margin-top:?20%;
????????????margin-left:?20%;
????????}
????</style>
</head>
<body>
????<p class="father">
????????<p class="son"></p>
????</p>
</body>
</html>

在這個例子中,我設置了margin-left的值為20%,margin-top的值為20%,父元素的width為500px,父元素的height為300px。下面看看效果吧。

從上圖可以看出子元素的margin-top值最終同樣是相對與父元素的寬度而非高度。

總結:

這篇博文只介紹了margin的其中一部分知識點,但如果大家讀后能有些許收獲是再好不過的了。由于本人總結倉促,知識不足,錯誤在所難免,希望大家如果發(fā)現(xiàn)不妥之初能提出意見,我將非常感激。

相信看了本文案例你已經(jīng)掌握了方法,更多精彩請關注php中文網(wǎng)其它相關文章!

推薦閱讀:

CSS3的box-sizing屬性圖文教程

在CSS邊界線消失如何處理

三種絕對定位元素的水平垂直居中的辦法

The above is the detailed content of Detailed explanation of margin attribute in css. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is 'render-blocking CSS'? What is 'render-blocking CSS'? Jun 24, 2025 am 12:42 AM

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

External vs. Internal CSS: What's the Best Approach? External vs. Internal CSS: What's the Best Approach? Jun 20, 2025 am 12:45 AM

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

What is Autoprefixer and how does it work? What is Autoprefixer and how does it work? Jul 02, 2025 am 01:15 AM

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

What are the key differences between inline, block, inline-block, and flex display values? What are the key differences between inline, block, inline-block, and flex display values? Jun 20, 2025 am 01:01 AM

Choosing the correct display value in CSS is crucial because it controls the behavior of elements in the layout. 1.inline: Make elements flow like text, without occupying a single line, and cannot directly set width and height, suitable for elements in text, such as; 2.block: Make elements exclusively occupy one line and occupy all width, can set width and height and inner and outer margins, suitable for structured elements, such as; 3.inline-block: has both block characteristics and inline layout, can set size but still display in the same line, suitable for horizontal layouts that require consistent spacing; 4.flex: Modern layout mode, suitable for containers, easy to achieve alignment and distribution through justify-content, align-items and other attributes, yes

How can you animate an SVG with CSS? How can you animate an SVG with CSS? Jun 30, 2025 am 02:06 AM

AnimatingSVGwithCSSispossibleusingkeyframesforbasicanimationsandtransitionsforinteractiveeffects.1.Use@keyframestodefineanimationstagesforpropertieslikescale,opacity,andcolor.2.ApplytheanimationtoSVGelementssuchas,,orviaCSSclasses.3.Forhoverorstate-b

What is the conic-gradient() function? What is the conic-gradient() function? Jul 01, 2025 am 01:16 AM

Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin

What is the scope of a CSS Custom Property? What is the scope of a CSS Custom Property? Jun 25, 2025 am 12:16 AM

The scope of CSS custom properties depends on the context of their declaration, global variables are usually defined in :root, while local variables are defined within a specific selector for componentization and isolation of styles. For example, variables defined in the .card class are only available for elements that match the class and their children. Best practices include: 1. Use: root to define global variables such as topic color; 2. Define local variables inside the component to implement encapsulation; 3. Avoid repeatedly declaring the same variable; 4. Pay attention to the coverage problems that may be caused by selector specificity. Additionally, CSS variables are case sensitive and should be defined before use to avoid errors. If the variable is undefined or the reference fails, the fallback value or default value initial will be used. Debug can be done through the browser developer

CSS tutorial focusing on mobile-first design CSS tutorial focusing on mobile-first design Jul 02, 2025 am 12:52 AM

Mobile-firstCSSdesignrequiressettingtheviewportmetatag,usingrelativeunits,stylingfromsmallscreensup,optimizingtypographyandtouchtargets.First,addtocontrolscaling.Second,use%,em,orreminsteadofpixelsforflexiblelayouts.Third,writebasestylesformobile,the

See all articles