search
HomeWeb Front-endCSS TutorialPractical tips for CSS layout: negative margin values

Practical tips for CSS layout: negative margin values

Negative margins, that is, setting the value of the margin attribute to a negative value, is a very useful technique in CSS layout. Scenarios with positive values ​​are very common, and everyone is familiar with its performance

  • When margin-top and margin-left are negative values, the element will be moved up and left, and at the same time The position in the document flow also changes accordingly, which is different from the position:relative element that still occupies its original position after setting top and left.

  • When margin-bottom and margin-right are set When it is a negative value, the element itself has no position change, and subsequent elements will move down and to the right

Look at a few application scenarios

Absolutely positioned elements

When an element is set to absolutely positioned, its top, right, bottom, and left values ​​refer to the distance from the nearest non-static element. The classic vertical centering This method is achieved by using the negative margins of absolutely positioned elements.

<style>
.wrap4{
position:relative;
margin:10px;
width:200px;
height:200px;
border:dashed 1px orange;
}
.wrap4 .content{
position:absolute;
width:100px;
height:100px;
top:50%;
left:50%;
margin-top:-50px;
margin-left:-50px;
background:orange;
}
</style>
<div class="wrap4">
<div class="content"></div>
</div>

Set the element to absolute positioning, and then set the top and left to 50%. At this time, the top and left sides of the element will reach the top and left of the parent element. At 50%, set negative margins to the element's own height and length, moving the center of the element to the center of the parent element to achieve center alignment

Practical tips for CSS layout: negative margin values

float element

The impact of negative margins on float elements is also as mentioned above, but it has its own particularities. Let’s look at an example to make it clear

Floating element negative margin

<style>
.float{
overflow:hidden;
width:280px;
border:dashed 1px orange;
}
.float .item{
width:100px;
height:100px;
float:left;
}
.float .item:nth-child(1){
background:red;
}
.float .item:nth-child(2){
background:grey;
}
.float .item:nth-child(3){
background:blue;
}
</style>
<div class="float">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>

In a div with a width of 280px, there are three float:left sub-elements on the right, with a width of 100px. Since they cannot fit in one row, the last one has been moved to Next line

Practical tips for CSS layout: negative margin values

We slightly modify the code

<style>
.float{
overflow:hidden;
width:280px;
border:dashed 1px orange;
}
.float .item{
width:100px;
height:100px;
float:left;
}
.float .item:nth-child(1){
background:red;
}
.float .item:nth-child(2){
background:grey;
}
.float .item:nth-child(3){
background:blue;
margin-left:-20px;
}
</style>
<div class="float">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>

Add a negative margin of -20px to the third element

Practical tips for CSS layout: negative margin values

At this time, I found that the third element moved up and covered the second element by 20px. The classic multi-column layout uses this principle

Multiple columns Layout

<style>
.body{
width:500px;
margin:10px;
border:dashed 1px orange;
overflow:hidden;
}
.wrap3{
float:left;
width:100%;
}
.wrap3 .content{
height:200px;
margin-right:100px;
background:rgba(255,0,0,0.5);
}
.body .right{
width:100px;
height:200px;
float:left;
margin-left:-100px;
background:rgba(0,255,0,0.5)
}
</style>
<div class="body">
<div class="wrap3">
<div class="content">
Content Content Content Content Content Content Content 
Content Content Content Content Content Content Content Content
</div>
</div>
<div class="right">Right</div>
</div>

The code is very simple

  • Add a parent element to the content element, set left floating, width 100%

  • The content element sets the right margin, the value is equal to the width of right

  • right floats left, and then sets the negative margin of its width

Originally, right should be displayed on the second line, but the left floating of its width brought it to the rightmost side of the first line, covering part of the wrap, but the content has a right margin of right width, and the covered area has no content, so Implemented two-column layout

Practical tips for CSS layout: negative margin values

Ordinary elements

Negative margins have a great impact on different block elements It’s interesting. Let’s take a look at a few examples.

Multi-column list

<style>
li{
line-height:2em;
}
.col2{
margin-left:150px;
}
.col3{
margin-left:300px;
}
li.top{
margin-top:-9em;
}
</style>
<ul>
<li class="col1">aaa</li>
<li class="col1">bbb</li>
<li class="col1">ccc</li>
<li class="col2 top">ddd</li>
<li class="col2">eee</li>
<li class="col2">fff</li>
<li class="col3 top">ggg</li>
<li class="col3">hhh</li>
<li class="col3">iii</li>
</ul>

The common approach is definitely to implement it through floating. It shouldn’t be difficult with the knowledge just introduced. It’s okay to understand why this is the case. It seems that there is nothing unusual about ordinary elements

Amplified elements

What? Negative margins can also make elements larger! ! !

<style>
.wrap{
width:300px;
border:dashed 5px orange;
}
.wrap .inner{
height:50px;
margin:0 -50px;
background:blue;
opacity:0.5;
}
</style>
<div class="wrap0">
  <div class="inner0">
  inner inner inner inner inner inner inner inner inner inner inner inner 
  </div>
</div>

This example looks ordinary, but the effect is amazing. The inner div becomes larger after setting horizontal negative margins

Practical tips for CSS layout: negative margin values

PS. The prerequisite for the effect to be achieved is that the width of the element cannot be set to a value other than auto

A list of floating child elements with right margin

Practical tips for CSS layout: negative margin values

What was your first thought when you saw this effect? Could it be that margin-right is set for the child elements, and nth-child(3n) is set to 0 during traversal? Let’s see how we can handle it using the above knowledge.

<style>
.wrap2{
width:320px;
border:dashed 1px orange;
}
.wrap2 .inner{
  overflow:hidden;
  margin-right:-10px;
}
.wrap2 .item{
float:left;
width:100px;
height:100px;
margin:10px 10px 10px 0;
background:blue;
}
</style>
<div class="wrap2">
<div class="inner">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
  </div>
</div>

We did not set nth-child( 3n) has 0 margins, but uses negative margins to make the parent element "larger".

Isn’t negative margin very interesting? Teenagers who don’t know much about it should learn it!

For more programming-related knowledge, please visit: Programming Learning! !

The above is the detailed content of Practical tips for CSS layout: negative margin values. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
@keyframes vs CSS Transitions: What is the difference?@keyframes vs CSS Transitions: What is the difference?May 14, 2025 am 12:01 AM

@keyframesandCSSTransitionsdifferincomplexity:@keyframesallowsfordetailedanimationsequences,whileCSSTransitionshandlesimplestatechanges.UseCSSTransitionsforhovereffectslikebuttoncolorchanges,and@keyframesforintricateanimationslikerotatingspinners.

Using Pages CMS for Static Site Content ManagementUsing Pages CMS for Static Site Content ManagementMay 13, 2025 am 09:24 AM

I know, I know: there are a ton of content management system options available, and while I've tested several, none have really been the one, y'know? Weird pricing models, difficult customization, some even end up becoming a whole &

The Ultimate Guide to Linking CSS Files in HTMLThe Ultimate Guide to Linking CSS Files in HTMLMay 13, 2025 am 12:02 AM

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

CSS Flexbox vs Grid: a comprehensive reviewCSS Flexbox vs Grid: a comprehensive reviewMay 12, 2025 am 12:01 AM

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

How to Include CSS Files: Methods and Best PracticesHow to Include CSS Files: Methods and Best PracticesMay 11, 2025 am 12:02 AM

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

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

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 Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools