Html 拉伸图像以填充浏览器窗口的宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9731163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:09:26  来源:igfitidea点击:

Stretch an image to fill width of browser window

htmlcss

提问by Billjk

I have an image, and I want the width to fill up the browser window, no matter the size of the window.

我有一个图像,无论窗口大小如何,我都希望宽度填满浏览器窗口。

How do I do this in HTML and CSS?

我如何在 HTML 和 CSS 中做到这一点?

回答by sbagdat

You can add a div with width an height of 100%, also set image's width and height are 100%

您可以添加宽度和高度为 100% 的 div,还可以将图像的宽度和高度设置为 100%

<div id="wrapper">
    <img src="http://lorempixel.com/200/200" />
</div>??????????

CSS:

CSS:

#wrapper, img{
    width:100%;
    height: 100%;
}

jsfiddle

提琴手

回答by Brian Willis

<img src="filename.jpg" alt="alt text" width="100%" />

This assumes that the image's container is as wide as the browser window.

这假设图像的容器与浏览器窗口一样宽。

回答by DianaHeit

You add the following <meta>element in the head of your HTML document:

<meta>在 HTML 文档的头部添加以下元素:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Then you add

然后你添加

max-width:100%;
height:auto;

as a CSS rule for both the image and the container of the image. (It can also work for the image without having a container.)

作为图像和图像容器的 CSS 规则。(它也可以用于没有容器的图像。)

And you add

你加上

body {
    margin: 0;
}

to get rid of the margin around the image and/or container. This is how your image will fill the whole width of the screen, no matter what size the screen is.

摆脱图像和/或容器周围的边距。无论屏幕大小如何,这都是您的图像填充整个屏幕宽度的方式。

回答by Sabarish R

<div class="fixpixel">
    <img src="ImagePath" />
</div>??????????

CSS file

CSS文件

.fixpixel img{
height: auto;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
 }

回答by SLop

The margin of the body element is set to a default of 8px, which is the space you are seeing which prevent the image to stretch the full width and height of the screen.

body 元素的边距设置为默认值 8px,这是您看到的空间,防止图像拉伸屏幕的整个宽度和高度。

You can include

你可以包括

body {margin: 0px;}

to prevent this behavior, which I guess was put in place to prevent unstyled pages to present the content pushing to the edge of the page. It was discussed here.

为了防止这种行为,我想这是为了防止无样式的页面将内容推送到页面边缘。在这里讨论