我有一个包装器 <main>
和包装内的一些元素 <div class="item>
.这些元素的宽度为 200 像素,高度为 300 像素。我希望这些元素左对齐,以便在屏幕变小时它们向左堆叠。但在它们包裹后,我希望这些元素能够自行居中。
这是元素的图片。
当它们包裹起来时,它们看起来像这样:
但我希望它们看起来像这样
但我不想使用 text-align: center
因为那时我得到了这种格式
这是一个具有相同代码的codepen: https://codepen.io/isaacweaver/pen/wQvBXY/
最佳答案
假设您想为您的卡片设置宽度,您应该能够使用媒体查询来设置您的 <main>
元素的宽度。缩小浏览器窗口时,这会将卡片捕捉到下一行(左对齐)。没有 text-align: center;
需要。我在下面添加了一个片段,希望能显示您想要的内容:)
body{
background-color: #eee;
}
main{
margin: 0 auto;
text-align: center;
}
.item{
width: 300px;
height: 400px;
background-color: white;
display: inline-block;
margin: 0px;
transition: .5s;
}
.item:hover{
transform: translateY(-2px);
box-shadow: 0px 0px 39px 0px rgba(0, 0, 0, 0.44);
}
@media (min-width: 605px) {
main {
width: 605px;
text-align: left;
}
}
@media (min-width: 910px) {
main {
width: 910px;
}
}
@media (min-width: 1517px) {
main {
width: 1517px;
}
}
<html>
<body>
<main>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</main>
</body>
</html>
关于javascript - 左对齐时居中内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53125093/