Can I overlap exactly half of an image with another using CSS? - javascript

I am trying to overlap exactly half an image in CSS using another image. Thing is I want the height of the images to be say (x=200px). The width of the image will wary depending on the aspect ratio of the image. Can I still write CSS that will overlap exactly half of the resized image with another image.
Following is a code where I have played around with the position of the overlapping image. Can I let CSS do this for me somehow? Or is there some js that can help? In the following code I want the height to be unchanged, but half of any image used should be overlapped widthwise.
<html>
<head>
<style type="text/css">
#collage-container{
width:300px;
height: 200px;
position: relative;
background:#f22;
}
#collage-one, #collage-two{
height:200px;
position:absolute;
}
#collage-one{
z-index:1;
left:100px;
position:absolute;
}
</style>
</head>
<body>
<div id=collage-container>
<img src="http://www.hack4fun.org/h4f/sites/default/files/bindump/lena.bmp" id=collage-one />
<img src="http://www.hack4fun.org/h4f/sites/default/files/bindump/lena.bmp" id=collage-two />
</div>
</body>
</html>

Since the width of images is vary, you could use CSS transform translate() expression with a percentage value to move images to a side with the respect to their width value:
EXAMPLE HERE
#collage-container {
height: 200px;
position: relative;
}
#collage-container img {
height: 100%; /* As tall as the container */
width: auto;
float: left;
}
#collage-container img + img { /* Move the second image 50% of its width */
transform: translateX(-50%); /* to the left */
}
It's worth noting that CSS transforms are supported in IE9+

I think, it is simple:
<html>
<head>
<style type=text/css>
.container {
float:left;
}
.half-img {
display:inline-block;
width:25%;
}
.clear {clear:left;}
</style>
</head>
<body>
<div class="container">
<span class="half-img">
<img src="http://www.hack4fun.org/h4f/sites/default/files/bindump/lena.bmp" width="100">
</span><img src="http://www.hack4fun.org/h4f/sites/default/files/bindump/lena.bmp" width="100">
</div>
<div class="clear"></div>
</body>
</html>

Related

crop GIF images without loosing animation using javascript [duplicate]

