如何查看标题中的所有图像 - CSS

时间:2017-01-07 16:00:56

标签: css image css3

我想知道如何在CSS标题中看到100%的图片。问题是,当我将图像添加到标题时,图像不会调整大小,所以我必须使标题更大,但我不想要它。

.header{
  background-image: url("../IMAGES/myimage.png");
  width: 100%;
  height: 100px;
}

基本上我想要调整图像大小的标题,这样我就可以在标题中看到标题中包含我想要的尺寸的完整图像。我是CSS新手。随意提出任何问题。谢谢。

3 个答案:

答案 0 :(得分:2)

  

我如何在带有CSS的标题中看到100%的图片

要完整地查看背景图片,请使用

background-size: contain;

.header{
  background-image: url("//placehold.it/300x100/cf5");
  background-size: contain;
  background-repeat: no-repeat;     /* add this to not repeat it as pattern */
  background-position: 50% 50%;     /* center it? */
  height: 100px;
}
<div class="header"></div>

比需要的id还可以使用background-position来设置它的位置

如果您希望图片填充整个标题区域而不会出现扭曲,请使用

background-size: cover;

.header{
  background-image: url("//placehold.it/300x100/cf5");
  background-size: cover;
  background-repeat: no-repeat;     /* add this to not repeat it as pattern */
  background-position: 50% 50%;     /* center it? */
  height: 100px;
}
<div class="header"></div>

如果您不关心图像是否扭曲但是您希望图像拉伸到填充而不是使用

background-size: 100% 100%;

.header{
  background-image: url("//placehold.it/300x100/cf5");
  background-size: 100% 100%;
  height: 100px;
}
<div class="header"></div>

答案 1 :(得分:0)

如果不完全知道你真正希望实现的目标,我认为你正在努力做到,background-size property会做什么。

使用background-size: cover;,您可以强制背景图像覆盖相应元素的整个区域(如div)。

您的代码示例如下所示

.header{
  background-image: url("../IMAGES/myimage.png");
  width: 100%;
  height: 100px;
  background-size: cover;
}

答案 2 :(得分:-1)

只需使用:

max-width: 100%;

在图像的css上,这将使其达到最大值,即容器宽度的100%。

<强>澄清

对于容器标题内的图像,max-width将起作用。如果是背景图片,background-size:contains会将图片保留在标题内,而封面则会展开图片以覆盖整个标题。

.header > img {
  max-width: 100%;
  height: 200px;
  width: 600px;
}

.header2 {
  background-image: url("https://source.unsplash.com/random/500x500");
  background-size: contain;
  background-repeat-x: no-repeat;
  height: 200px;
  width: 600px;
}

.header3 {
  background-image: url("https://source.unsplash.com/random/500x500");
  background-size: cover;
  background-repeat: no-repeat;
  height: 200px;
  width: 600px;
}
<div class="header">
  This is my header
  <img src="https://source.unsplash.com/random/500x500" alt="and this is my image inside it" />
</div>

<div class="header2">
  This is my second header with a background contained inside
</div>

<div class="header3">
  This is my third header with a background covering it
</div>

相关问题