Background Image Not Displaying On Div - html

For some reason, my website does not want to display the background-image which I have set on my div.
I want to have a featured image that display's across the whole page (kind of like on Microsoft's homepage). However, the image doesn't want to show.
I have tried disabling AdBlock and any other extensions with no avail, I have also tried to look on forums to see if I could find anything (which I haven't).
The following is my HTML:
<body>
<div class="container">
<div class="content">
<div class="featured-img-display imgdisplay" data-lazyload="undefined" data-bgfit="cover" data-bgposition="right center" data-bgrepeat="no-repeat" data-lazydone="undefined" src="/data/img/game_data/19a017f91q.jpg" data-src="/data/img/game_data/19a017f91q.jpg">
</div>
</div>
</div>
</body>
And my 'relevant' CSS:
.container {
left:15%;
width:70%;
margin:0px auto;
}
.content {
background-color: #FFF;
border: 1px solid #F2F2F2;
padding-bottom:100px;
padding:40px;
width:90%;
margin:0px auto;
padding-top:100px;
}
.featured-img-display{
width: 100%;
height: 100%;
opacity: 1;
background-image: url('/data/img/game_data/19a017f91q.jpg');
background-size: cover;
background-repeat: no-repeat;
}
Thanks
Fiddle: https://jsfiddle.net/ses3j1Ld/

Currently, the featured-img-display element has no height. That's why you don't see the background image.
height: 100%; will only set full screen height on an element if its parent actually has 100% screen height as well.
To do this using % units you'll need to make sure that all elements up to the featured-img-display element have 100% height,.. something like:
html,body,.container,.content {
height: 100%
}
Then your current CSS code will work. Sometimes however the above code isn't so viable.
Using viewport units here: height: 100vh; makes things a lot easier
Note:
If you want the image to span the full screen height (and without scroll-bars), you'll have to adjust your CSS a bit:
1) remove default margin with body { margin:0 }
2) You have set padding and a border on the parent of the element with the background image... you'll probably want to set these properties on the image element itself with box-sizing set to border-box.
Codepen demo

the height of .featured-img is percentage value for make it work the parent's height must be determined and the only exception is the root element html, which can be a percentage height.
body, html{
height: 100%;
width: 100%;
}
.container {
left:15%;
width:70%;
height: 100%;
margin:0px auto;
}
.content {
background-color: #FFF;
border: 1px solid #F2F2F2;
padding-bottom:100px;
padding:40px;
width:90%;
height: 100%;
margin:0px auto;
padding-top:100px;
}
.featured-img-display{
width: 100%;
height: 100%;
opacity: 1;
background-image: url('http://i.imgur.com/IMiabf0.jpg');
background-size: cover;
background-repeat: no-repeat;
}
<body>
<div class="container">
<div class="content">
<div class="featured-img-display imgdisplay" data-lazyload="undefined" data-bgfit="cover" data-bgposition="right center" data-bgrepeat="no-repeat" data-lazydone="undefined" src="/data/img/game_data/19a017f91q.jpg" data-src="/data/img/game_data/19a017f91q.jpg">
</div>
</div>
</div>
</body>

Instead of div, can you try with img tag as well. I think that might work

Well, all your divs .container, .content, and .featured-img-display don't have a height. height:100% means having height equal to the element's parent but since none of those elements have any height, height: 100% equates to 0px. Same goes for width.
So, one of the divs will have to have a specific height and width. Here's an example.:

Related

Centering an image element within a div