I want to show an image from an URL with a certain width and height even if it has a different size ratio.
So I want to resize (maintaining the ratio) and then cut the image to the size I want.
I can resize with html img property and I can cut with background-image.
How can I do both?
Example:
This image:
Has the size 800x600 pixels and I want to show like an image of 200x100 pixels
With img I can resize the image 200x150px:
<img
style="width: 200px; height: 150px;"
src="http://i.stack.imgur.com/wPh0S.jpg">
That gives me this:
<img style="width: 200px; height: 150px;" src="https://i.stack.imgur.com/wPh0S.jpg">
And with background-image I can cut the image 200x100 pixels.
<div
style="background-image:
url('https://i.stack.imgur.com/wPh0S.jpg');
width:200px;
height:100px;
background-position:center;"> </div>
Gives me:
<div style="background-image:url('https://i.stack.imgur.com/wPh0S.jpg'); width:200px; height:100px; background-position:center;"> </div>
How can I do both?
Resize the image and then cut it the size I want?
You could use a combination of both methods eg.
.crop {
width: 200px;
height: 150px;
overflow: hidden;
}
.crop img {
width: 400px;
height: 300px;
margin: -75px 0 0 -100px;
}
<div class="crop">
<img src="https://i.stack.imgur.com/wPh0S.jpg" alt="Donald Duck">
</div>
You can use negative margin to move the image around within the <div/>.
With CSS3 it's possible to change the size of a background-image with background-size, fulfilling both goals at once.
There are a bunch of examples on css3.info.
Implemented based on your example, using donald_duck_4.jpg. In this case, background-size: cover; is just what you want - it fits the background-image to cover the entire area of the containing <div> and clips the excess (depending on the ratio).
.with-bg-size {
background-image: url('https://i.stack.imgur.com/wPh0S.jpg');
width: 200px;
height: 100px;
background-position: center;
/* Make the background image cover the area of the <div>, and clip the excess */
background-size: cover;
}
<div class="with-bg-size">Donald Duck!</div>
css3 background-image background-size
Did you try to use this?
.centered-and-cropped { object-fit: cover }
I needed to resize image, center (both vertically and horizontally) and than crop it.
I was happy to find, that it could be done in a single css-line.
Check the example here: http://codepen.io/chrisnager/pen/azWWgr/?editors=110
Here is the CSS and HTMLcode from that example:
.centered-and-cropped { object-fit: cover }
<h1>original</h1>
<img height="200" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="Bear">
<h1>object-fit: cover</h1>
<img class="centered-and-cropped" width="200" height="200"
style="border-radius:50%" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="Bear">
.imgContainer {
overflow: hidden;
width: 200px;
height: 100px;
}
.imgContainer img {
width: 200px;
height: 120px;
}
<div class="imgContainer">
<img src="imageSrc" />
</div>
The containing div with essentially crop the image by hiding the overflow.
img {
position: absolute;
clip: rect(0px, 140px, 140px, 0px);
}
<img src="w3css.gif" width="100" height="140" />
Thanks sanchothefat.
I have an improvement to your answer. As crop is very tailored for every image, this definitions should be at the HTML instead of CSS.
<div style="overflow:hidden;">
<img src="img.jpg" alt="" style="margin:-30% 0px -10% 0px;" />
</div>
object-fit may help you, if you're playing with <img> tag
The below code will crop your image for you. You can play around with object-fit
img {
object-fit: cover;
width: 300px;
height: 337px;
}
A small addition to the previous answers that includes object-fit: cover:
object-position
You can alter the alignment of the replaced element's content object within the element's box using the object-position property.
.trimmed-cover {
object-fit: cover;
width: 100%;
height: 177px;
object-position: center 40%;
}
<img class="trimmed-cover" src="http://i.stack.imgur.com/wPh0S.jpg">
img {
position: absolute;
clip: rect(0px,60px,200px,0px);
}
Try using the clip-path property:
The clip-path property lets you clip an element to a basic shape or to
an SVG source.
Note: The clip-path property will replace the deprecated clip
property.
img {
width: 150px;
clip-path: inset(30px 35px);
}
<img src="http://i.stack.imgur.com/wPh0S.jpg">
More examples here.
Live Example:
https://jsfiddle.net/de4Lt57z/
HTML:
<div class="crop">
<img src="example.jpg" alt="..." />
</div>
CSS:
.crop img{
width:400px;
height:300px;
position: absolute;
clip: rect(0px,200px, 150px, 0px);
}
Explanation:
Here image is resized by width and height value of the image. And crop is done by clip property.
For details about clip property follow:
http://tympanus.net/codrops/2013/01/16/understanding-the-css-clip-property/
In the crop class, place the image size that you want to appear:
.crop {
width: 282px;
height: 282px;
overflow: hidden;
}
.crop span.img {
background-position: center;
background-size: cover;
height: 282px;
display: block;
}
The html will look like:
<div class="crop">
<span class="img" style="background-image:url('http://url.to.image/image.jpg');"></span>
</div>
<p class="crop"><a href="http://templatica.com" title="Css Templates">
<img src="img.jpg" alt="css template" /></a></p>
.crop {
float: left;
margin: .5em 10px .5em 0;
overflow: hidden; /* this is important */
position: relative; /* this is important too */
border: 1px solid #ccc;
width: 150px;
height: 90px;
}
.crop img {
position: absolute;
top: -20px;
left: -55px;
}
There are services like Filestack that will do this for you.
They take your image url and allow you to resize it using url parameters. It is pretty easy.
Your image would look like this after resizing to 200x100 but keeping the aspect ratio
The whole url looks like this
https://process.filestackapi.com/AhTgLagciQByzXpFGRI0Az/resize=width:200/crop=d:[0,25,200,100]/https://i.stack.imgur.com/wPh0S.jpg
but the important part is just
resize=width:200/crop=d:[0,25,200,100]
You can put the img tag in a div tag and do both, but I would recommend against scaling images in the browser. It does a lousy job most of the time because browsers have very simplistic scaling algorithms. Better to do your scaling in Photoshop or ImageMagick first, then serve it up to the client nice and pretty.
What I've done is to create a server side script that will resize and crop a picture on the server end so it'll send less data across the interweb.
It's fairly trivial, but if anyone is interested, I can dig up and post the code (asp.net)
<div class="crop">
<img src="image.jpg"/>
</div>
.crop {
width: 200px;
height: 150px;
overflow: hidden;
}
.crop img {
width: 100%;
/*Here you can use margins for accurate positioning of cropped image*/
}
If you are using Bootstrap, try using { background-size: cover;
} for the <div> maybe give the div a class say <div class="example" style=url('../your_image.jpeg');> so it becomes
div.example{
background-size: cover}
I needed to do this recently. I wanted to make a thumbnail-link to a NOAA graph. Since their graph could change at any time, I wanted my thumbnail to change with it. But there's a problem with their graph: it has a huge white border at the top, so if you just scale it to make the thumbnail you end up with extraneous whitespace in the document.
Here's how I solved it:
http://sealevel.info/example_css_scale_and_crop.html
First I needed to do a little bit of arithmetic. The original image from NOAA is 960 × 720 pixels, but the top seventy pixels are a superfluous white border area. I needed a 348 × 172 thumbnail, without the extra border area at the top. That means the desired part of the original image is 720 - 70 = 650 pixels high. I needed to scale that down to 172 pixels, i.e., 172 / 650 = 26.5%. That meant 26.5% of 70 = 19 rows of pixels needed to be deleted from the top of the scaled image.
So…
Set the height = 172 + 19 = 191 pixels:
height=191
Set the bottom margin to -19 pixels (shortening the image to 172 pixels high):
margin-bottom:-19px
Set the top position to -19 pixels (shifting the image up, so that the top 19 pixel rows overflow & are hidden instead of the bottom ones):
top:-19px
The resulting HTML looks like this:
<a href="…" style="display:inline-block;overflow:hidden">
<img width=348 height=191 alt=""
style="border:0;position:relative;margin-bottom:-19px;top:-19px"
src="…"></a>
As you can see, I chose to style the containing <a> tag, but you could style a <div>, instead.
One artifact of this approach is that if you show the borders, the top border will be missing. Since I use border=0 anyhow, that wasn't an issue for me.
You can use Kodem's Image Resize Service. You can resize any image with just a http call. Can be used casually in the browser or used in your production app.
Upload the image somewhere you prefer (S3, imgur etc.)
Plug it into your dedicated API url (from our dashboard)
You can also use a tool called Croppie that can crop images...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link href="https://foliotek.github.io/Croppie/croppie.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script>
<script src="https://foliotek.github.io/Croppie/croppie.js"> </script>
<script src="https://foliotek.github.io/Croppie/bower_components/exif-js/exif.js"> </script>
<style>
#page {
background: #ffffff;
padding: 20px;
margin: 20px;
}
#demo-basic {
width: 600px;
height: 600px;
}
</style>
</head>
<body>
<h1>Crop Image Demo</h1>
<input id="upload" type="file" />
<br />
<div id="page">
<div id="demo-basic"></div>
</div>
<input id="upload-result" type="button" value="Crop Image"/>
<br />
<img id="cropped-result" src=""/>
<script>
var $uploadCrop;
$("#upload").on("change", function () { readFile(this); show(); });
$("#upload-result").on("click", function (ev) {
$uploadCrop.croppie("result", {
type: "canvas",
size: "viewport"
}).then(function (resp) {
$("#cropped-result").attr("src", resp);
});
});
function show() {
$uploadCrop = $("#demo-basic").croppie({
viewport: { width: 100, height: 100 },
boundary: { width: 300, height: 300 },
enableResize: true,
enableOrientation: true,
mouseWheelZoom: 'ctrl',
enableExif: true
});
}
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$("#demo-basic").addClass("ready");
$uploadCrop.croppie("bind", {
url: e.target.result
}).then(function () {
console.log("jQuery bind complete");
});
}
reader.readAsDataURL(input.files[0]);
}
else {
alert("Sorry - you're browser doesn't support the FileReader API");
}
}
</script>
</body>
</html>

