javascript - 如何使我的 div 居中并使它们与媒体查询堆叠
问题描述
所以我有这个,它应该在媒体查询命中之前并排在中间,然后当它命中时它应该堆叠在一起。我不知道它为什么会这样。
我尝试在 ti 处于全宽时使其居中,但它不想居中,当我使浏览器小于 400 像素时,它们奇怪地堆叠,它们确实堆叠在顶部但不居中。
.wrapper {
margin-top: 15%;
border : 2px solid #000;
overflow:hidden;
}
.wrapper div {
min-height: 300px;
padding: 10px;
}
#one {
background-color: orange;
float:left;
display: inline;
margin-left: 30%;
height: 400px;
width:250px;
border-right:2px solid #000;
}
#two {
background-color: orange;
float:left;
margin-right:30px;
height: 400px;
width:250px;
border-right:2px solid #000;
}
@media screen and (max-width: 400px) {
#one {
float: none;
margin-right:0;
bottom: 10%;
border:0;
}
#two {
float: none;
margin-right:0;
bottom: 10%;
border:0;
}
}
<div class="wrapper">
<div id="one">one</div>
<div id="two">two</div>
</div>
解决方案
使用 flexbox,您可以轻松地做到这一点,而无需媒体查询:
.wrapper {
margin-top: 15%;
border: 2px solid #000;
display: flex;
justify-content: center; /*center the element*/
flex-wrap: wrap; /*make them above each other when they cannot fit in one row*/
}
.wrapper div {
min-height: 300px;
padding: 10px;
background-color: orange;
height: 400px;
width: 250px;
border: 2px solid #000;
}
<div class="wrapper">
<div id="one">one</div>
<div id="two">two</div>
</div>
您也可以使用inline-block
代替float
:
.wrapper {
margin-top: 15%;
border: 2px solid #000;
overflow: hidden;
text-align:center;
}
.wrapper div {
min-height: 300px;
padding: 10px;
}
#one {
background-color: orange;
display: inline-block;
height: 400px;
width: 250px;
border-right: 2px solid #000;
}
#two {
background-color: orange;
display: inline-block;
height: 400px;
width: 250px;
border-right: 2px solid #000;
}
<div class="wrapper">
<div id="one">one</div><div id="two">two</div>
</div>
推荐阅读
- java - 如何使用另一个数组列表提供的索引比较数组列表中的元素
- java - 服务器不听请求
- r - 数据框操作:变量操作
- c# - 在公共项目中使用 mimekit nuget 包(通过 paket)从引用公共项目的其他项目中删除现有 System.net.http.dll
- java - 如何调用 Ajax 请求以从数据库中获取记录并在页面加载时使用 servlet 在 jsp 上显示
- excel - 如何使用 putty 将多个命令传递给 VBA 中的 Shell 函数?
- python - 有没有办法让一个对象与 Python Turtle 中的另一个对象一起旋转?
- python-3.x - 使用 word2vec 确定最相似的短语
- android - 将 Fragment 与其在另一个 Fragment 中的更新链接
- traefik - Traefik 背后的码头服务