html - PHP 中的 PHP 媒体查询宽度

标签 html css

我在 php 中有一个小脚本:

<section>
<?php
    $sql = "SELECT * FROM bilder";
    $result=mysqli_query($db,$sql);
    $counter = 1;
    while($row=mysqli_fetch_assoc($result)){
        if($counter == 1){
            echo "<img class='image' src='$row[bild_pfad]' alt='$row[bild_name]' style='$row[bild_werte]'>";
        }
        else{
            echo "<img class='image image-margin' src='$row[bild_pfad]' alt='$row[bild_name]' style='$row[bild_werte]'>";
        }
        if($counter == 6){
            $counter = 1;
        }
        else{
            $counter = $counter + 1;
        }
    } 
?>
</section>

此脚本创建“许多”图像。图像的信息在数据库中。在正常情况下 <section></section>925px宽度。 1 张图片是 150px x 150px大。

.image{
    object-position: center; /* Center the image within the element */
    height: 150px;
    width: 150px;
    object-fit: cover; 
}
.image-margin{
    margin-left: 5px;
}

正常情况下是6张并排的图片,左边距为5px。这就是我使用 $counter 的原因在脚本中,因为一行由 6 张图片组成,而第一张图片不需要留边距。现在我使用了一些媒体查询。

@media only screen and (max-width : 924px) {
section{
    margin: 0px auto;
    width: 770px;
    margin-top: 55px;
}
}
@media only screen and (max-width : 770px) {
section{
    margin: 0px auto;
    width: 615px;
    margin-top: 55px;
}
}
@media only screen and (max-width : 615px) {
section{
    margin: 0px auto;
    width: 460px;
    margin-top: 55px;
}
}
@media only screen and (max-width : 460px) {
section{
    margin: 0px auto;
    width: 305px;
    margin-top: 55px;
}
}

每个媒体查询类都会将行缩小 1,图片放在下一行。我的问题:在脚本中我连续设置了 6 张图片,我如何为媒体查询自定义它? (对于一行中的 5-、4-、3-、2- 图片)

最佳答案

不要使用计数器变量来确定边距的位置。

使用 nth-child CSS 选择器来确定哪些图像应该有边距。

https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

https://css-tricks.com/how-nth-child-works/

设置右侧的边距并移除一行中最后一张图片的边距。

@media only screen and (max-width : 924px) {
/* Five images in each row */
section{
    margin: 0px auto;
    width: 770px;
    margin-top: 55px;
}
  section img{
     margin-right:5px;  
  }
  section img:nth-child(5n+5){
    margin-right:0;
  }
}
@media only screen and (max-width : 770px) {
  /* Four images in each row */
section{
    margin: 0px auto;
    width: 615px;
    margin-top: 55px;
}
  section img:nth-child(4n+4){
    margin-right:0;
  }
}

关于html - PHP 中的 PHP 媒体查询宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29109868/

相关文章:

javascript - Wordpress 单击后关闭主题菜单

html - 为什么这不缩进 HTML?

HTML 和 CSS 边距问题

Javascript:我的数组的大小随着每次 for 循环迭代而减小。为什么?

javascript - 在 iOS 设备上的 iframe 中填写表单时跳转页面

javascript - 如何修改由外部 javascript 创建的元素的类

jquery - 带有 Twitter Bootstrap 的响应式/流畅的 jQGrid

javascript - 页面完全加载事件

php - 导航栏当前类更改 php include

jquery - 自动滑动需要下一个,上一个选项