adding an jpg image in the css in a javascript game

I currently have the beginning's of a flappy bird game and the css generates a small red ball. I want to replace the ball with a jpg image taken from the internet, which I can also style and control/animate from the css, as I would do with the ball.
Image source: "https://img1.pnghut.com/16/12/25/KjSdhUe19q/logo-app-store-smiley-smile-score.jpg"
I've tried various things to put it in the CSS and in the HTML, but do not fully understand how it all ties together.
If I add the image (as I have done) in the html, can I not style it using the CSS?
For now, I want to:
Render the image on the screen (as I have done)
Style it to the same specs as the red ball (e.g. 20 x 20 etc, with starting positions, positioning etc)
Currently the TOP POSITION in the CSS seems to work (when applied to the image) but not the width and height. I had to hard code the width and the height of the image in to the HTML.
Any explanations as to best practices and a solution please.
Full current code here:
https://repl.it/#iamapersonthing/flappybirds
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>FlappyBird</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="game">
<div id="block"></div>
<div id="hole"></div>
<div id="character">
<img src="https://img1.pnghut.com/16/12/25/KjSdhUe19q/logo-app-store-smiley-smile-score.jpg">
</div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS
*{
padding:0;
margin:0;
}
#game{
width:400px;
height:500px;
border: 1px solid greenyellow;
margin:auto;
overflow:hidden;
}
#block{
width:50px;
height:500px;
background-color:greenyellow;
position: relative;
left:400px;
animation:block 2s infinite linear;
}
#keyframes block{
0%{left:400px}
100%{left:-50px}
}
#hole{
width:50px;
height:150px;
background-color:red;
position: relative;
left:400px;
top:-500px;
animation:block 2s infinite linear;
}
#character{
width:20px;
height:20px;
background-color:red;
position: absolute;
top:100px;
border-radius:50%;
}
JavaScript
var block = document.getElementById("block");
var hole = document.getElementById("hole");
hole.addEventListener('animationiteration',() => {
var random = -((Math.random()*300)+150);
hole.style.top=random +"px";
});
You have to add you style to the img tag. You'll have to add a display:block as well otherwise, the image will not take the width and height you specified.
#character img{
width:20px;
height:20px;
background-color:red;
position: absolute;
top:100px;
border-radius:50%;
}
If you want a guide on how to select your components and which one is stronger, you can read that CSS Batman guide : http://batificity.com/
For your problem, you can also use an object-fit. Like so :
var block = document.getElementById("block");
var hole = document.getElementById("hole");
hole.addEventListener('animationiteration',() => {
var random = -((Math.random()*300)+150);
hole.style.top=random +"px";
});
*{
padding:0;
margin:0;
}
#game{
width:400px;
height:500px;
border: 1px solid greenyellow;
margin:auto;
overflow:hidden;
}
#block{
width:50px;
height:500px;
background-color:greenyellow;
position: relative;
left:400px;
animation:block 2s infinite linear;
}
#keyframes block{
0%{left:400px}
100%{left:-50px}
}
#hole{
width:50px;
height:150px;
background-color:red;
position: relative;
left:400px;
top:-500px;
animation:block 2s infinite linear;
}
#character{
display:block;
width:20px;
height:20px;
background-color:red;
position: absolute;
top:100px;
border-radius:50%;
}
#character img{
width: 100%;
height: 100%;
object-fit: cover;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>FlappyBird</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="game">
<div id="block"></div>
<div id="hole"></div>
<div id="character">
<img src="https://img1.pnghut.com/16/12/25/KjSdhUe19q/logo-app-store-smiley-smile-score.jpg">
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Full object-fit specification here : https://developer.mozilla.org/fr/docs/Web/CSS/object-fit
You have many ways to possibly solve your issue. The best way in my opinion is to not use a IMG object at all and instead use a DIV that changes its background properties. This allows you to use a sprite sheet more easily because you can set the offsets for x and y in a background image. This also allows you to more easily change the image being used by changing the background-image property.
Alternatively, you can continue using IMG objects and just unload that HTML and replace it with a new IMG object with a different src parameter. JQuery makes this a lot easier to manage in my experience, but it can be done fairly easily using straight JS as well. Here's how I'd do this in JQuery (because I simply remember this syntax better):
$('#character').html('<img src="new image address">');
As far as editing the width/height, it comes down to just manually setting the offset afterwards and leaving the width/height alone (assuming you aren't already forcing dimensions onto the image) or for manual placement/positioning, just manually setting the width/height every time you replace the image.

Is there a way to auto add gradient to images?

Here is my code:
<div class='my-posts-container' id='<%=postobj._id%>'>
<%var menuid='menu'+postobj._id%>
<%var imagesource='../'+postobj.blob.path%>
<div class="my-posts-container-header">
<%-include('postheader.ejs',{friend:postobj.username,postid:postobj._id});%>
</div>
<div class="menu hide" id="<%=menuid%>" >
<ul >
<li><button onclick="viewpost('<%=postobj._id%>')" >view</button></li>
<li><button onclick="removepost('<%=postobj._id%>')" >remove</button></li>
<!-- <li><button onclick="copypostlink('<%=postobj._id%>')" >copy link</button></li>
<li><button onclick="editthispost('<%=postobj._id%>')" >edit</button></li> -->
</ul>
</div>
<div class="post-image" >
<img src="<%=imagesource%>" alt="image" height="400px" width="400px" style="margin: 5px;object-fit: contain;" ondblclick="like('<%=postobj._id%>')">
</div>
<span>
<%-include('likecommentsharesave.ejs',{postid:postobj._id,username:username,likes:postobj.likes})%>
</span>
<hr>
<div class="caption">
<%=postobj.caption%>
</div>
I want to keep my image size as 400px *400px
but add a background colour .post_image div,
basically, I want to add a gradient to the background based on any image in the image tag, something like this,
so that the whole 400 X 400 size is covered is this possible to achieve, if not can you suggest me other options, Thanks.
You can achieve something similar with CSS
Considering using this stylesheet
<style type="text/css">
.blured {
width:320px;
height:320px;
position: relative;
overflow: hidden;
}
.blured .blur {
height:70px;
width:100%;
position:absolute;
filter: blur(7px);
}
.blured .top {
top:0px;
background: linear-gradient(#000000d9, #00000000)
}
.blured .bottom {
bottom:0px;
background: linear-gradient(#00000000, #000000d9)
}
</style>
Then use the following markup
<div class='blured' style='background-image:url("http://placekitten.com/320/320")'>
<div class='blur top'></div>
<div class='blur bottom'></div>
</div>
The result will be something like this:
You can experiment with linear-gradient colors and the value for blur() to achieve an output close to your requirement.
References:
filter:blur()
background: linear-gradient
The effect you describe can actually be achieved. You just need to stack the same image with a smaller size on top of the image. The image underneath can then be blurred out and it will span the remainder of the 400px x 400px area.
To do this, you need to set the position field of the enclosing div to relative and that of both the images to absolute. I have reduced the height of the image sitting on top to 200px and kept the image width the same as the image underneath to resemble the style of the image in the question. Use filter: blur() to blur out the larger image.
Blurring softens the edges of the image (Remove the clip property and you'll know). Use the clip property to make the edges look "crisp".
I have used this image.
Run the code snippet below to see it in action:
<!DOCTYPE html>
<html>
<style>
*{box-sizing: border-box;}
.container {
margin: auto;
position: relative;
width: 50%;
}
.outer {
filter: blur(5px);
position: absolute;
z-index: -1;
clip: rect(0,400px,400px,0);
}
.inner {
position: absolute;
top: 100px;
}
</style>
<div class="container">
<img src="https://i.stack.imgur.com/Y1ELT.jpg" class="outer" height="400px" width="400px">
<img src="https://i.stack.imgur.com/Y1ELT.jpg" class="inner" height="200px" width="400px">
</div>
</html>
This answers part of your question. Now, to automate the image placement as per size, you can retrieve and update the image dimensions using JavaScript:
var image = new Image();
image.onload = function() {
var height = image.height;
var width = image.width;
}
image.src = "<source>";
The image underneath will always be 400 x 400 px, you can update the attributes of the image on the top as per its actual retrieved dimensions if it is smaller than 400 x 400 px. Otherwise, squash it down to 400 x 400 px to cover the entire image underneath.

Dynamic equal height responsive image gallery

I need to display thumbnails of various images of different sizes. I wanna display them in equal height and width of responsive divs. But the problem is the images are of different sizes. I have also tried jquery but couldn't reach to a solution.
HTML Code:
<div class="gallery">
<div class="pic">
<img src="http://img.autobytel.com/car-reviews/autobytel/11827-cool-luxury-cars/2015-Tesla-Model-S-90D-black-profile-in-front-of-modern-house.jpg">
</div>
<div class="pic">
<img src="https://imgct2.aeplcdn.com/img/800x600/news/Nissan_XTrail_2015/nissan-x-trail-1.jpg">
</div>
<div class="pic">
<img src="http://media.caranddriver.com/images/14q3/612034/best-sports-cars-2015-editors-choice-for-premium-and-exotic-sports-cars-car-and-driver-photo-634605-s-450x274.jpg">
</div>
</div>
CSS:
.gallery{
max-width:800px;
overflow:hidden;
width:100%;
}
.gallery .pic{
width:33%;
float:left;
max-height:200px;
height:100%;
}
.gallery img{
height:100%;
width:100%;
}
Jquery
var maxHeight = 0;
$('.gallery .pic').each(function(index){
if ($(this).height() > maxHeight)
{
maxHeight = $(this).height();
}
});
$('.gallery .pic').height(maxHeight);
Fiddle: https://jsfiddle.net/1rooxnko/
Note: I am looking for a solution that is without fixed height to pic class.
try this updated responsive code may be it can help you
JSfiddle
HTML:
<div class="gallary">
<div class="pic">
<img src="http://img.autobytel.com/car-reviews/autobytel/11827-cool-luxury-cars/2015-Tesla-Model-S-90D-black-profile-in-front-of-modern-house.jpg">
</div>
<div class="pic">
<img src="https://imgct2.aeplcdn.com/img/800x600/news/Nissan_XTrail_2015/nissan-x-trail-1.jpg">
</div>
<div class="pic">
<img src="http://media.caranddriver.com/images/14q3/612034/best-sports-cars-2015-editors-choice-for-premium-and-exotic-sports-cars-car-and-driver-photo-634605-s-450x274.jpg">
</div>
</div>
CSS:
.gallary{
width:100%;
overflow:hidden;
display:flex;
}
.pic{
width:33.33%;
}
.gallary img{
width:100%;
height:100%;
}
The problem I could find was in your .gallery element, you've set the max-height, but you also need to specify height too.
have a look at this https://jsfiddle.net/ya2za6d1/
Change this
.gallary .pic{
width:33%;
float:left;
max-height:200px;
height:100%;
}
to this
.gallary .pic{
width:auto;
float:left;
max-height:200px;
}
EDIT: I've seen that your code works. But also that images looks distorted.
One suggest that I can give you is to use (if you can) background images to avoid this problem.
You can do this with flexbox (no js required) as follows:
.gallary{
width:100%;
display: flex;
}
.pic {
flex: 1;
}
.pic img {
width: 100%;
}
I've set .gallary's width to 100% so that we can see it's responsive.
As gallery is the parent element I've set this to flex.
I've then added flex: 1 to each .pic element so that they are each the same width. Finally, I've set the width of each image to 100% so that they scale to fit the width of each .pic element.
Using flexbox like this means that each child element (in this case the .pic elements) is automatically the same height.
I've set up a codepen http://codepen.io/alexmagill/pen/ggGVwL with some background colours in place so that you can play around with it and get a sense of what is happening.
Support for it is pretty solid now but you might want to add in fallbacks for older browsers.
Please refer this link https://github.com/liabru/jquery-match-height
1.Apply match height class for the outer div of the image.
2.Then apply this css for the image
<style>
.img{
width:100%;
height:100%;
object-fit:cover;
object-position:center;
}
</style>

vertically align img inside floated div

There are 5 floated divs which heights are stretched to 100% of document height using Javascript. All 5 of them contain img element.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link type="text/css" rel="stylesheet" href="style.css"/>
</head>
<body>
<div id="wrapper">
<div id="static"><img src="http://www.rs.dhamma.org/wheel.gif"/></div>
<div><img src="http://www.rs.dhamma.org/wheel.gif"/></div>
<div><img src="http://www.rs.dhamma.org/wheel.gif"/></div>
<div><img src="http://www.rs.dhamma.org/wheel.gif"/></div>
<div class="clear"><img src="http://www.rs.dhamma.org/wheel.gif"/></div>
</div>
</body>
</html>​
Javascript:
//sets columns height to 100%;
function colsHeight(){
var docHeight = $(document).height();
$("#wrapper div").height(docHeight);
};
$(document).ready(function(){
colsHeight();
});
and CSS:
*{
margin: 0;
padding: 0;
}
#wrapper{
width: 1000px;
margin: 0 auto;
}
#wrapper div{
padding: 0 20px;
background-color: #9F81F7;
float: left;
border-right: 1px solid black;
}
#wrapper img{
}
div.clear:after{
content: " ";
clear: both;
}
​I've tried setting parent's div display: table and img display: table-cell, vertical-align: middle but no luck. Defining margin-top: 50% is acting anything but expected.
JSFIDDLE HERE!!!
Any help appreciated.
Thanks!
You could position them absolutely, then set top: 50% and margin-top: -63px. Of course, this only works if you know the height of the image (126px in your case). If the image sizes are dynamic, the easiest, but yucky way would be to set the margin-top on the images using js after they are loaded.
Anyway, the static method can be seen here: http://jsfiddle.net/3gqcS/2/
This feels a bit dirty, but you can set the div's line-height to div height + image height then overflow:hidden
<div id="static" style="height: 481px; line-height: 607px; overflow: hidden;">
since you using javascript and jQuery(can't live without him) you can do....
check this: http://jsfiddle.net/828pW/
here is the code:
function verticalAlignImage(img)
{
if(img.height)
{
$(img).css({
position:'absolute',
top: ($(img).parent().height() - img.height)/2
}).parent().css('position', 'relative');
}
else
{
setTimeout(function(){
verticalAlignImage(img);
}, 100);
}
}
​
Try setting the columns:
position:relative;
width:<width>;/* width must be set */
and the images as:
position:absolute;
top:0;
bottom:0;
margin:auto 0;
That should perfectly center them however then you need to set column width as the image with absolute positioning take up no space at all.
Also, instead of using java script just add:
html, body, #wrapper, #wrapper div{height:100%;}
instead.
Learned from: http://www.tutwow.com/htmlcss/quick-tip-css-100-height/

Categories