简体   繁体   English

CSS百分比无法正常工作

[英]CSS Percent Not Working Correct

The webpage has a parent container with 4 child containers. 该网页有一个带有4个子容器的父容器。 Sketch: 草图:

---------------
|  Child 0    |
|-------------|
|  Child 1    |
|-------------|
|  Child 2    |
|-------------|
|  Child 3    |
---------------

CSS CSS

.Parent {
    float: right;
    height: 300px;
    width: 25%;
}
.Child {
   height: 22%;
   margin-bottom: 4%; 
}

Javascript 使用Javascript

var pParent = document.getElementById("id");
pParent.className = "Parent";
for(var k = 0; k < 4; ++k) {
    var pChild = document.createElement("div");
    pChild.className = "Child";
    pParent.appendChild(pChild);
}        

The 4 child containers should fit perfectly into the parent container: 4个子容器应完全适合父容器:

4 * 22% + 3 * 4% = 100% or 4 * 22%+ 3 * 4%= 100%或

4 * 22% of 300px + 3 * 4% of 300px = 300px where 300像素的4 * 22%+ 300像素的3 * 4%= 300像素

4 is the number child containers and 4是子容器的数量,

3 is the number of spaces/margins between the child containers 3是子容器之间的空格/边距数

But they do not. 但是他们没有。 Depending on the browser size, the child containers may be much to small or even move outside of the parent container. 根据浏览器的大小,子容器可能很大,甚至很小,甚至可能移出父容器。 Can anyone help me what I am missing? 谁能帮我我所缺少的吗?

Thanks! 谢谢!

Your assumption of "4 * 22% + 3 * 4% = 100%" is not correct, it would be, "4 * 22% + 4* 4% = 104%" because a margin-bottom would be applied for each of the children. 您对“ 4 * 22%+ 3 * 4%= 100%”的假设是不正确的,而是“ 4 * 22%+ 4 * 4%= 104%”,因为对于每个这些孩子。 Try this, 尝试这个,

.Parent {
    float: right;
    height: 300px;
    width: 25%;
}
.Child {
   height: 22%;
   margin-bottom: 3%; 
}

Alternatively, if you want to have margin-bottom: 4% for first three children and none for the last one do this, 或者,如果您想让页margin-bottom: 4%前三个孩子为margin-bottom: 4% ,最后一个孩子为不,

.Parent {
        float: right;
        height: 300px;
        width: 25%;
    }
    .Child {
       height: 22%;
       margin-bottom: 4%; 
    }
.Parent:last-child{
        height: 22%;
       margin-bottom: none;
}

Your problem is a combination of several mistakes: 您的问题是几个错误的组合:

  1. Simple math - margin-bottom appears 4 times, not 3. (22+4)*4 = 104. 简单的数学-底边出现4次,而不是3次。(22 + 4)* 4 = 104。
  2. margin-bottom: xx% - you expect that to be a percentage of the parent height, but actually the parent width is the source for calculating the margin, even for margin-bottom . margin-bottom: xx% -您期望这是父级高度的百分比,但实际上,即使对于margin-bottom ,父级宽度也是计算页边距的来源。

margin-bottom是根据宽度计算的,您可能需要查看flexbox。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM