You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

移动端实现Razor页面循环生成的Div每行显示一个的问题求助

移动端实现Razor页面循环生成的Div每行显示一个的问题求助

我知道类似的问题挺多,但到我自己的场景里就不知道怎么落地了😅。我在Razor页面里用@foreach循环生成了一排并排的div,在笔记本电脑上显示正常,但切换到移动端后,整个页面的内容就挤在一起了。我试着用@media媒体查询来实现移动端每行只显示一个div,但折腾了好久都没搞定,尤其是图片高度这块一直调不顺。另外我也是刚接触复杂CSS,可能我的CSS写得有点冗余,麻烦大家帮忙看看我的代码,给点改进建议!

我的Razor页面代码

@page
@model Products.Pages.NoLayoutModel
{
    Layout = null;
}
@Html.AntiForgeryToken()
<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
    <link rel="stylesheet" href="~/css/Products_erase.css" asp-append-version="true" />
</head>
<body>
    <div>
        @foreach (var product in Model.availableProducts)
        {
            <div class="divouterproductcontainer">
                <div class="divinnerproductcontainer">
                    <div class="divimage">
                        <img id="@product.ProductId" class="imgproduct" src="@product.ImageUrl">
                    </div>
                </div>
            </div>
        }
    </div>
</body>
</html>

我的CSS代码

.imgproduct {
    height: 98%;
    width: 98%;
    object-fit: contain;
}

.divimage {
    width: 100%;
    height: 250px;
    display: flex;
    justify-content: center;
}

.divouterproductcontainer {
    width: 25%;
    float: left;
    display: inline-block;
    box-sizing: border-box;
}

.divinnerproductcontainer {
    width: 95%;
    border: 1px solid red;
}

@media only screen and (width < 1000px) {
    .divouterproductcontainer {
        width: 100%;
        float: left;
        display: inline-block;
    }
}

我尝试过的方法&遇到的问题

我给移动端加了媒体查询,把.divouterproductcontainer的宽度设为100%,但实际效果还是不对,内容还是挤在一起,而且图片的高度在移动端显得很奇怪,要么被拉伸要么显示不全。


内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 11:04:30