html - 如何使用 flexbox 在每个断点处居中 div?
问题描述
我想以我目前拥有的方式将 div 居中,但问题是当有两个 div 时,它们不会与上面的矩形对齐。我知道它们会与 对齐justify-content:space between
,但这会阻止 div 当它是行中唯一的一个时居中。我想做的事有可能吗?
.wrapper {
max-width: 1000px;
margin: 0 auto
}
.title {
width: 100%;
height: 100px;
background: green;
margin-bottom: 30px;
}
.outer {
width: 100%;
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.col {
/* flex-grow, flex-shrink, flex-basis*/
flex: 0 0 31%;
margin: 0 1% 2% 1%;
height: 300px;
}
.col1 {
background-color: red;
}
.col2 {
background-color: blue
}
.col3 {
background: black;
}
@media only screen and (max-width: 960px) {
.col {
flex: 0 0 48%;
}
}
@media only screen and (max-width: 480px) {
.col {
flex: 0 0 100%;
}
}
<div class="wrapper">
<div class="title">
</div>
<div class="outer">
<div class="col col1">
</div>
<div class="col col2">
</div>
<div class="col col3">
</div>
</div>
</div>
解决方案
您可以将 a 设置margin-left: auto
为.col1
和margin-right: auto
以.col2
分别推送 div。
.wrapper {
max-width: 1000px;
margin: 0 auto
}
.title {
width: 100%;
height: 100px;
background: green;
margin-bottom: 30px;
}
.outer {
width: 100%;
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.col {
/* flex-grow, flex-shrink, flex-basis*/
flex: 0 0 31%;
margin: 1% 0 2% 0;
height: 300px;
}
.col1 {
background-color: red;
margin-right: auto;
}
.col2 {
background-color: blue;
margin-left: auto;
}
.col3 {
background: black;
}
@media only screen and (max-width: 960px) {
.col {
flex: 0 0 48%;
}
}
@media only screen and (max-width: 480px) {
.col {
flex: 0 0 100%;
}
}
<div class="wrapper">
<div class="title">
</div>
<div class="outer">
<div class="col col1">
</div>
<div class="col col2">
</div>
<div class="col col3">
</div>
</div>
</div>
推荐阅读
- android - Camera2默认控制场景模式为CONTROL_SCENE_MODE_FACE_PRIORITY
- php - 如何在 WooCommerce 商店页面中为未登录用户显示不同的图像?
- python - Selenium (Python):元素不可点击
- typescript - 如何声明必须可以为空或不可定义的类型
- python - 尝试使用 Jupyter Notebooks 从模块导入函数时出现 ModuleNotFoundError
- python - TOP 10 数据框 + 条形图
- python - Python selenium 向下滚动 Instagram 用户喜欢
- python - 这些句子使用 Rasa NLU 是什么意思?
- c++ - c++中系统命令的奇怪行为
- c - 如何通过结构访问 char* 的二维数组?