【问题标题】:Embedded divs in header: css issue标题中嵌入的 div:css 问题
【发布时间】:2015-07-31 20:14:32
【问题描述】:

我正在尝试在 header 中使用嵌入的 divs 创建以下结构:

  • 红色部分的高度和宽度已知并修复
  • 绿色矩形的高度已知并修复
  • 框架的整体宽度可以变化,但绝不会小于红色部分

我已尝试使用以下 html 代码:

<header id="header">
  <div id="yellowAndGreen">
      <div id="yellow"></div>
      <div id="green"></div>
  </div>
  <div id="red"></div>
</header>

以及以下 CSS:

#header {
    width: 400px;  
}
#yellowAndGreen {

}

#yellow {    
    background-color: yelow;
}

#green {    
    background-color: green;
    height: 40px;
}

#red {    
    height: 150px;
    width: 150px;
    background-color: red;
}

但它不起作用。我创建了一个JsFiddle。任何人都可以修改它来创建我正在寻找的东西吗?

【问题讨论】:

  • 如果视口低于400px 标题宽度,黄色和绿色应该高于还是低于红色?
  • 400px 是标题的随机大小,它可以大于红色部分的宽度。黄色和绿色的宽度应该适应整个矩形的宽度(即减去红色部分的宽度)。
  • 瑞秋,红色方块的左边有个缺口……

标签: html css divide


【解决方案1】:

使用float:right; 使红色框向右浮动。您需要调整 html:

<header id="header">
  <div id="alldivs">
      <div id="red"></div>
      <div id="yellow"></div>
      <div id="green"></div>
  </div>
</header>

和css:

#header {
    width: 400px;  
}
#yellow {    
    background-color: yellow;
    height:110px;
}

#green {    
    background-color: green;
    height: 40px;
}

#red {    
    height: 150px;
    width: 150px;
    background-color: red;
    float:right;
}

请注意您拼错了“yellow”,并且您需要为黄色&lt;div&gt; 设置高度。

终于here is the adjusted fiddle

希望对你有帮助

【讨论】:

    【解决方案2】:

    这使用了 flexbox,它在旧版浏览器上有一些支持下降。为简单起见,我排除了特定于供应商的属性。

    #header {
        width: 400px;  
        display: flex;
    }
    #yellowAndGreen {
        flex: 1 1 auto;
        display: flex;
        flex-direction: column;
    }
    
    #yellow {    
        background-color: yellow;
        flex-grow: 1;
    }
    
    #green {    
        background-color: green;
        height: 40px;
    }
    
    #red {    
        height: 150px;
        width: 150px;
        background-color: red;
    }
    

    【讨论】:

      【解决方案3】:

      不需要浮动或弹性框!

      稍微重新排列了您的 HTML。将#headerbackground-color 设置为redmin-width,这样它就永远不会太小。使用calc() 作为#yellow 的宽度,使其父级的红色背景始终为150px 宽。

      #header {
          width: 400px;
          background-color: red;
          width: 100%;
          min-width: 150px;
      }
      
      #yellow {
          height: 150px;
          width: calc(100% - 150px);
          background-color: yellow;
      }
      
      #green {    
          background-color: green;
          height: 40px;
      }
      <header id="header">
            <div id="yellow"></div>
            <div id="green"></div>
      </header>

      【讨论】:

      • 这不是他们真正要求的 - 红色 div 包含另外两个,他们想要 3 个独立的 div
      • 哎呀!在divs 中没有看到任何内容,所以我认为没关系。
      猜你喜欢
      • 1970-01-01
      • 2020-12-05
      • 2011-08-29
      • 2020-12-31
      • 1970-01-01
      • 2018-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多