html - 如何将行内 block 元素与边距居中

标签 html css centering

HTML:

<div id="wrap">
    <div id="block1"></div>
    <div id="block2"></div>
</div>

CSS:

div#wrap{
    margin-top: 3em;
    border: solid 1px black;
    text-align: center;
}

div#wrap *{
    display: inline-block;
    width: 12.5em;
    margin-top: 1em;
    height: 8em;
}

div#wrap *:not(:last-child){
    margin-right: 8em;
}

#block1{
    background: orange;
}

div#wrap #block2{
    background: magenta;
}

这两个 block 应该在响应式设计模式中居中。当屏幕足够宽以连续显示 2 个 block 时,代码就可以工作了。但是当我缩小屏幕时,由于边距,顶部 block 向左移动:

enter image description here

fiddle

是否可以在没有媒体查询的情况下解决这个问题?

编辑

我试过 flex-box:

div#wrap{
    margin-top: 3em;
    border: solid 1px black;
    display: flex;
    flex-flow: row wrap;
    justify-content: center;
}

fiddle2

最佳答案

一个解决方案是使用 flex 和 justify-content:space-around 并移除边距:

div#wrap {
  margin-top: 3em;
  border: solid 1px black;
  justify-content:space-around;
  display: flex;
  flex-wrap: wrap;
}

div#wrap * {
  display: inline-block;
  width: 12.5em;
  margin-top: 1em;
  height: 8em;
}

#block1 {
  background: orange;
}

#block2 {
  background: magenta;
}
<div id="wrap">
  <div id="block1"></div>
  <div id="block2"></div>
</div>

关于html - 如何将行内 block 元素与边距居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48015115/

相关文章:

jquery - 使用 HTML 和 JQuery 创建可编辑列表

html - 表格行中同一行的选择框和输入框

HTML/CSS 需要 div 占父级垂直高度的 100%

css - 如何在 div 中创建固定大小的文本框?附上图片

javascript - 使用 HTML5 将两个 Canvas 方 block 设置到 Canvas 的中心

Html 表单不包含在帖子的参数文件数据中

css - Div 布局随着移动浏览器的变化而变化

c# - 如何使标签在 WinForms 中居中?

html - 你如何在 CSS 中将一个换行的 <nav> 菜单居中?

html - css 布局显示不正确