I'm following some tutorials on beginner's HTML and CSS. Im trying to center an image in a div, but when I shrink the window's width to a certain pixel, the image has less and less margin on the right. Here is the picture I took to demonstrate: https://imgur.com/Ihz0OeY. Here are the css codes:
.bg-image {
background-image: url("res/img/testbackground.jpg");
filter: blur(8px);
-webkit-filter: blur(8px);
width: 100%;
height: calc(100vh - 56px);
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
bg-text {
background-color: rgb(0,0,0);
background-color: rgba(0,0,0, 0.4);
color: white;
position: relative;
left:50%;
top:50%;
font-weight: bold;
transform: translate(-50%, -150%);
border: 3px solid #f1f1f1;
width: 80%;
padding: 20px;
text-align: center;
}
.bg-text img {
width:200px;
display: block;
margin-left: auto;
margin-right: auto;
}
I use position: relative because if I use absolute, the text wont be pushed down when the navbar expands. The HTML codes are nothing special, the nav bar I took from Bootstrap.
<div class="bg-image"></div>
<div class="bg-text">
<img id ="1" src="res/img/dog.png" alt="">
<h1>12345</h1>
<p>ABCDEF</p>
</div>
Can you guys help me? Thank you so much.
The problem is just that your img element is bigger than the screen size at a center width. Use a fluid width to solve this:
.bg-text img {
width:90%;
display: block;
margin: 0 auto;
}
A block level element always justifies left by default, which means if you don't tell the element to be contained within the window using a percentage-based width, the element will maintain its static width (in this case, 200px) even when the window shrinks beyond that number. Thus, the margin appears to shrink on the right. If you're using pixel-based widths, it's always best to declare it as a max-width, and define a percentage-based width as a fallback, like so:
.bg-text img {
width:100%;
max-width:200px;
display: block;
margin: 0 auto;
}
This means the element will be 200px wide and centered as long as the parent element is wider than 200px. If the parent element's width becomes less than 200px, the element will automatically become 100% of its parent's width.
You want this?
https://imgur.com/qkJP8pg
https://www.w3schools.com/code/tryit.asp?filename=G5P5BKV1XGGL
.bg-text img {
position: absolute;
left: 0;
right: 0;
top:0;
bottom:0;
margin: auto;
width:90%;
}
In HTML:
<img src="..." class="mx-auto d-block">
or in CSS:
.bg-text img{
margin: auto;
display-block;
}

Force responsive <img> to expand to parent <div>

for clarity, see codepen: http://codepen.io/anon/pen/QyaLPb
I want to create an image with an overlay. The overlay should be the same size as the image, however because of the width: 100% and height: auto for both the .imagecontainer and img, they don't have the exact same height. The overlay now has a few pixels more height than the img. You can see the .imagecontainer has more height than the img inside (red background showing at the bottom). I need the imagecontainer and img to be responsive, so setting a fixed height is not really an option. How do I solve this?
HTML:
<div class="wrapper">
<div class="imagecontainer">
<img src="http://www.kleinewolf.nl/uploads/fancybox/8f5b7a59-32b7-4582-868b- e2ff1f3e41a2/2835832130.jpg">
<div class="overlay">
</div>
</div>
</div>
CSS:
.wrapper{
width: 400px;
padding: 40px;
}
.imagecontainer {
width: 100%;
height: auto;
overflow: hidden;
background: red;
position: relative;
}
.imagecontainer img {
width: 100%;
height: auto;
}
.overlay {
position: absolute;
top:0;
left:0;
width: 100%;
height: 100%;
background:rgba(0,0,0,0.8);
display:none;
}
.imagecontainer:hover .overlay {
display:block;
}
If you're speaking of the red border below the image.
Add to your .imagecontainer img: display: block. That should solve the problem...
http://codepen.io/anon/pen/QyaWNE
Added line-height:0; to your container div. Images contained by parent divs usually tend to take margins from other elements, and line-height and font-size are usually a problem. Good luck!

How do i get different sized images into 100x100px divs without aspect ratio getting messed up. (with overflow hidden)

Here is a JSFiddle to show what I mean: http://jsfiddle.net/p4toy2qq/.
The Code is here:
HTML
<div class="container">
<img src="image-of-any-size.jpg" alt="alt" />
</div>
CSS
.container { width: 100px; height: 100px; overflow: hidden; border: black solid 1px; margin: 10px;}
.container img { width: 100%; }
I basically want different sized images to fill out the divs, without the aspect ratio getting messed up. The overflow should be hidden, so the parts outside get 'cropped' off.
Any ideas?
If you have the option to set them as background images you can use:
.container{
background: url('something.jpg');
background-size:cover;
background-position:center center;
}
Note that some older browsers don't support background-size: http://caniuse.com/#search=background-size
there's a method to do this.
.img-container{
position:relative;
width:100px;
height:100px;
display:block;
overflow:hidden;
text-align:center;
}
horizontal img
.img-container > img{
position:absolute;
top:0;
height:100%;
}
vertical img
.img-container > img{
position:absolute;
top:0;
width:100%;
}
demo
If you want to cover the height of the images inside the container, use background-image: auto 100% style instead of img tag and apply the image to the .container element directly.
Working Fiddle
Note: This solution is assuming that all your images have more than 100px of height as you have shown in the fiddle.
Update:
If you want to just cover the image completely inside the container then you can use background-image: cover
Working Fiddle
You could use the new object-fit property (currently webkit only)
1) Set object-fit: cover; on the image to ensure that the aspect ratio is kept, and
2) Set height: 100px to fill the box if the image is < 100px high.
FIDDLE
.container {
width: 100px;
height: 100px;
overflow: hidden;
border: black solid 1px;
margin: 10px;
}
.container img {
width: 100%;
object-fit: cover;
height: 100px;
}
<div class="container">
<img src="http://static.ddmcdn.com/gif/storymaker-best-hubble-space-telescope-images-20092-514x268.jpg" alt="alt" />
</div>
<div class="container">
<img src="http://chennaionline.com/images/gallery/2013/June/20110623010938/Singam2_Suriya_Stills_Photos_Images_10.jpg" alt="alt" />
</div>
<div class="container">
<img src="http://www.moviehdwallpapers.com/wp-content/uploads/2014/10/happy_diwali__sms_images_.jpg" alt="alt" />
</div>
You can read more about this new property in this webplatform article.
From the above article - regarding the 'cover' value:
The whole image is scaled down or expanded till it fills the box
completely, the aspect ratio is maintained. This normally results in
only part of the image being visible.
Also, here is a fiddle from the above article which demonstrates all the values of the object-fit property.

