3

I'm trying to create a simple header and I'm having problems with the logo image because it's taking more space than needed.

.wrapper {
  display: flex;
  flex-direction: row;
  height: 50px;
}
.logo {
  padding: 5px;
}
img {
  height: 100%;
}
.content {
  padding: 5px;
}
<div class="wrapper">
  <div class="logo"><img src="http://placehold.it/350x150"/></div>
  <div class="content">content</div>
</div>

As you can see, the "content" text isn't placed near the logo, because the logo wrapper has a width equal to the size of the image before it gets resized by CSS.

I noticed that if I set height: 100% to the .logo element the situation is a bit better, but doing so, the "content" text overlaps a bit the image.

How can I fix it?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Fez Vrasta
  • 14,110
  • 21
  • 98
  • 160

2 Answers2

4

Here are two ways to fix the problem:

Method #1 – Remove the extra wrapper. Make the image itself the flex item.

.wrapper {
  display: flex;
  flex-direction: row;
  height: 50px;
}
img {
  height: 100%;
}
.content {
  padding: 5px;
}
<div class="wrapper">
  <img src="http://placehold.it/350x150"/><!-- div wrapper removed -->
  <div class="content">content</div>
</div>

Method #2 – Define a height for the image wrapper. (No changes to the HTML.)

.wrapper {
  display: flex;
  flex-direction: row;
  height: 50px;
}

.logo {
  height: 100%; /* new */
  border: 1px dashed red;
}

img {
  height: 100%;
}

.content {
  padding: 5px;
  margin-left: 5px;
  border: 1px dashed red;
}
<div class="wrapper">
  <div class="logo"><img src="http://placehold.it/350x150" /></div>
  <div class="content">content</div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
0

You have to explicitly set image height in pixels. height: 100% will use the image original height, NOT its container height.

I added justify-content and align-items to the flex container so things get properly positioned.

.wrapper {
  display: flex;
  flex-direction: row;
  height: 50px;
  justify-content: flex-start;
  align-items: flex-start;
}
.logo {
  padding: 5px;
}
img {
  max-height: 50px
}
.content {
  padding: 5px;
}
<div class="wrapper">
  <div class="logo"><img src="http://placehold.it/350x150"/></div>
  <div class="content">content</div>
</div>
JoannaFalkowska
  • 2,771
  • 20
  • 37
  • `height: 100%` refers to the parent height, in fact the image in my snippet has the correct height. – Fez Vrasta Feb 23 '17 at 13:40
  • I don't understand: either the image is supposed to have 50px height (parent) or 150px height (original). Which one is it? Or are they both the same? Cause in this case height: 100% would also work, obviously. – JoannaFalkowska Feb 23 '17 at 13:43
  • You say that `100%` refers to the original image size, this is wrong, it refers to its parent height. – Fez Vrasta Feb 23 '17 at 13:44