unloco
unloco

Reputation: 7330

Image exceeding parent size

I want to center and restrict an image
I have an outer container and an image-container which has display: inline-block; to have the same size as the image (required, will contain draggable items)
But the image keeps exceeding the height: 100%;
Is there a workaround to get the desired result (as in the screenshot) enter image description here

.container {
  width: 300px;
  height: 100px;
  background: red;
  text-align: center;
}

.image-container { 
  display: inline-block;
  background: #0f0;
  outline: 5px solid #00f;
  max-width: 100%;
  max-height: 100%;
  
}

.main-image {
  max-width: 100%;
  max-height: 100%;
}
<div class="container">
  <div class="image-container">
    <img class="main-image" src="http://via.placeholder.com/400x400" />
  </div>
</div>

fiddle

Upvotes: 0

Views: 2921

Answers (2)

Potter
Potter

Reputation: 643

I ended up using absolute positioning on the image-container to collapse it to the size of the child. this requires position: relative on the parent container. overflow: hidden is added here to fix slight offset due to the transform on image-container.

.container {
  width: 300px;
  height: 100px;
  background: red;
  position: relative;
  overflow: hidden;
}

position, top, left, and transform are set here to center the image-container vertically and horizontally in the parent container.

.image-container {
  background: green;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

max-width and max-height need to match the parent container's width and height.

.main-image {
  max-width: 300px;
  max-height: 100px;
}

fiddle

Upvotes: 1

VXp
VXp

Reputation: 12118

You can do it like this:

.container {
  width: 300px;
  height: 100px;
  background: red;
  display: flex;
}

.image-container { 
  display: flex;
  justify-content: center; /* horizontal centering */
  background: #0f0;
  outline: 5px solid #00f;
}

img { /* responsiveness */
  display: block;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
}
<div class="container">
  <div class="image-container">
    <img class="main-image" src="http://via.placeholder.com/400x400">
  </div>
</div>

Upvotes: 1

Related Questions