Home > Back-end >  How to add an image to my header background in html?
How to add an image to my header background in html?

Time:12-17

I would like to add an image to my header background, I tried this, but didn't work.

What am I doing wrong?

div.cabecalho {
  padding: 20px;
  font-size: 250%;
  text-align: center;
  background-image: url(https://via.placeholder.com/800/ff0000);
  vertical-align: middle;
  color: #ffffff;
  border-bottom: 30px solid #0f4098;
  width: 100%;
  align-items: center;
}

div.cabecalho span {
  margin-left: 20px;
}

img {
  object-fit: cover;
}
<div >
  <img src="https://via.placeholder.com/320x300" width="320" height="300">
  <span>Desempenho do <strong>PIB</strong> no terceiro trimestre de 2021</span>
</div>

CodePudding user response:

Judging by text-align: center;, vertical-align: middle, and align-items: center; I'm going to take a wild guess and assume you want the background image centered. You can use background-image: center; in your CSS. background-size: cover; to expand the entire image throughout the header. align-items: center; generally only works with flex or grids

  • Check here to learn more about background properties.

div.cabecalho {
  padding: 20px;
  font-size: 250%;
  text-align: center;
  background-image: url(https://via.placeholder.com/800/ff0000);
  background-position: center;
  background-size: cover;
  color: #ffffff;
  border-bottom: 30px solid #0f4098;
  width: 100%;
  align-items: center;
}

div.cabecalho span {
  margin-left: 20px;
}

img {
  object-fit: cover;
}
<div >
  <img src="#" width="320" height="300">
  <span>Desempenho do <strong>PIB</strong> no terceiro trimestre de 2021</span>
</div>

CodePudding user response:

Your css and html looks like it will work. And in fact, when I tried it myself with copy and paste, but changing out the images, it did work. It may be an issue with the path of your image files. Try navigating directly to them in your browser to see if they display without issue.

Edit: After posting this, the original question was edited to replace the author's image paths and names with placeholders. This would appear to confirm my above statement, as using "run code snippet" with the placeholder images works. Thus the issue still appears to be with the images in use. Perhaps the path is incorrect or perhaps the images are not located there.

CodePudding user response:

Both images are being displayed on my end. The 800x800 can only be seen in a small screen.

Set your height to 100vh for example and you'll be able to see it. You may need to adjust the width of your image to fit within your header container.

Also please inspect your css img selector. Even if you remove it, you code will work as img { object-fit: cover; } is not working. Your code is applying the width you've set on your html.

  • Related