Crop div from left and right

This is my code:
<div style="width: 75px; height: 75px; text-align: center; overflow: hidden;">
<img src"myimg.png"/>
</div>
I want to crop from left and right my image in this div.
But it only crop a part from right.
I want to do something like this (which works in IE 8-10 too).
Thanks in advance!!!
You can keep your HTML as is and make the image's position:relative and the position left:-50% (or margin-left:-50%).
Your HTML:
<div id="cropper">
<img src="http://lorempixel.com/output/sports-q-c-900-600-3.jpg" />
</div>
Your CSS:
#cropper{
width:450px;
height:600px;
overflow:hidden;
}
img{
position:relative;
left:-50%;
}
Here's the demo.
EDIT
To accurately center the image in any div size, you need to position the image in pixels and not in percentage unless the container is exactly half the size of the image. So the final CSS of an image size of 900x600 pixels would be:
img{
position:relative;
left:-450px;
}
You can use clip-path to crop pretty much anything:
.crop-left {
clip-path: inset(0 50px 0 0);
}
.crop-right {
clip-path: inset(0 0 0 50px);
}
.crop-top {
clip-path: inset(0 0 50px 0);
}
.crop-bottom {
clip-path: inset(50px 0 0 0);
}
Why not set the image as background?
HTML
<div id="mydiv" style="width: 75px; height: 75px; text-align: center; overflow: hidden;">
</div>
CSS
#mydiv
{
background-image:url('myimg.png');
background-repeat:no-repeat;
background-attachment:fixed;
background-position:center;
}
Here this is s small trick to crop a div...
put the div you want to crop inside another div..
set overflow of outer div to hidden
them simply shift the inner div as you want to crop it using margin_left,right,top,down attributes...
<div style="overflow:hidden;">
<div id="myDiv" style="overflow:hidden;margin-top:-30px"></div>
</div>
Simple :)
What you want is not possible with an <img>. However, you can use the "CSS Sprite" trick:
<div style="width: 75px; height: 75px; text-align: center; overflow: hidden;
background: url(myimg.png) no-repeat center center">
</div>
No jsFiddle, sorry, as I don't have your image.
here's a solution proposed a few times here for similar questions:http://codepen.io/gcyrillus/pen/BdtEj
/* see demo : http://codepen.io/gcyrillus/pen/BdtEj , to play with and understand */
parent {
line-height:equals to height;
text-align:center;
}
parent img {
vertical-align:middle;
margin:-100%;
}
It's about clipping your image.You have that old and usefull CSS rule : clip:rect();
http://www.w3.org/wiki/CSS/Properties/clip wich has this purpose.
Or using a trick (cause you enjoy to play with CSS) to reduce virtually image zize to null, so it centers horizontally and vertically no matters it's real size.
http://codepen.io/gcyrillus/pen/BdtEj
You can just set a background image to the div
HTML
<div class='myDiv'></div>
CSS
.myDiv {
width: 75px;
height: 75px;
background: url('myimg.jpg') no-repeat -123px 0px;
}
Adjust -123px to the correct left offset from where cropping should start.
EDIT: jsFiddle
There are more possible solutions for this:
Using a container div and applying negative positioning on the image. Or you can set the image as the background of div which makes you able to use background-position for example.
Below is the DEMO link as per your requirement, which work in ie.
<div class="mainDiv">
<div class="green"></div>
</div>
.mainDiv {
margin:0 auto;
border:1px solid #000;
width:700px;
height:500px;
text-align:center;
}
.mainDiv .green {
width:100px;
height:100px;
background-color:red;
display:inline-block;
}
It's possible with image and any element, css positioning, provided that you know the width of the image.
Add position:relative to the div, and position:absolute on the image together with half the width of the image in a left:-204px;top:0;.
Example fiddle: http://jsfiddle.net/ctXcJ/2/
try margin: 0 auto; instead of text-align.

