CSS 重新居中元素

标签 css responsive-design

我原以为这很简单,但事实证明这有点让人头疼。当用户调整浏览器大小时,我试图让图像网格重新居中并导致其中一个(或多个)换行到下一行。

我试过给 grid-wrapper display:inline-block;它的父值为 text-align: center;但这不会在元素换行时重新居中。感谢帮助。

要查看我正在尝试实现的目标,请查看 picture here
(来源:ianclarke.ca)
.

HTML:

<div class="parent-wrapper">
    <div class="child-wrapper">
        <!-- Worpress loop to load many thumnails -->
        <?php if(have_posts()) : ?><?php while(have_posts()) : the_post(); ?>
        <div class="project-thumbnail">
        <?php the_post_thumbnail('thumbnail'); ?>
        </div>
        <?php endwhile; ?>
    </div>
</div>

CSS:

.parent-wrapper
{
width:100%;
text-align: center;
}

.child-wrapper
{
display:inline-block;
}

.project-thumbnail{
float:left;
border:2px solid black;
min-width: 269px;
max-width: 269px;
}

最佳答案

这是我能想到的仅使用 CSS 的最佳解决方案,神奇的部分是 @media 查询。显然,您必须根据自己的情况进行计算。

JsFiddle Demo

body {
    margin: 0;
}
.parent-wrapper {
    margin: auto;
    width: 500px;
    padding: 5px 0;
    font-size: 0;
}
.child-wrapper {
    display: inline-block;
    width: 100px;
    font-size: 16px;
}
.child-wrapper img {
    max-width: 100%;
    height: auto;
    padding: 5px;
    vertical-align: top;
    box-sizing: border-box;
}
@media screen and (max-width: 499px) {
    .parent-wrapper { width: 400px; }
}
@media screen and (max-width: 399px) {
    .parent-wrapper { width: 300px; }
}
@media screen and (max-width: 299px) {
    .parent-wrapper { width: 200px; }
}
@media screen and (max-width: 199px) {
    .parent-wrapper { width: 100px; }
}
<div class="parent-wrapper">
    <div class="child-wrapper">
        <img src="//dummyimage.com/100" />
    </div>
    <div class="child-wrapper">
        <img src="//dummyimage.com/100" />
    </div>
    <div class="child-wrapper">
        <img src="//dummyimage.com/100" />
    </div>
    <div class="child-wrapper">
        <img src="//dummyimage.com/100" />
    </div>
    <div class="child-wrapper">
        <img src="//dummyimage.com/100" />
    </div>
    <div class="child-wrapper">
        <img src="//dummyimage.com/100" />
    </div>
</div>

关于CSS 重新居中元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30737863/

相关文章:

html - CSS 形状不符合预期。如何解决?

html - 显示 : inline-block forces new line

css - 扩展以填充空间但保持最小宽度的 div

html - 如何实现各方固定大小的动态宽度 div

jquery - 调整图像大小?

javascript - HTML 页面自动重新加载

html - react 引导 : Carousel carousel indicator

javascript - 使用附加按钮扩展 <Table/> UI

html - 在 IE6 中制作 <div> 覆盖

css - 将 <img> 下推其高度的 50% 仍然影响流量