html - div 与其内部的 div 一样宽

标签 html css width center parent

是否有一种 CSS 方法可以使父 div 的宽度与其中所有 div 的宽度相同。像这样:

+--------------------------------------------------+
|               DIV                                |
|                                                  |
|  +---------+    +---------+    +---------------+ |
|  |         |    |         |    |               | |
|  |         |    |         |    |               | |
|  |   DIV   |    |  DIV    |    |   DIV         | |
|  |         |    |         |    |               | |
|  |         |    |         |    |               | |
|  +---------+    +---------+    +---------------+ |
|                                                  |
|                                                  |
|                                                  |
|                                                  |
+--------------------------------------------------+


+---------------------------------------+
|                 DIV                   |
|  +-----------+    +---------------+   |
|  |           |    |               |   |
|  |           |    |               |   |
|  |           |    |               |   |
|  |   DIV     |    |     DIV       |   |
|  |           |    |               |   |
|  |           |    |               |   |
|  |           |    |               |   |
|  |           |    |               |   |
|  +-----------+    +---------------+   |
|                                       |
+---------------------------------------+

最后我想让父 div 水平居中。因此,我必须将子 div 的总宽度作为父 div 的宽度。我将使用 display:table 和 margin:0 auto 将父 div 居中。

有什么想法吗?

谢谢!

最佳答案

运行下面的代码片段,看看我已经根据您提供的图片创建了一个类似的布局,

使用完全响应式的 flexbox,一切都居中,一切都可以调整。

父 div 也水平居中。

* {
  margin: 0;
  padding: 0;
}
html,
body {
  width: 100vw;
  height: 100vh;
}
.container {
  display: flex;
  height: 100%;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
}
.parent_one,
.parent_two {
  display: flex;
  background-color: blue;
  height: 40%;
  justify-content: space-around;
  align-items: center;
}
.parent_one {
  width: 60%;
}
.parent_two {
  width: 30%;
}
.child {
  background-color: yellow;
  width: 30%;
  height: 90%;
}
<div class="container">
  <div class="parent_one">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
  </div>

  <div class="parent_two">
    <div class="child"></div>
    <div class="child"></div>
  </div>
</div>

关于html - div 与其内部的 div 一样宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35503216/

相关文章:

css - 移动表单选择与输入或文本区域的大小不同

html - chrome 与所有其他浏览器的输入文本框宽度不同

html - 为什么 chrome 开发工具报告的字体大小与 css 不同

javascript - 没有 "white-space: nowrap"的文本溢出省略号?

html - 需要基本的侧面菜单脚本帮助

javascript - 如何制作一个从底部平滑扩展到视口(viewport) 85% 的 div?

javascript - 在输入框的开头显示光标/插入符号

javascript - 正则表达式匹配css键值字符串

php - POST 表单显示错误回显

html - 使用 CSS calc() 函数将元素保留在多余空间的中间