How do I auto-resize an image to fit a 'div' container?

How do you auto-resize a large image so that it will fit into a smaller width div container whilst maintaining its width:height ratio?
Example: stackoverflow.com - when an image is inserted onto the editor panel and the image is too large to fit onto the page, the image is automatically resized.
Do not apply an explicit width or height to the image tag. Instead, give it:
max-width:100%;
max-height:100%;
Also, height: auto; if you want to specify a width only.
Example: http://jsfiddle.net/xwrvxser/1/
img {
max-width: 100%;
max-height: 100%;
}
.portrait {
height: 80px;
width: 30px;
}
.landscape {
height: 30px;
width: 80px;
}
.square {
height: 75px;
width: 75px;
}
Portrait Div
<div class="portrait">
<img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>
Landscape Div
<div class="landscape">
<img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>
Square Div
<div class="square">
<img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>
It turns out there's another way to do this: object-fit.
<img style='height: 100%; width: 100%; object-fit: contain'/>
will do the work. Don't forget to include other necessary attributes like src and alt, of course.
Fiddle: http://jsfiddle.net/mbHB4/7364/
Currently there is no way to do this correctly in a deterministic way, with fixed-size images such as JPEGs or PNG files.
To resize an image proportionally, you have to set either the height or width to "100%", but not both. If you set both to "100%", your image will be stretched.
Choosing whether to do height or width depends on your image and container dimensions:
If your image and container are both "portrait shaped" or both "landscape shaped" (taller than they are wide, or wider than they are tall, respectively), then it doesn't matter which of height or width are "%100".
If your image is portrait, and your container is landscape, you must set height="100%" on the image.
If your image is landscape, and your container is portrait, you must set width="100%" on the image.
If your image is an SVG, which is a variable-sized vector image format, you can have the expansion to fit the container happen automatically.
You just have to ensure that the SVG file has none of these properties set in the <svg> tag:
height
width
viewbox
Most vector drawing programs out there will set these properties when exporting an SVG file, so you will have to manually edit your file every time you export, or write a script to do it.
Here is a solution that will both vertically and horizontally align your img within a div without any stretching even if the image supplied is too small or too big to fit in the div.
The HTML content:
<div id="myDiv">
<img alt="Client Logo" title="Client Logo" src="Imagelocation" />
</div>
The CSS content:
#myDiv
{
height: 104px;
width: 140px;
}
#myDiv img
{
max-width: 100%;
max-height: 100%;
margin: auto;
display: block;
}
The jQuery part:
var logoHeight = $('#myDiv img').height();
if (logoHeight < 104) {
var margintop = (104 - logoHeight) / 2;
$('#myDiv img').css('margin-top', margintop);
}
You have two ways of making the image responsive.
When an image is a background image.
#container{
width: 300px;
height: 300px;
background-image: url(https://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg);
background-size: cover;
background-repeat: no-repeat;
background-position: center;
}
<div id="container"><div>
Run it here
But one should use img tag to put images as it is better than background-image in terms of SEO as you can write keyword in the alt of the img tag. So here is you can make the image responsive.
When image is in img tag.
#container{
max-width: 400px;
overflow: hidden;
}
img{
width: 100%;
object-fit: contain;
}
<div id="container">
<img src="https://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg" alt="your_keyword"/>
<div>
Run it here
Make it simple!
Give the container a fixed height and then for the img tag inside it, set width and max-height.
<div style="height: 250px">
<img src="..." alt=" " style="width: 100%;max-height: 100%" />
</div>
The difference is that you set the width to be 100%, not the max-width.
You can set the image as the background to a div, and then use the CSS background-size property:
background-size: cover;
It will "Scale the background image to be as large as possible so that the background area is completely covered by the background image. Some parts of the background image may not be in view within the background positioning area" -- W3Schools
Check out my solution: http://codepen.io/petethepig/pen/dvFsA
It's written in pure CSS, without any JavaScript code.
It can handle images of any size and any orientation.
Given such HTML:
<div class="image">
<div class="trick"></div>
<img src="http://placekitten.com/415/200"/>
</div>
the CSS code would be:
.image {
font-size: 0;
text-align: center;
width: 200px; /* Container's dimensions */
height: 150px;
}
img {
display: inline-block;
vertical-align: middle;
max-height: 100%;
max-width: 100%;
}
.trick {
display: inline-block;
vertical-align: middle;
height: 150px;
}
There are several ways to fit the image to <div>.
img {
object-fit: cover;
}
The CSS object-fit property is used to specify how an <img> or <video> should be resized to fit its container.
This property tells the content to fill the container in a variety of ways; such as "preserve that aspect ratio" or "stretch up and take up as much space as possible".
fill - This is default. The image is resized to fill the given dimension. If necessary, the image will be stretched or squished to fit
contain - The image keeps its aspect ratio, but is resized to fit within the given dimension
cover - The image keeps its aspect ratio and fills the given dimension. The image will be clipped to fit
none - The image is not resized
scale-down - the image is scaled down to the smallest version of none or contain
You can find out more working samples here.
I have much better solution without need of any JavaScript. It is fully responsive, and I use it a lot. You often need to fit an image of any aspect ratio to a container element with a specified aspect ratio. And having whole this thing fully responsive is a must.
/* For this demo only */
.container {
max-width: 300px;
margin: 0 auto;
}
.img-frame {
box-shadow: 3px 3px 6px rgba(0, 0, 0, .15);
background: #ee0;
margin: 20px auto;
}
/* This is for responsive container with specified aspect ratio */
.aspect-ratio {
position: relative;
}
.aspect-ratio-1-1 {
padding-bottom: 100%;
}
.aspect-ratio-4-3 {
padding-bottom: 75%;
}
.aspect-ratio-16-9 {
padding-bottom: 56.25%;
}
/* This is the key part - position and fit the image to the container */
.fit-img {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
max-width: 80%;
max-height: 90%
}
.fit-img-bottom {
top: auto;
}
.fit-img-tight {
max-width: 100%;
max-height: 100%
}
<div class="container">
<div class="aspect-ratio aspect-ratio-1-1 img-frame">
<img src="https://via.placeholder.com/400x300" class="fit-img" alt="sample">
</div>
<div class="aspect-ratio aspect-ratio-4-3 img-frame">
<img src="https://via.placeholder.com/400x300" class="fit-img fit-img-tight" alt="sample">
</div>
<div class="aspect-ratio aspect-ratio-16-9 img-frame">
<img src="https://via.placeholder.com/400x400" class="fit-img" alt="sample">
</div>
<div class="aspect-ratio aspect-ratio-16-9 img-frame">
<img src="https://via.placeholder.com/300x400" class="fit-img fit-img-bottom" alt="sample">
</div>
</div>
You can set max-width and max height independently; the image will respect the smallest one (depending on the values and aspect ratio of the image). You can also set image to be aligned as you want (for example, for a product picture on an infinite white background you can position it to center bottom easily).
This solution doesn't stretch the image and fills the whole container, but it cuts some of the image.
HTML:
<div><img src="/images/image.png"></div>
CSS:
div {
width: 100%;
height: 10em;
overflow: hidden;
img {
min-width: 100%;
min-height: 100%;
}
I just published a jQuery plugin that does exactly what you need with a lot of options:
https://github.com/GestiXi/image-scale
Usage:
HTML
<div class="image-container">
<img class="scale" data-scale="best-fit-down" data-align="center" src="img/example.jpg">
</div>
JavaScript
$(function() {
$("img.scale").imageScale();
});
I see that many people have suggested object-fit which is a good option. But if you want it to work in older browsers as well, there is another way of doing it easily.
It's quite simple. The approach I took was to position the image inside the container with absolute and then place it right at the centre using the combination:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
Once it is in the centre, I give to the image,
// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;
// For horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;
This makes the image get the effect of object-fit:cover.
Here is a demonstration of the above logic.
https://jsfiddle.net/furqan_694/s3xLe1gp/
This logic works in all browsers.
The following works perfectly for me:
img{
height: 99999px;
object-fit:contain;
max-height: 100%;
max-width: 100%;
display: block;
margin: auto auto;
}
I fixed this problem using the following code:
<div class="container"><img src="image_url" /></div>
.container {
height: 75px;
width: 75px;
}
.container img {
object-fit: cover;
object-position: top;
display: block;
height: 100%;
width: 100%;
}
A simple solution is to use Flexbox. Define the container's CSS to:
.container{
display: flex;
justify-content: center;
align-items: center;
align-content: center;
overflow: hidden;
/* Any custom height */
}
Adjust the contained image width to 100% and you should get a nice centered image in the container with the dimensions preserved.
<style type="text/css">
#container{
text-align: center;
width: 100%;
height: 200px; /* Set height */
margin: 0px;
padding: 0px;
background-image: url('../assets/images/img.jpg');
background-size: content; /* Scaling down large image to a div */
background-repeat: no-repeat;
background-position: center;
}
</style>
<div id="container>
<!-- Inside container -->
</div>
As answered here, you can also use vh units instead of max-height: 100% if it doesn't work on your browser (like Chrome):
img {
max-height: 75vh;
}
I centered and scaled proportionally an image inside a hyperlink both horizontally and vertically this way:
#link {
border: 1px solid blue;
display: table-cell;
height: 100px;
vertical-align: middle;
width: 100px;
}
#link img {
border: 1px solid red;
display: block;
margin-left: auto;
margin-right: auto;
max-height: 60px;
max-width: 60px;
}
It was tested in Internet Explorer, Firefox, and Safari.
More information about centering is here.
Give the height and width you need for your image to the div that contains the <img> tag. Don't forget to give the height/width in the proper style tag.
In the <img> tag, give the max-height and max-width as 100%.
<div style="height:750px; width:700px;">
<img alt="That Image" style="max-height:100%; max-width:100%;" src="">
</div>
You can add the details in the appropriate classes after you get it right.
The code below is adapted from previous answers and is tested by me using an image called storm.jpg.
This is the complete HTML code for a simple page that displays the image. This works perfect and was tested by me with www.resizemybrowser.com. Put the CSS code at the top of your HTML code, underneath your head section. Put the picture code wherever you want the picture.
<html>
<head>
<style type="text/css">
#myDiv
{
height: auto;
width: auto;
}
#myDiv img
{
max-width: 100%;
max-height: 100%;
margin: auto;
display: block;
}
</style>
</head>
<body>
<div id="myDiv">
<img src="images/storm.jpg">
</div>
</body>
</html>
You have to tell the browser the height of where you are placing it:
.example {
height: 220px; /* DEFINE HEIGHT */
background: url('../img/example.png');
background-size: 100% 100%;
background-repeat: no-repeat;
}
Edit: Previous table-based image positioning had issues in Internet Explorer 11 (max-height doesn't work in display:table elements). I've replaced it with inline based positioning which not only works fine in both Internet Explorer 7 and Internet Explorer 11, but it also requires less code.
Here is my take on the subject. It'll only work if the container has a specified size (max-width and max-height don't seem to get along with containers that don't have concrete size), but I wrote the CSS content in a way that allows it to be reused (add picture-frame class and px125 size class to your existing container).
In CSS:
.picture-frame
{
vertical-align: top;
display: inline-block;
text-align: center;
}
.picture-frame.px125
{
width: 125px;
height: 125px;
line-height: 125px;
}
.picture-frame img
{
margin-top: -4px; /* Inline images have a slight offset for some reason when positioned using vertical-align */
max-width: 100%;
max-height: 100%;
display: inline-block;
vertical-align: middle;
border: 0; /* Remove border on images enclosed in anchors in Internet Explorer */
}
And in HTML:
<a href="#" class="picture-frame px125">
<img src="http://i.imgur.com/lesa2wS.png"/>
</a>
DEMO
/* Main style */
.picture-frame
{
vertical-align: top;
display: inline-block;
text-align: center;
}
.picture-frame.px32
{
width: 32px;
height: 32px;
line-height: 32px;
}
.picture-frame.px125
{
width: 125px;
height: 125px;
line-height: 125px;
}
.picture-frame img
{
margin-top: -4px; /* Inline images have a slight offset for some reason when positioned using vertical-align */
max-width: 100%;
max-height: 100%;
display: inline-block;
vertical-align: middle;
border: 0; /* Remove border on images enclosed in anchors in Internet Explorer */
}
/* Extras */
.picture-frame
{
padding: 5px;
}
.frame
{
border:1px solid black;
}
<p>32px</p>
<a href="#" class="picture-frame px32 frame">
<img src="http://i.imgur.com/lesa2wS.png"/>
</a>
<a href="#" class="picture-frame px32 frame">
<img src="http://i.imgur.com/kFMJxdZ.png"/>
</a>
<a href="#" class="picture-frame px32 frame">
<img src="http://i.imgur.com/BDabZj0.png"/>
</a>
<p>125px</p>
<a href="#" class="picture-frame px125 frame">
<img src="http://i.imgur.com/lesa2wS.png"/>
</a>
<a href="#" class="picture-frame px125 frame">
<img src="http://i.imgur.com/kFMJxdZ.png"/>
</a>
<a href="#" class="picture-frame px125 frame">
<img src="http://i.imgur.com/BDabZj0.png"/>
</a>
Edit: Possible further improvement using JavaScript (upscaling images):
function fixImage(img)
{
var $this = $(img);
var parent = $this.closest('.picture-frame');
if ($this.width() == parent.width() || $this.height() == parent.height())
return;
if ($this.width() > $this.height())
$this.css('width', parent.width() + 'px');
else
$this.css('height', parent.height() + 'px');
}
$('.picture-frame img:visible').each(function
{
if (this.complete)
fixImage(this);
else
this.onload = function(){ fixImage(this) };
});
The accepted answer from Thorn007 doesn't work when the image is too small.
To solve this, I added a scale factor. This way, it makes the image bigger and it fills the div container.
Example:
<div style="width:400px; height:200px;">
<img src="pix.jpg" style="max-width:100px; height:50px; transform:scale(4); transform-origin:left top;" />
</div>
Notes:
For WebKit you must add -webkit-transform:scale(4); -webkit-transform-origin:left top; in the style.
With a scale factor of 4, you have max-width = 400/4 = 100 and max-height = 200/4 = 50
An alternate solution is to set max-width and max-height at 25%. It's even simpler.
A simple solution (4-step fix!!) that seems to work for me, is below. The example uses the width to determine the overall size, but you can also flip it to use the height instead.
Apply CSS styling to the image container (for example, <img>)
Set the width property to the dimension you want
For dimensions, use % for relative size, or autoscaling (based on image container or display)
Use px (or other) for a static, or set dimension
Set the height property to automatically adjust, based on the width
ENJOY!
For example,
<img style="width:100%; height:auto;"
src="https://googledrive.com/host/0BwDx0R31u6sYY1hPWnZrencxb1k/thanksgiving.png"
/>
All the provided answers, including the accepted one, work only under the assumption that the div wrapper is of a fixed size. So this is how to do it whatever the size of the div wrapper is and this is very useful if you develop a responsive page:
Write these declarations inside your DIV selector:
width: 8.33% /* Or whatever percentage you want your div to take */
max-height: anyValueYouWant /* (In px or %) */
Then put these declarations inside your IMG selector:
width: "100%" /* Obligatory */
max-height: anyValueYouWant /* (In px or %) */
VERY IMPORTANT:
The value of maxHeight must be the same for both the DIV and IMG selectors.
The simplest way to do this is by using object-fit:
<div class="container">
<img src="path/to/image.jpg">
</div>
.container{
height: 300px;
}
.container img{
height: 100%;
width: 100%;
object-fit: cover;
}
If you're using Bootstrap, just add the img-responsive class and change to
.container img{
object-fit: cover;
}
If you're using Bootstrap, you just need to add the img-responsive class to the img tag:
<img class="img-responsive" src="img_chania.jpg" alt="Chania">
Bootstrap Images
As seen in my 2014 Codepen example, I've made a solution that would work for any unknown combination of width/height (aspect-ratio) with the help of a as little javascript as possible, to change the CSS of how the image is centered when the aspect-ratio of the container changes above/below the aspect ratio of the image:
Try resizing the container by dragging the bottom right corner:
// Detects when the window width is too narrow for the current image
// aspect-ratio, and fits it to height 100% instead of width 100%.
const photo = document.images[0]
const onPhotoResize = new ResizeObserver(entries =>
window.requestAnimationFrame(checkRatio)
)
onPhotoResize.observe(photo.parentNode)
function checkRatio(){
const photoParent = photo.parentNode,
imageAspectRatio = photo.clientWidth / photo.clientHeight,
parentAspectRatio = photoParent.clientWidth / photoParent.clientHeight
photo.classList[imageAspectRatio > parentAspectRatio ? 'add':'remove']('max')
}
.box{
width: 20%;
height: 60%;
margin: auto;
position: absolute;
top:0; left:0; right:0; bottom:0;
resize: both;
overflow: hidden;
border: 5px solid red;
}
.box > img{
position: absolute;
top: 50%;
left: 50%;
width: 100%;
transform: translate(-50%, -50%);
}
.box > img.max{ width:auto; height:100%; }
<div class='box'>
<img src="https://upload.wikimedia.org/wikipedia/commons/6/6a/Mona_Lisa.jpg">
</div>
The solution is easy with a bit of maths...
Just put the image in a div and then in the HTML file where you specify the image. Set the width and height values in percentages using the pixel values of the image to calculate the exact ratio of width to height.
For example, say you have an image that has a width of 200 pixels and a height of 160 pixels. You can safely say that the width value will be 100%, because it is the larger value. To then calculate the height value you simply divide the height by the width which gives the percentage value of 80%. In the code it will look something like this...
<div class="image_holder_div">
<img src="some_pic.png" width="100%" height="80%">
</div>