html - 如何在不破坏其他 CSS 属性的情况下将 CSS 中的 background-image 属性正确地传输到 HTML 代码中?

标签 html css image background-image

我首先在 div 中使用“背景图像”CSS 属性来显示图像,因为它可以按照我的需要正确显示:

  1. 图像位于导航栏下方(允许显示阴影)。
  2. 图像是边到边的,但只容纳不到 30% 屏幕高度根据用户屏幕尺寸。
  3. 图像允许半透明覆盖标题和 图片说明。
  4. 图像将填充(裁剪)以适合 Canvas 而不是拉伸(stretch) 缩小或缩小。

如何将“背景图像”CSS 属性作为标记传输到 HTML 中?因为 CSS 不支持替代文本,因为它们是我通过考试所必需的。 p>

I've tried to add a tag into HTML and removed background-image property from HTML (also ruleset name to accommodate the added img tag) However, it doesn't display it correctly as I wanted it to be.

== 代码 ==

旧代码:
CSS:

.image-container {
    padding-top: 10px;
    width: 100%;
    height: 48vw;
    min-height: 380px;
    max-height: 550px;
    background-image: url('/assests/DisplayImage.jpg');
    background-size: cover;
    position: relative;

.image-container .detail {
    position: absolute;
    bottom: 0;
    background: rgb(0, 0, 0);
    background: rgba(0, 0, 0, 0.5);
    color: #f1f1f1;
    width: 100%;
    padding: 0;
    text-align: center;
}

HTML:

    <div class="image-container">
        <div class="=detail">
            <h1>
                Title text
            </h1>
            <h3>
                Description
            </h3>
        </div>
    </div>

新代码:
HTML:

    <div class="image-container">
      <img scr=/assests/DisplayImage.jpg>
        <div class="=detail">
            <h1>
                Title text
            </h1>
            <h3>
                Description
            </h3>
        </div>
    </div>

CSS: (.image-container .detail 保持不变)

.image-container img{
    padding-top: 10px;
    width: 100%;
    height: 48vw;
    min-height: 380px;
    max-height: 550px;
    position: relative;
}

我希望它是这样的: Expected (original result)
相反,我得到了这个: The result of changing the code

除此之外,我还希望我的图像在调整屏幕大小时集中在图像的中心,而不是仅仅裁剪底部。

谢谢。这可能太具体了,但我相信这会帮助那些也使用 CSS 背景图像而不是 HTML 标记的人。

最佳答案

检查这个pen
如我所见,您的代码没有任何问题。
用于将图像对齐到中心使用

 background-position: center;

如果您将 img 标签用于图像,请使用以下属性。

object-fit: cover;
object-position: bottom;

关于html - 如何在不破坏其他 CSS 属性的情况下将 CSS 中的 background-image 属性正确地传输到 HTML 代码中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56580740/

相关文章:

python - 如何删除 Django 模板中的特定 HTML 标记?

jQuery 检测到损坏的图像太晚了

css - 这是标准行为吗? div从容器中流出

image - 我在哪里可以找到免费的天气图标?

html - 了解 HTML 元素为何具有其大小的一般方法

javascript - 如何将点击区域限制为文本?

jquery - 滚动条显示何时调用 jquery.show()

html - 选择框的自定义滚动条

java - 如何在我的 UI 中使用 vaadin 显示图片

图像数据库存储引擎