电脑和移动设备上不同的英雄背景图片

问题描述 投票:0回答:1
html css bootstrap-4 responsive-design
1个回答
0
投票

我理解您的意思,如果您需要根据用户访问您网站的设备的大小使用不同的图像,我建议您使用

srcset
元素上的
img
属性。这是示例代码:

/* Basic Section Styling */
section {
    position: relative;
    width: 100%;
    height: 200px;
    /* aspect-ratio: 16 / 9; You can use also use Aspect Ratio of 1920x1080 */
}

/* This pseudo-class is for the overlay effect */
section::after {
    content: "";
    position: absolute;
    inset: 0;
    background-image: linear-gradient(rgba(0, 0, 0, 0.45), rgba(0, 0, 0, 0.5));
}

/* This will be the image that will be displayed */
img {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
}

/* This is to place the content above the image */
.container {
    position: relative;
    z-index: 1;
}
<section class="bgimage d-flex align-items-center">
    <img
        src="https://placehold.co/3200x800.png"
        srcset="
            https://placehold.co/800x200.png   800w,
            https://placehold.co/1600x400.png 1600w,
            https://placehold.co/3200x800.png 3200w
        "
    />
    <!-- 1st URL image will be shown if the screen size is equal or less than 800px -->
    <!-- 2nd URL image will be shown if the screen size is equal or less than 1600px -->
    <!-- 3rd URL image will be shown if the screen size is equal or less than 3200px -->

    <!-- You will put your image URL with the desired width of the screen -->
    <div class="container">
        <div class="row">
            <div class="col text-center">
                <h1 class="bgimage_title text-white">Rendelés menete</h1>
                <!-- Your rest of the content goes here -->
            </div>
        </div>
    </div>
</section>

注意事项:

  • 如果您已经加载了浏览器第一次重新加载的较大图像,之后缩小屏幕尺寸不会将图像变回小尺寸,并且将保持大尺寸
  • 如果您想查看小图像,则必须硬重新加载浏览器(Ctrl + F5)以从浏览器缓存中清除图像。
  • 用户屏幕尺寸显然不可调整,因此如果他们首先在小屏幕上打开它,这不会给用户带来任何问题。

如果您想了解

srcset
如何工作的详细信息和完整解释,我强烈建议您阅读此博客,我也使用此博客作为回答您问题的参考。

博客链接和信用转到:https://blog.webdevsimplified.com/2023-05/responsive-images/

© www.soinside.com 2019 - 2024. All rights reserved.