首页 > margin-right:-100% 这个百分比是以什么为基准算出来的?

margin-right:-100% 这个百分比是以什么为基准算出来的?

 <!DOCTYPE HTML>
 <html lang="ru-RU">
 <head>
   <title></title>
   <meta charset="UTF-8">
<style type="text/css">
*{margin:0;padding:0;}
li div{display:inline-block;
border:1px solid green;
width:200px;
height:25px;
}
div{
text-align:center;
}
li {

height:30px;
border:1px solid gold;
width:500px;
margin-top:1px;
}
.last{
width:100px;margin-right:-100%;background:gold;
}
</style>
 </head>
 <body>


<div > 
<li> <div class='last' style='margin-right:-125%'>100px</div><b>&nbsp;</b> </li>
 
 <li> <DIV  style='width:200px'>xx</DIV><div class='last' >100px</div><b>&nbsp;</b> </li>
 <li> <div style="width:100px">xx</div><div style="width:200px">oo</div> <div class='last'>100px</div> </li>
  
</div>
   


 </body>
 </html>

margin 的值是 百分比的时候 通常是按照父亲一级的宽度计算,如果上一级没有宽度,那么算的是更上一层。

注意是宽度,即,margin-top:10% 是按照父亲宽度的10%计算,而不父亲是高度。

以下是测试代码

<!DOCTYPE html>
<html>
<head>
  <style>
  .margin-box {
    color: #fff;
    background: green;
    width: 100px;
    height: 100px;
  }
  .container{
    width: 200px;
    height: 200px;
    background: blue;
    padding: 10px;
    margin: 10px;
  }
  </style>
</head>
<body>
  <div class="margin-box" style="margin-top: 50%;">
    margin-top: 50%; parent is body
  </div>
  <div class="container">
    <div class="margin-box" style="margin-top: 50%;">
      margin-top: 50%; parent is a container
    </div>
  </div>
  
  <div class="container" style="width:400px">
    <div class="margin-box" style="margin-top: 50%;">
      margin-top: 50%; parent is a wider container
    </div>
  </div>
  
  <div class="container" style="display:inline;">
    <div class="margin-box" style="margin-top: 50%;">
      margin-top: 50%; parent is a inline.
    </div>
  </div>
</body>
</html>

另外,margin 还会受到排在它前面的dom的margin影响。

例如

<div id="a" style="margin:100px">test</div>
<div id="b" style="margin:100px">test</div>

这时,A 和 B之间的间距 是100px 而不是200px 于是前面的那个规则基础上还要加上这一层变化。据知情人士说这个现象叫做 “margin collapse”。可以使用 padding (不等于0), 或者 :before :after 塞空内容来避免。

总的来说,margin 不是一定按照父亲来计算,这些都会发生在现代浏览器上。我们用的大多数CSS框架都替你干了。


百分比应该是根据父元素决定,至少在日常布局可以这样运用。楼上说的margin会被推上父元素的现象,是margin collapse,中文不打好翻译,可以设置父元素的padding属性防止


<!DOCTYPE HTML>
<html lang="ru-RU">
<head>
  <title></title>
  <meta charset="UTF-8">
<style type="text/css">
.list{
width:300px;
height:300px;
background:gold;
border:1px solid crimson;
float:left;
}

#left{
background:green;
height:200px;

margin-right:-100%;
}

</style>
</head>
<body>
<div class='list'> 11111 </div><div class='list'  id="left"   > 2222</div>
<div class='list' style='background:navy' > 33333</div>
<div > 4444 o</div>


  
</body>
</html>

父元素的宽度


以它的父元素,也就是li为参照的


以父元素的宽度来作为参考的。


according to the width of the containing box

【热门文章】
【热门文章】