html - 如何在媒体查询设置的流体布局中垂直和水平居中子元素?

标签 html css responsive-design vertical-alignment centering

我正在尝试实现某种流畅的布局,其中每个 DIV 的内容在垂直和水平方向上居中。但是,我的中间行(A、B、C)一直存在垂直和/或水平对齐问题。

目标是让它像这样工作:

enter image description here

Note: If there's a way I can have the option to set the Mobile layout's "C" area fluid as well (without having to change the HTML, just the CSS, so that I can test which option works best), that'd be a bonus!

这是 HTML 的片段:

<div class="page">
    <div class="col col-top">top</div>
    <div class="col col-mid">
        <div class="col col-left">
            <div class="centerBox"><div class='debugBox'></div></div>
        </div>
        <div class="col col-center">
            <div class="centerBox"><div class='debugBox'></div></div>
        </div>
        <div class="col col-right">
            <div class="centerBox"><div class='debugBox'></div></div>
        </div>
    </div>
    <div class="col col-bottom">bottom</div>
</div>

我不确定带有“centerBox”类的“包装”DIV 是否真的有必要(它们被设置为 display: table-cell 而每个 col 类被设置为 display: table表现像表格,但这会导致将这些区域放置为 position: absolute 和 % 值的问题它们的左/右/上/下属性。

例如,如果“C”区域设置为display: table,会发生这种情况:

enter image description here

如果我将“C”区域更改为 display: block;,那么它会填满整个中心区域,但是......

enter image description here

...水平和垂直对齐方式在其中中断。

使用“Ghost”DIV 元素(如 css-tricks article 中所讨论,Chris Coyier 的“Centering in the Unknown”)是否会更好地获得正确对齐?

最佳答案

好的,这个解决方案没有框架,使用 flexbox 的纯 CSS。只要布局是水平的,C 就有固定的宽度。移动时,C占据整个宽度,高度可变。

header,
footer {
  padding: 10px;
  background-color: lightblue;
}
main {
  display: flex;
  flex-direction: row;
}

main > div {
  padding: 10px;
  background-color: tomato;
  flex-grow: 1;
  min-height: 40px;
  display: flex;
  align-items: center;
}
main > div:nth-child(2) {
  background-color: olive;
}

.fixed {
  width: 400px;
}

@media (max-width: 768px) {
  main {
    flex-direction: column;
  }
  .fixed {
    width: auto;
  }
}
<header>Top</header>
<main>
  <div>A</div>
  <div class="fixed">C</div>
  <div>B</div>
</main>
<footer>Bottom</footer>

这里是笔(拖动边框看移动布局): Codepen

关于html - 如何在媒体查询设置的流体布局中垂直和水平居中子元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33875537/

相关文章:

css - 检查 facebook 图像时奇怪的 CSS 背景图像 url

javascript - 如何附加按比例缩小的大宽度 Canvas ,以使页面宽度不会变大

responsive-design - bootstrap 3.0 全长正文侧边栏

html - 为什么选中这些自定义复选框会将屏幕位置移到顶部?

javascript - Dragula 放入多个 div

html - 从特定 DIV 中删除所有 CSS

css - 尽可能在响应式设计中使用固定元素,仅使用 css

php - 如何防止导航栏元素重叠?

javascript - Chrome 应用程序中的按钮不起作用

html - 如何将 html 文件转换为 Bootstrap 模板