Pizza lord
Pizza lord

Reputation: 763

Displaying a portion of a image in a div element

When i have a div that is for example 300*300px and a image that is 1280*560px. Can i show a specific part of the image in my div while it stays responsive while only using html/css?

the div is always taking up 33% of the page width

my code looks like this:

html

<div class="crop">
    <img src="path/to/img">
</div>

css

position: relative;
overflow: hidden;
min-height: 300px;

Upvotes: 2

Views: 3511

Answers (3)

Obink
Obink

Reputation: 329

yes you can do that with flex

this is the code, explaination below

div{
width:300px;
height:300px;
overflow:hidden;
position:relative;
left:50%;
transform:translateX(-50%);
display:flex;
justify-content:center;
align-items:center;
}
div img{
flex:0;
width:auto;
min-height:100%;}
<div>
  <img src ="http://www.cooperindustries.com/content/dam/public/safety/notification/products/Mass%20Notification%20Systems/Spotlight/MNS_WideArea_Spotlight3.jpg">
</div>

on justify-content you can put flex-start, flex-end, and center to fit which part you want to input horizontally

on align-items you can put the same thing as justify content to adjust vertically.

this image is landscape so i set min-height 100% and width auto, you can do the other side when you got a portrait image. if the image is square, width 100% will do just fine

Upvotes: 1

Ionut Necula
Ionut Necula

Reputation: 11472

Using a background-image might help you in this situation, you can adjust the position of it using background-position:

.crop{
  position: relative;
  overflow: hidden;
  min-height: 300px;
  width: 300px;
  background-image: url(https://cdn.pixabay.com/photo/2015/07/06/13/58/arlberg-pass-833326_960_720.jpg);
  background-size: contain;
}
<div class="crop">
</div>

Upvotes: 3

David Dylan
David Dylan

Reputation: 214

Yes, quite easy, in fact:

.image {
display: block;
position: relative;
overflow: hidden;
width: 300px;
height: 300px;
}

.image img {
position: relative;
left: -100px;
top: -100px;
}

<div class="image">
    <img src="http://img05.deviantart.net/c135/i/2011/134/7/0/bridge_by_kzonedd-d3gcetc.jpg" alt="photo of old wooden bridge" />
</div>

Of course, the minus 100px just to show you how to position. Play around with the values and all will become clear.

HTH. Good luck and have fun.

Upvotes: 4

Related Questions