【问题标题】:Why do divs lose their ability to output at % when inside other divs?为什么在其他 div 中时 div 会失去以 % 输出的能力?
【发布时间】:2017-03-10 22:44:36
【问题描述】:

为什么<divs> 在其他<divs> 内时会失去以%(百分比)输出宽度和高度的能力?

我在<div id="1"> 中有<div id="2"><div id="3">

<div id="1"> 的宽度和高度用 %(百分比)设置。

我将<div id="2"><div id="3"> 高度设置为% 时,为什么它们不起作用? (不过,它们使用 px(像素)。)

【问题讨论】:

    标签: html css pixel percentage elements


    【解决方案1】:

    % 是相对测量单位,因此您需要将任何父级设置为绝对单位,例如 px 例如,如果您的 div1 为空,那么 div1 的 100% width and 0% height 在这种情况下您的 div2 and div3 将不起作用。

    将您的 html、正文宽度和高度设置为 100%,您的所有 div 应该可以正常工作 试试这段代码;

    body, html{
      height: 100%;
      background: #eee;
    }
    
    .div1{
      width: 100%;
      height: 100%;
      background: #ccc;
    }
    
    .div2{
      width: 50%;
      height: 50%;
      background: #888;
      margin-left: 50%;
    }
    
    .div3{
      width: 50%;
      height: 50%;
      background: #fff;
    }
    

    SEE WORKING EXAMPLE

    【讨论】:

      【解决方案2】:

      在 div1 中使用 position:relative,它们只有内部 div 将采用相对于父级的 % 高度和 div

      .parent {
        position: relative;
        width: 300px;
        height: 100px;
        background: #eee;
      }
      #div1 {
        position: relative;
        width: 80%;
        background: #f00;
        height: 80%;
        display: inline-block;
      }
      #div2 {
        width: 30%;
        background: #0f0;
        height: 30%;
        display: inline-block;
      }
      #div3 {
        width: 30%;
        background: #00f;
        height: 30%;
        display: inline-block;
      }
      <div class='parent'>
        <div id="div1">
          <div id="div2">
          </div>
          <div id="div3">
          </div>
        </div>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-08-15
        • 2023-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多