Acrux
Acrux

Reputation: 406

Scale image based on div

Hi I am having difficulty making my image responsive to div. Is there a way to simply have css "cut off" parts which do not fit and simply show whatever fits inside the div?

HTML

<div class="col-md-4">
      <div style="height:42vh; background-color:#f2f2f2; margin-top:0px; margin-bottom:30px;" >
      <!--IMAGE DIV-->
      <div id="imgdiv" style="height:28vh;" class="img-responsive">
      </div>

      <div style="height:14vh; background-color:#1c1818; padding-top:0.95em; padding-left:1.75em; padding-right:1.75em;"><%= link_to event.name, event, 'data-no-turbolink' => true, :style=>"float:left; font-family: 'Roboto' !important; font-size:1.5em; color:white;" %> <br>
        <div style="float:left; font-family: 'Roboto' !important; font-size:1em; color:white; margin-top:0.15em;"><%= event.start_date.strftime('%B %d, %Y')%><br>
        <span style="float:left;"><%= event.city%> City</span></div>
      </div>

      </div>
</div>

CSS

#imgdiv{
background-image: url(http://lorempixel.com/500/226/fashion);
background-repeat: no-repeat;
background-size: contain;
}

I am also using twitter bootstrap, however the class="img-responsive" does not meet my needs. When the image does not have the same aspect ratio, there is blank space for the shorter side--it always tries to fit the whole image inside the div. Is there another way to go about this? Should I use javascript for this? If so, how do I go about it?

Thanks in advance. :)

Upvotes: 1

Views: 89

Answers (4)

Francis
Francis

Reputation: 137

This may be a duplicate to another question. But check this out. https://medium.com/@chrisnager/center-and-crop-images-with-a-single-line-of-css-ad140d5b4a87

img {
   object-fit: cover;
}

Upvotes: 1

David Wilkinson
David Wilkinson

Reputation: 5118

Try using the background-size: cover value if you want the background image to scale within the div according to viewport:

#imgdiv{
  background-image: url(http://lorempixel.com/500/226/fashion);
  background-repeat: no-repeat;
  background-size: cover;
}

If you want the background image to simply "cut-off", you can try omitting the background-size property altogether...

Upvotes: 2

Roland Ruul
Roland Ruul

Reputation: 1242

To make something responsive to it's parent node you must give it width of 100% and auto height.

Example css:

img {
    width: 100%;
    height: auto;
}

And jsfiddle: https://jsfiddle.net/04mLykqc/

Upvotes: 1

Renuka CE
Renuka CE

Reputation: 686

use background-size: cover; instead background-size: contain; in CSS, It will help you.

Upvotes: 2

Related Questions