css margin负值

130 阅读2分钟

栗子

<!DOCTYPE html>
<html>
<head> 
    <style>
        .outer {
            border: 1px solid black;
        }
        .inner {
            width: 200px;
            height: 200px;
        }
        .box1 {
            background-color: coral;
            margin-top: -80px;
        }
        .box2 {
            background-color: lightblue;
        }
    </style>
</head>
<body>
    <div class="outer">
        <div class="inner box1"></div>
        <div class="inner box2"></div>
    </div>
</body>
</html>

image.png

1. margin-top: -xx

.box1 {
    background-color: coral;
    margin-top: -80px;
}

元素整体自身向上移动,下方元素跟随上移。

image.png

2. margin-bottom: -xx

.box1 {
    background-color: coral;
    margin-bottom: -80px;
}

元素不移动,只是改变自身的高度

image.png

3. margin-left: -xx

.box1 {
    background-color: coral;
    margin-left: -80px;
}

image.png

  • 元素会左移,右边元素跟随左移

4. margin-right: -xx

无变化,元素不移动,元素宽度也不变。

image.png

5.float + margin 特殊应用

适用于圣杯布局与双飞翼布局

5.1 float:left + float:left + margin负数 上移上一行

  • 由于浮动会紧贴着上一个浮动元素或父级别容器。
  • 当上一行元素开始大于自身宽度就会发生上移行。把元素移动到上一行。
.outer {
    border: 1px solid black; 
    overflow: hidden;
}
.inner {
    width: 200px;
    height: 200px;
}
.box1 {
    background-color: coral;
    float: left;
    width: 100%;
}
.box2 {
    background-color: lightblue;
    float: left;
}

image.png

5.1.1. 移动到上一行末端

image.png

方法1

.box2 {
    background-color: lightblue;
    float: left;
    margin-left: -200px;
}

当设置 margin-left: -200px; 刚好等于自身子元素宽度,则上移到上一行。

方法2

.box1 {
    background-color: coral;
    float: left;
    width: 100%;
    margin-right: -200px; /* box1 宽度减200px,box2因为float紧跟在后 */
}

box1 通过margin-right:-200px ,宽度减200px,box2因为float紧跟在后.

5.1.2. 移动到上一行左端

.box2 {
    background-color: lightblue;
    float: left;
    margin-left: -100%;
}

image.png

当设置 margin-left: -100%; 刚好等于上一行的总长度,则上移到上一行的最左端。

5.3 float:left + float:right margin负数上移上一行

已知:

.outer {
    border: 1px solid black; 
    overflow: hidden;
}
.inner {
    width: 200px;
    height: 200px;

}
.box1 {
    background-color: coral;  
    width: 100%;
    float: left;
}
.box2 {
    background-color: lightblue;  
    float: right;
}

image.png

1.移动到上一行末端

.box2 {
    background-color: lightblue;  
    float: right;
    margin-left: -100%; 
}

当设置 margin-left: -100%; 刚好上移到上一行的末尾。 image.png

2.移动到上一行左端

由于是右对齐,则需要借助right:xx 来设置。

.outer {
    border: 1px solid black; 
    overflow: hidden;
}
.inner {
    width: 200px;
    height: 200px;

}
.box1 {
    background-color: coral;  
    width: 100%;
    float: left;
}
.box2 {
    background-color: lightblue;  
    float: right;
    margin-left: -100%;
    position: relative; /*设置相对定位 才能开启left right等设置*/ 
    right: calc(100% - 200px);/*通过总长度减去 - 自身宽度 做右偏移 */
}

image.png