【问题标题】:Horizontal div layout within a foreachloopforeach 循环中的水平 div 布局
【发布时间】:2010-05-24 20:11:37
【问题描述】:

我正在尝试在现有网站上集成一小部分,我的问题似乎很简单,但我似乎无法理解它。这是我想要的样子:

alt text http://img691.imageshack.us/img691/329/layouth.jpg

蓝色 = #pagecontainer
红色 = #sectioncontainer
黄色 = .post

pagecontainer { height: 100%; width: 900px;}
post container {width: 900px;}
.post {width: 210px;}

四个帖子正在从 WordPress 中提取,使用:

<?php if (have_posts()) : ?>
<?php query_posts('category_name=Category&posts_per_page=4'); ?>
<?php while (have_posts()) : the_post(); update_post_caches($posts); ?>
    <div class="post">
        <?php the_content() ?>
    </div>
<?php endwhile; ?>

帖子的宽度固定,但高度不同。问题是,如果没有最后一个帖子将 div 推到下面,我不能在中间放置垫片,而且我不能使用边距,因为第一个和最后一个 div 会碰到页面容器。

我可能会使用类似的东西

.post {margin-right: 20px;}
.post:last-child {margin: 0 !important;}

...但这看起来很乱,我宁愿避免使用子伪选择器。

对更简洁的解决方案有什么想法吗?

【问题讨论】:

    标签: php wordpress css


    【解决方案1】:

    您可以使用 $count

    类似:

        <?php $count = 0; ?>
    
        <?php while (have_posts()) : the_post(); update_post_caches($posts); ?>
    
        <?php $count++; ?>
    
        <?php if ($count < 5) {
             $class = 'post';
        } else {
             $class = 'post-last';
        } ?>
    
        <div class="<?php echo $class; ?>">
              <?php the_content() ?>
        </div>
    
        <?php endwhile; ?>
    

    然后只需将 CSS 中的“post”类设置为具有 20px 的边距,将“post-last”设置为没有边距

    【讨论】:

    • 冠军!谢谢。比必须使用负边距更好。
    【解决方案2】:

    尝试使用基于边距的解决方案,但不要使用:last-child 技巧(不幸的是不是跨浏览器),而是将右侧的父级边距设置为等效的负值:

    .post {margin-right: 20px;}
    .secioncontainer {margin-right: -20px;}
    

    还要确保.posts 之间没有空格。您可以修改标记,使其写在没有空格的一行中:

    <?php while (have_posts()) : the_post(); update_post_caches($posts); ?><div class="post"><?php the_content() ?></div><?php endwhile; ?>
    

    或使用 CSS 技术,例如:

    .secioncontainer {font-size: 0px;}
    .post {font-size: /*your normal value*/;}
    

    【讨论】:

    • 负边距是个好主意,无论如何我找到的最好的解决方案。 .post {margin-left: 20px;} .secioncontainer {margin-left: -20px;宽度:920px;} 谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多