javascript - 将容器中的 div 内容居中

标签 javascript html css web

在我的网站上,我有一系列这样的 div:

.box{
   float:left;
   width:143px;
   height:183px;
   overflow:hidden;
}

这些 div 在一个像这样的简单容器中:

.container{
   margin:70px 190px 0 190px;
   overflow:hidden;
}

我会实现响应式布局,但 div 在容器中不是水平居中的。我试图添加“margin-left:auto;”和“margin-right:auto”但没有。我有这样的布局:

enter image description here

相反,我会这样布局:

enter image description here

有人可以帮助我吗?

最佳答案

使用 FlexBox 的解决方案。

FlexBox Guide

FlexBox Browsers Compatibility

.container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-around;
  
    margin:7px 19px 0 19px;
    background-color: red;
}

.box {
    width:143px;
    height:183px;
    margin: 10px;
    background-color: black;
}
<div class="container">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</div>

关于javascript - 将容器中的 div 内容居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30289625/

相关文章:

javascript - 使用 javascript 查找特定 div 是否不可见(visible = false)

javascript - 使用 jquery 的按钮的奇怪行为

html - Rmarkdown HTML 渲染问题

html - 固定在 HTML 页面顶部的导航栏 (CSS/HTML)

ruby-on-rails - sprockets - 多个入口点?

javascript - 使用 jQuery 呈现随机字体图标(列表中的随机字符串)?

javascript - 将动态值绑定(bind)到 ng-repeat 内的进度条

html - 图像不会在 bootstrap 3 中的一行上对齐

javascript - Angular ng-class(2个参数之间)

html - 内联放置两个表单元素