-1

I have an issue with my images (svg, jpg,...., all formats). For instance if I want to make a header and set in CSS the header height for instance like this:

.container {
  width: 1024px;
  min-height: 300px;
  margin-left: auto;
  margin-right: auto;
}

header {
  height: 300px;
  display: flex;
  align-items: center;
}
<div class="container">
  <header>
    <div>
      <img src="https://via.placeholder.com/400/09f/fff.png" alt="" />
    </div>
    <nav>
      <a href="#"></a>
      <a href="#"></a>
      <a href="#"></a>
      <a href="#"></a>
    </nav>
  </header>
</div>

The image extends over the borders. How can I tackle that issue?

TylerH
  • 20,799
  • 66
  • 75
  • 101
  • 2
    `img { width: 100%; }` will solve your issue. By default the image will display nativly (be as wide as the image has pixels). Just limit the width to 100% of the parents width. – tacoshy Jun 21 '22 at 22:28
  • 1
    Hi and Welcome to SO. Please take the [tour] first. Then read [how to ask questions here](https://stackoverflow.com/help/how-to-ask). Note, that asking `for the best practise` is usually opinion-based and as such then **off-topic** for SO. SO is not a discussion board but a very strict and focused Q&A Forum. – tacoshy Jun 21 '22 at 22:29
  • @tacoshy Due to the fact his image is nested within both `
    ` and `
    ` tags before reaching the parent with it's size set, doing this will not be enough alone to fix the issue.
    – Libra Jun 21 '22 at 22:46

1 Answers1

-1

If the image needs to nested within div that themselves are nested within the constricting parent, you'll need to specify the size on those also.

.container{
  height: 300px;
  width: 1000px;
  margin: 0 auto;
  border: 3px solid red;
}

.container header, .container div{
  height: 100%;
}

img{
  height: 100%;
  width: auto;
}
<div class="container">
  <header>
    <div>
      <img src="https://via.placeholder.com/500" alt="">
    </div>
  </header>
</div>
Libra
  • 2,544
  • 1
  • 8
  • 24