CSS 在relative absolute定位布局裡通過-margin定位技巧

CSS 在relative absolute定位布局裡通過-margin定位技巧

今天看到一段有意思的代碼,是一個通過border畫圖標的代碼,而在代碼中,我發現他是通過magin-left和margin-top為負數來完成定位的。但是我發現在父級是absolute 子級relative時是並不是margin的任何一個方向都會起作用,於是我深究了一下。

結論:當我們設置relative定位的元素的位置時必須使用right/left,bottom/top,此時我們用的是哪一方向,我們的margin也就會在那個方向起作用。

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title></title>

<style>

.add{

display: inline-block;

width: 76px;height: 76px;

border: dashed 2px;

text-indent: -12em;

transform: color .25s;

position: relative;

}

.add:hover{

color: #FF0000;

}

.add::before, .add::after {

content: "";

position: absolute;

top: 100%;

left: 100%;

}

.add::after{

width: 20px;

border-top:4px solid;

margin: -40px 0 0 -48px;

}

.add::before{

height: 20px;

border-left:4px solid;

margin: -48px 0 0 -40px;

}

</style>

</head>

<body>

<a href class="add" title="繼續上傳">添加圖片</a>

</body>

</html>

這是那個圖標的源代碼。

首先這段代碼中,內部relative定位的兩個元素都未對位置進行設置,也就是left:0;top:0;這時下面也恰好是margin-left 和 margin-top起了作用。

用簡單的代碼分析

<div class="father">

<div class="son"></div>

</div>

.father{

width: 300px;height: 200px;

background-color:#CCCCCC ;

position: relative;

margin: 100px auto;

}

.son{

width: 50px;height: 50px;

border: 2px solid red;

position: absolute;

left:0px;

top:0px;

margin-left: -100px;

margin-top: -50px;

}

這時可見到子代元素在左上方偏移,也是margin-left 和 margin-top 起了作用,但是如果設置的時margin-right或是margin-bottom對子代元素就完全不起作用

margin-right: 100px;

margin-bottom: 50px;

或是

margin-right: -100px;

margin-bottom: -50px;

然後我們設置right:0;bottom:0;

在這種情況下我們設置

margin-right: -100px;

margin-bottom: -50px;

此時在right和bottom方向上的margin起了作用

而在left跟top方向上就不起作用

margin-left: 50px;

margin-top: -50px;

這時我們可能回想,這是因為位置上的權重。而實際僅僅是跟我們設置的元素有關。下面我們同時通過left、top和bottom、right將子元素設置到父元素中間。

第一組: left: 125px;

top: 75px;

第二組: right: 125px;

bottom: 75px;

當我們使用第一組數據時

我們設置

margin-left: 50px;

margin-top: 50px;

就完全不起作用,而使用

margin-right: 50px;

margin-bottom: 50px;

就會起作用

當我們使用第二組數據時

我們設置

margin-left: 50px;

margin-top: 50px;

就會起作用,而使用

margin-right: 50px;

margin-bottom: 50px;

就完全不會起作用

此文章僅僅是小白在學習時發現的問題,希望得到指導。


推薦閱讀:

Medium上有那些值得關注的前端領域的作者?
DOM【介紹、HTML中的DOM、XML中的DOM】
如何從任意HTML頁面里提取正文?(Python3)
詳解DOM元素寬高和相對位置的一些方法
有哪些網站的前端代碼風格非常好,值得學習?

TAG:HTML | 前端開發 | DivCSS |