使flexbox与其父级的宽度匹配

时间:2018-04-10 10:24:37

标签: html css css3 flexbox

我正试图在没有运气的情况下实现这个特定的设计:

enter image description here

黑框应控制#container的宽度(黄色边框)。 然后,#flex的容器(包含红色div的flexbox)将调整大小以匹配其父级的维度。

我提出的代码如下:

#container {
  border: 4px solid #f1c40f;
  font-family: Tahoma;
  color: white;
}
#title {
  padding: .5em .75em;
  background: #2c3e50;
  display: inline-flex;
}
#flex {
  display: flex;
}
#icon {
  background: #c0392b;
  padding: .5em .75em;
}
#content {
  background: #e74c3c;
  padding: .5em .75em;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div id="container">
    <div id="title">I should set the width of the container!</div>
    <div id="flex">
      <div id="icon">
        icon
      </div>
      <div id="content">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eu eleifend sem. Cras elit odio, faucibus vel tortor nec, lacinia accumsan enim. Aenean eget vulputate ante. Integer quis condimentum magna. Suspendisse potenti. Suspendisse imperdiet eget magna vitae rhoncus. Vestibulum fringilla accumsan accumsan. Duis facilisis lobortis scelerisque. Pellentesque at erat porta, scelerisque nisl in, volutpat sem. Nulla facilisi. Phasellus enim augue, tempus et facilisis id, lobortis eu urna. Aenean volutpat risus dolor, ac volutpat enim euismod ac. Ut id rutrum felis.
      </div>
    </div>
  </div>
</body>
</html>

正如您在代码段中看到的那样,#flex使#container比应有的更宽。我尝试#container {display: inline-flex;},我尝试将flex-basis: 0%;flex-shrink: 1;应用于flexbox的子项,但似乎没有任何改变此行为。

如何使#flex#title的宽度相匹配?

谢谢!

1 个答案:

答案 0 :(得分:-1)

也许你应该修改你的容器:

#container {

  display:flex;
  flex-direction: column;

  border: 4px solid #f1c40f;
  font-family: Tahoma;
  color: white;
}

然后你可以给容器一个width

http://jsbin.com/vufolodowe/edit?html,css,output