html - 使父 div 适合其子元素

标签 html css

<分区>

我有一个问题,我没有找到任何简单的解决方案。

仅使用 HTML 和 CSS,
有没有一种很好的方法可以使父级 div 与其包含的元素的总大小“匹配”?
请注意,box 元素都具有相同的固定强制大小。但是这个大小可能会有所不同,所以我不想使用 @media 查询。

这是一个注释片段来说明我的意思:

#page{
  width: 500px;
}

.container {
  display: inline-block;
  border: 1px solid black;
  background: #ddd;
  height: auto;
}

.box {
  width: 200px;
  height: 30px;
  background: #fff;
  line-height: 30px;
  text-align: center;
  border: 1px solid gray;
  float: left;
}

#con1{
  width: 404px;
}
<div id="page">

<p>How is it possible to have the container sized to fit its children?</p>
<div class="container">
  <div class="box">x</div>
  <div class="box">x</div>
  <div class="box">x</div>
</div>

<br><br>

<p>Here is what I want, but without setting width in the CSS!</p>
<div class="container" id="con1">
  <div class="box">x</div>
  <div class="box">x</div>
  <div class="box">x</div>
</div>

</div>

做这个片段,在我看来我还有一个小问题......
为什么我的代码段中的框之间有一些空间?

提前感谢您提供任何有用的答案。

最佳答案

像这样使用媒体查询:

.container {
    border: 1px solid black;
    background: #ddd;
   display: inline-block;
}

@media screen and (max-width: 631px) {
   .container {
       width: 409px;
   }
}

@media screen and (max-width: 421px) {
   .container {
       width: 202px;
   }
}

.box {
    width: 200px;
    height: 30px;
    display: inline-block;
    background: #fff;
    line-height: 30px;
    text-align: center;
    border: 1px solid gray;
}
<p>How is it possible to have the container sized to fit its children?</p>
<div class="container">
    <div class="box">x</div>
    <div class="box">x</div>
    <div class="box">x</div>
</div>

注意:调整浏览器大小并查看结果!

关于html - 使父 div 适合其子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50256501/

相关文章:

javascript - 搜索 JSON 数组中的项目

javascript - ionic 2 : Add Class to Item While Removing Class From Other Items

javascript - 我怎样才能强制 PhantomJS 等到 MathJax 完成?

javascript - 如何将 XML 数据包装在 HTML 表格中?

jquery - 隐藏在其他元素上的 CSS 菜单

html - 调整父元素大小时,使用内联 block 的 Div 重叠

html - 悬停影响两个元素

css - Bootstrap 脚本和样式不起作用

css - parent * :hover {} and parent:hover * {}?有什么区别

html - 将文本垂直居中在单行文本区域旁边?