100%真正做到了什么?(多案例研究)

Art*_*hur 1 html css width css3 percentage

我目前正在建立一个完全响应的网站,我越努力理解,我就越不了解.主要是百分比.

我知道%是基于第一个定位的父级.但是,我在JSFiddle上做了一些例子,我有不同的结果:

小提琴

在所有示例中,我们都有相同的基础:

HTML:

<div class="example">  
  <div class="container">  
    <div class="item"></div>
  </div>   
</div>
Run Code Online (Sandbox Code Playgroud)

divs的CSS属性:

  1. .example块有position: relative.它有width: 60%(他的父母:身体).
  2. .container块有position: static.它有一个宽度:80%(这个时间.example因为它是一个相对块).

我的问题:

当我想移动.item,而不是块.example大小,但每个CSS属性我使用(margin-left,left,transform等),100个%会导致不同的大小.此外,如果我改变用于定位.item(static,relative等)的尺寸是不同的再.

有人可以解释为什么100%.item是不同的margin,lefttransform

Dan*_*niP 6

只是为了澄清您的注意事项,%百分比与所有属性的计算值不同:

在您的示例中,默认位置为:

在此输入图像描述

  • 在使用位置 left

    Percentages of the width of the containing block
    
    Run Code Online (Sandbox Code Playgroud)

    在这种情况下,由于您使用的是absolute位置,因此指定的父级是最接近的非静态位置."示例"容器是相对定义的.

    在此输入图像描述

  • margin

    Percentages refer to the width of the containing block
    
    Run Code Online (Sandbox Code Playgroud)

    如果一个没有absolute位置的人正好将元素向左移动,则将containerdiv 的大小从其初始位置精确调整.

    在此输入图像描述

    当你添加absolute现在是example他的初始位置空间后的100%.

    在此输入图像描述

  • transform

    Percentages refer to the size of bounding box
    
    Run Code Online (Sandbox Code Playgroud)

    因此元素偏移量等于其宽度.

    在此输入图像描述