How to make rotated <hr> line length adapt to page height? - rotation

I have a rotated hr line. See far right here.
Is it possible to make the line's length adapt to the height of the page?
Thank you!

Here is a script that calculates letter-spacing:
#container {
width: 50px;
height: 500px;
display: block;
border: 1px solid red;
}
p {
writing-mode: vertical-rl;
text-orientation: mixed;
}
<div id="container">
<p>My Text Here</p>
<script>
const container = document.querySelector('#container');
const text = container.querySelector('p');
const height0 = text.offsetHeight;
text.style.letterSpacing = '1px';
const height1 = text.offsetHeight;
const spacing = (container.offsetHeight - height0 - 2) / (height1 - height0);
text.style.letterSpacing = `${spacing}px`;
</script>
</div>
Tried also text-align: justify with text-justify and it seems to be incompatible with vertically oriented texts...

Related

Scroll hero animation using main scroll bar/scroll jacking

I'm trying to create a scroll animation similar to Apple (which there are a lot of codepen examples and tutorials for that, such as these: https://codepen.io/Maltsbier/pen/dyYmGGq or https://codepen.io/j-v-w/pen/ZEbGzyv). However, what I need is for it to not take over the entire screen, but instead, just a portion of the screen like a typical hero (around 600-700px) before allowing the user to scroll the rest of the page (which would just be regular html). I've sort of simulated it in this codepen (https://codepen.io/kmell/pen/RwQzjGp) using "position: sticky" and overflow: scroll on the parent div, but it only works when you use your mousewheel and scroll over the video itself. Basically, I'm looking for that effect, but when using the main scroll bar. I believe this will require some "scroll jacking" but after reading tons of articles and looking at a bunch of stackoverflow answers, I just can't seem to find anything that works and/or that I can understand/replicate. I'm also having trouble getting the text to scroll with the animation, but I think I can figure that part out. Anyway, any help, guidance or even just a push in the right direction would be greatly appreciated. Happy to provide more context if needed. Thank you!
Here's the HTML:
<div class="container">
<div class="app">
<div id="bound-one" class="scroll-bound">
<div class="content">
<div class="video-holder">
<video width="600" muted="" preload="" id="html5_video_cylzo56m54e">
<source src="https://cdn.ananaspizza.de/file/malte-image-store/v9-webm.webm" type="video/webm">
</video>
</div>
</div>
<div class="text-holder">
<h1>Here is the first bit of text</h1>
<p>Here is the first sub-title</p>
<h1 class="second-scroll">Here is the second bit of text</h1>
<p>Here is the second sub-title</p>
</div>
</div>
</div>
</div>
<div class="spacer">More Content would go here that does not require any of this scrolling functionality, just plain text.</div>
Here's the CSS:
.app { height: 700px; overflow-y: scroll; }
.scroll-bound { height:300vh; }
.scroll-bound .content { height: 700px; width: 50%; position: sticky; position: -webkit-sticky; top:0; }
.scroll-bound video { width: 100%; }
.second-scroll { margin-top: 115vh;}
/*.app::-webkit-scrollbar { display: none; }*/
.text-holder { width: 50%; position: absolute; top: 70px; right: 0; }
.spacer { min-height: 500px; background: #ccc; }
Here's the JS:
const registerVideo = (bound, video) => {
bound = document.querySelector(bound);
video = document.querySelector(video);
const scrollVideo = ()=>{
if(video.duration) {
const distanceFromTop = window.scrollY + bound.getBoundingClientRect().top;
const rawPercentScrolled = (window.scrollY - distanceFromTop) / (bound.scrollHeight - window.innerHeight);
const percentScrolled = Math.min(Math.max(rawPercentScrolled, 0), 1);
video.currentTime = video.duration * percentScrolled;
}
requestAnimationFrame(scrollVideo);
}
requestAnimationFrame(scrollVideo);
}
registerVideo("#bound-one", "#bound-one video");

Scroll duration for behaviour = smooth in different browsers

I'm want to use the window.scrollTo function with smooth behaviour.
For example:
window.scrollTo({ top: 0, behavior: 'smooth' })
Parallel I want to change an elements color. For this I could use the scroll event to calculate the color for the current scroll position. But this would result in a bad performance because the scroll callback will called to often.
The better solution would be to start a transition at the same time. But for this I have to know the scroll duration. Since it's not possible to define it manually, I need to know which duration the browsers uses.
The specification says
The scrolling box is scrolled in a smooth fashion
using a user-agent-defined timing function over a user-agent-defined period of time.
User agents should follow platform conventions, if any.
Right away that makes it a complicated question to which there is likely no answer, or at least no answer which will reliably stay put.
Browsers might
Aim for a target speed rather than duration, and so scroll for a longer period of time if there are several pages to scroll
Adjust the scrolling behaviour if many nested scrolling panels are scrolling at once, such as sequencing them one after another (I see some code in Chromium which might be doing something like this)
Allow it to be user-configurable, so people with poor vision or motion sickness can tweak it to their liking, or disable it
Defer to the operating system, which might have its own quirks and customizations
Change any of this with no notice, or the underlying OS might
Here is an excerpt of a comment in some Firefox code to do with smooth scrolling. I did not dig in to whether this is actually strictly relevant to the sorts of scroll you are doing, but it gives an idea:
* |Smooth| scrolls have a symmetrical acceleration and deceleration curve
* modeled with a set of splines that guarantee that the destination will be
* reached over a fixed time interval. |Smooth| will only be smooth if smooth
* scrolling is actually enabled. This behavior is utilized by keyboard and
* mouse wheel scrolling events.
*
* |SmoothMsd| implements a physically based model that approximates the
* behavior of a mass-spring-damper system. |SmoothMsd| scrolls have a
* non-symmetrical acceleration and deceleration curve, can potentially
* overshoot the destination on intermediate frames, and complete over a
* variable time interval. |SmoothMsd| will only be smooth if cssom-view
* smooth-scrolling is enabled.
And here is a little bit of code you can use to test for yourself. In my experimentation I'm seeing the duration varying based on how far it scrolls, both in Firefox and Chromium, and I'm seeing different speeds in each of those.
const qs = document.querySelector.bind(document);
const viewportHeightInput = qs("#viewport-height");
const contentHeightInput = qs("#content-height");
const viewport = qs("#viewport");
const content = qs("#content");
const output = qs("#output");
function update() {
viewport.style.height = `${viewportHeightInput.value}px`;
content.style.height = `${contentHeightInput.value}px`;
}
update();
viewportHeightInput.addEventListener("input", update);
contentHeightInput.addEventListener("input", update);
qs("#to-top").addEventListener("click", () => {
start = performance.now();
scrollEvents = 0;
updateScrollEvents();
viewport.scrollTo({
behavior: "smooth",
top: 0,
})
});
qs("#to-bottom").addEventListener("click", () => {
start = performance.now();
scrollEvents = 0;
updateScrollEvents();
viewport.scrollTo({
behavior: "smooth",
top: viewport.scrollHeight - viewport.clientHeight,
})
});
const scrollEventsOutput = qs("#scroll-events");
const elapsedOutput = qs("#elapsed");
let scrollEvents = 0;
let start = performance.now();
let last = null;
viewport.addEventListener("scroll", () => {
last = performance.now();
scrollEvents++;
updateScrollEvents();
});
function updateScrollEvents() {
scrollEventsOutput.value = scrollEvents;
elapsedOutput.value = last == null ? 0 : last - start;
}
#controls {
display: grid;
grid-template-columns: 10rem 1fr;
}
#controls fieldset {
display: contents;
}
#viewport {
overflow: auto;
border: thick solid orange;
margin: 4rem 0;
}
#content {
background-image: linear-gradient(to bottom left, black, white);
position: relative;
}
#content::before,
#content::after {
position: absolute;
left: 0;
background-color: black;
color: white;
display: block;
}
#content::before {
content: "start";
top: 0;
}
#content::after {
content: "end";
bottom: 0;
}
<div id="controls">
<fieldset>
<label for="viewport-height">Viewport height</label>
<input id="viewport-height" type="number" min="1" value="400">
</fieldset>
<fieldset>
<label for="content-height">Content height</label>
<input id="content-height" type="number" min="1" value="1000">
</fieldset>
<fieldset>
<label>Triggers</label>
<ul>
<li><button id="to-top">Scroll to top</button></li>
<li><button id="to-bottom">Scroll to bottom</button></li>
</ul>
</fieldset>
<fieldset>
<label for="scroll-events">Scroll events</label>
<input id="scroll-events" type="number" readonly value="0">
</fieldset>
<fieldset>
<label for="elapsed">Milliseconds between start of scroll and last scroll event</label>
<input id="elapsed" type="number" readonly value="0">
</fieldset>
</div>
<div id="viewport">
<div id="content"></div>
</div>
The code example I shared in the comment is just for reference. You further need to modify the code as per your own requirement for scrolling the page.
Here, I have tried to modify that sample code to scroll the page.
$(window).scroll(function() {
// selectors
var $window = $(window),
$body = $('body'),
$panel = $('.panel');
// Change 33% earlier than scroll position so colour is there when you arrive.
var scroll = $window.scrollTop() + ($window.height() / 3);
$panel.each(function () {
var $this = $(this);
// if position is within range of this panel.
// So position of (position of top of div <= scroll position) && (position of bottom of div > scroll position).
// Remember we set the scroll to 33% earlier in scroll var.
if ($this.position().top <= scroll && $this.position().top + $this.height() > scroll) {
// Remove all classes on body with color-
$body.removeClass(function (index, css) {
return (css.match (/(^|\s)color-\S+/g) || []).join(' ');
});
// Add class of currently active div
$body.addClass('color-' + $(this).data('color'));
}
});
}).scroll();
$(document).ready(function(){
$("button").click(function(){
$("html, body").animate({
scrollTop: $("#bottom").offset().top - 220
}, 8000);
// document.getElementById('bottom').scrollIntoView({behavior: "smooth"});
});
});
/* Setting fade transition and default settings */
body {
color: #000;
background-color: #f4f4f4;
transition: background-color 1s ease;
}
/* panel styles */
.panel {
/* min height incase content is higher than window height */
min-height: 100vh;
display: flex;
justify-content: space-around;
align-items: center;
font-family: sans-serif;
/* outline: 10px solid hotpink; */
/* turn above on to see the edge of panels */
}
/* colours */
.color-violet {
background-color: #7A4EAB;
}
.color-indigo {
background-color: #4332CF;
}
.color-blue {
background-color: #2F8FED;
}
.color-green {
background-color: #4DCF42;
}
.color-yellow {
background-color: #FAEB33;
}
.color-orange {
background-color: #F19031;
}
.color-red {
background-color: #F2293A;
}
/* styling for demo, can ignore */
body {
text-align: center;
font-size: 120%;
line-height: 1.618;
}
h1, h2 {
font-size: 3em;
letter-spacing: -0.05em;
line-height: 1.1;
}
p {
max-width: 30em;
margin-bottom: 1.618em;
}
a {
color: #4332CF;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="panel" data-color="white">
<div>
<h1>scrolling example</h1>
<div><button>Click me to scroll to bottom</button></div>
</div>
</div>
<div class="panel" data-color="violet">
<h2>Violet panel</h2>
</div>
<div class="panel" data-color="indigo">
<h2>Indigo panel</h2>
</div>
<div class="panel" data-color="blue">
<h2>Blue panel</h2>
</div>
<div class="panel" data-color="green">
<h2>Green panel</h2>
</div>
<div class="panel" data-color="yellow">
<h2>Yellow panel</h2>
</div>
<div class="panel" data-color="orange">
<h2>Orange panel</h2>
</div>
<div class="panel" data-color="red">
<h2>Red panel</h2>
</div>
<div id="bottom"></div>
Output in the MS Edge Chromium browser:
Further, you can try to modify the code sample as per your requirements.
Reference:
Code example link

Trying to align image and canvas

First-time posting a question, and I avow up front that my HTML/CSS/Javascript knowledge is ... shall we say scrappy. I usually manage, but I can't seem to figure this out.
All I want to do is display an image centered. Then create a canvas, position the canvas over the image, and draw on it. Then have the canvas stay with the image as the browser is re-sized. Here's what I have so far (I confess, I got much of the Javascript code from another poster, and I'm trying to use it as a learning example):
<!DOCTYPE html>
<html>
<head>
<script>
function myInit()
{
hdc = set_canvas();
hdc.fillRect(0, 0, 50, 50);
}
function set_canvas()
{
var img = document.getElementById('audubon_image');
var x = img.offsetLeft,
y = img.offsetTop,
w = img.clientWidth,
h = img.clientHeight;
var c = document.getElementById('myCanvas');
img.parentNode.appendChild(c);
c.style.zIndex = 1;
c.style.left = x + 'px';
c.style.top = y + 'px';
c.setAttribute('width', w+'px');
c.setAttribute('height', h+'px');
hdc = c.getContext('2d');
return(hdc);
}
</script>
<style>
#container
{
text-align: center;
}
canvas
{
pointer-events: none;
position: absolute;
border: 1px solid black;
}
</style>
</head>
<body onload='myInit()'>
<div id="container">
<img src="http://www.sturtz.org/john/audubon/wp-content/uploads/2015/04/Audubon.jpg" id="audubon_image" />
<canvas id='myCanvas'></canvas> <!-- gets re-positioned in myInit(); -->
</div>
</body>
</html>
What's supposed to happen: The image gets placed. Then the Javascript code determines the position and size of the image, and sets the canvas to match. Then draws on the canvas (for the moment, a lovely elegant block box in the upper left corner).
So far, so good. But since the image centered, if the browser is re-sized (specifically made wider or narrower), the image's position moves relative to the left and right edges of the browser window.
With 'position: absolute' specified for the canvas, the canvas does not move (unsurprisingly; I suppose that's what absolute means). So the image and canvas do not stay aligned.
If I change the canvas CSS to 'position: relative', then when I re-size the window, the image and canvas remain in the same position relative to one another (which is what I want). But then I can't get the canvas over the top of the image.
My gut feel is that this should be possible (easy, even), and my lack of knowledge is causing me not to see it.
I think I'm on to it.
Put the canvas in a div. Wrap that and the img in a container div. Specify 'position: relative' for the outer div, 'position: absolute' for the inner div. That way, the x and y coordinates of the div containing the canvas may simply be specified as (0,0).
<!DOCTYPE html>
<html>
<head>
<script>
function myInit()
{
hdc = set_canvas();
hdc.fillRect(0, 0, 50, 50);
}
function set_canvas()
{
var c = document.getElementById('map_canvas');
c.style.zIndex = 1;
c.setAttribute('width', '650px');
c.setAttribute('height', '300px');
hdc = c.getContext('2d');
return(hdc);
}
</script>
<style>
#image_container
{
margin-left: auto;
margin-right: auto;
width: 650px;
position: relative;
}
#canvas_container
{
position: absolute;
top: 0px;
left: 0px;
}
#map_canvas
{
}
</style>
</head>
<body onload='myInit()'>
<div id="image_container">
<img src="http://www.sturtz.org/john/audubon/wp-content/uploads/2015/04/Audubon.jpg" id="audubon_image" />
<div id="canvas_container">
<canvas id="map_canvas"></canvas>
</div>
</div>
</body>
</html>
How to position the canvas directly over the img with the container horizontally centered.
Keep the canvas directly over the image
Set both #audubon_image and #myCanvas to position:absolute inside the #container that's set to position:relative.
Center the container div
margin:0 auto; to center #container on the page.
CSS
#container{
margin:0 auto;
position:relative;
border:1px solid blue;
}
#audubon_image,#myCanvas{position:absolute; top:0px; left:0px;}
#audubon_image{border:1px solid green;}
#myCanvas{ border:1px solid red;}
Javascript
Set the #container's CSS size and #canvas's element size to equal the img's size. Be sure to set the canvas element size (not css size) or your canvas drawings will be distorted.
// get a reference to #audubon_image
var img=document.getElementById('audubon_image');
// set #container's size to equal the #audubon_image size
var container=document.getElementById('container');
container.style.width=img.width+'px';
container.style.height=img.height+'px';
// set #myCanvas's size to equal the #audubon_image size
var canvas=document.getElementById('myCanvas');
canvas.width=img.width;
canvas.height=img.height;
Note: Once in a great while, browsers will fire window.onload before the image's width & height are set (shame on you browsers!). So in production, you might "defensively" wrap the javascript inside a setTimeout of 1 second to be sure the image's width & height have been set.
Full code and a Demo:
window.onload = (function() {
// get a reference to #audubon_image
var img = document.getElementById('audubon_image');
// set #container's size to equal the #audubon_image size
var container = document.getElementById('container');
container.style.width = img.width + 'px';
container.style.height = img.height + 'px';
// set #myCanvas's size to equal the #audubon_image size
var canvas = document.getElementById('myCanvas');
canvas.width = img.width;
canvas.height = img.height;
});
body {
background-color: ivory;
}
#container {
margin: 0 auto;
position: relative;
border: 1px solid blue;
}
#audubon_image,
#myCanvas {
position: absolute;
top: 0px;
left: 0px;
}
#audubon_image {
border: 1px solid green;
}
#myCanvas {
border: 1px solid red;
}
<div id="container">
<img id="audubon_image" src='https://dl.dropboxusercontent.com/u/139992952/multple/character3.png' />
<canvas id='myCanvas'></canvas>
</div>

Split/reveal image with css translate-y on scroll

I would like to achieve the effect where one image is revealed over the other when scrolling the page.
You can see an example on livearealabs.com (new york / seattle). Does anybody know how to create it using CSS3?
Check out this jsfiddle to create the sliding effect.
The trick is to have one div rotated 60 degrees. You position it so that it covers the entire wrapper and the overflow is hidden. Then with javascript you just have to move the slice container either by changing the left property or by changing the translate-X property.
Here is the code:
HTML:
<div class="wrapper">
<div class="bg"></div>
<div class="slice" data-show="true"></div>
</div>
CSS:
.wrapper {
position: relative;
overflow: hidden;
width: 20em;
height: 10em;
}
.bg {
background-color: red;
width: 100%;
height: 100%;
}
.slice {
position: absolute;
top: -12em;
left: -8em;
width: 30em;
height: 30em;
background-color: blue;
-webkit-transform: rotate(-60deg);
}
JS:
var hidden = false;
$('.wrapper').click(function() {
console.log('click');
if (hidden) {
$('.slice').stop().animate({left: '-8em'}, 2000);
hidden = false;
} else {
$('.slice').stop().animate({left: '-34em'}, 2000);
hidden = true;
}
console.log('click end');
});
Also check out this jsfiddle for a similar sliding effect that can be achieved with CSS only.

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

I need to make this image stretch to the maximum size possible without overflowing it's <div> or skewing the image.
I can't predict the aspect-ratio of the image, so there's no way to know whether to use:
<img src="url" style="width: 100%;">
or
<img src="url" style="height: 100%;">
I can't use both (i.e. style="width: 100%; height: 100%;") because that will stretch the image to fit the <div>.
The <div> has a size set by percentage of the screen, which is also unpredictable.
Update 2016:
Modern browser behave much better. All you should need to do is to set the image width to 100% (demo)
.container img {
width: 100%;
}
Since you don't know the aspect ratio, you'll have to use some scripting. Here is how I would do it with jQuery (demo):
CSS
.container {
width: 40%;
height: 40%;
background: #444;
margin: 0 auto;
}
.container img.wide {
max-width: 100%;
max-height: 100%;
height: auto;
}
.container img.tall {
max-height: 100%;
max-width: 100%;
width: auto;
}​
HTML
<div class="container">
<img src="http://i48.tinypic.com/wrltuc.jpg" />
</div>
<br />
<br />
<div class="container">
<img src="http://i47.tinypic.com/i1bek8.jpg" />
</div>
Script
$(window).load(function(){
$('.container').find('img').each(function(){
var imgClass = (this.width/this.height > 1) ? 'wide' : 'tall';
$(this).addClass(imgClass);
})
})
There is a much easier way to do this using only CSS and HTML:
HTML:
<div
class="fill"
style="background-image: url('path/to/image.jpg');">
</div>
CSS:
.fill {
background-size: cover;
background-position: center;
width: 100%;
height: 100%;
}
This will place your image as the background, and stretch it to fit the div size without distortion.
Not a perfect solution, but this CSS might help. The zoom is what makes this code work, and the factor should theoretically be infinite to work ideally for small images - but 2, 4, or 8 works fine in most cases.
#myImage {
zoom: 2; //increase if you have very small images
display: block;
margin: auto;
height: auto;
max-height: 100%;
width: auto;
max-width: 100%;
}
If you're able to set the image as a background-image then you can do something like this, which will crop the image without stretching it:
<div style="background-image: url(...); background-size: cover; width: 100%; height: 100%;"></div>
If you need to stick with an <img> tag, then as of 2019, you can now use the object-fit css property that accepts the following values:
fill | contain | cover | none | scale-down
See https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
As an example, you could have a container that holds an image:
<div class="container">
<img src="" class="container_img" />
</div>
.container {
height: 50px;
width: 50%;
}
.container_img {
height: 100%;
width: 100%;
object-fit: cover;
}
If you can, use background images and set background-size: cover. This will make the background cover the whole element.
CSS
div {
background-image: url(path/to/your/image.png);
background-repeat: no-repeat;
background-position: 50% 50%;
background-size: cover;
}
If you're stuck with using inline images there are a few options. First, there is
object-fit
This property acts on images, videos and other objects similar to background-size: cover.
CSS
img {
object-fit: cover;
}
Sadly, browser support is not that great with IE up to version 11 not supporting it at all. The next option uses jQuery
CSS + jQuery
HTML
<div>
<img src="image.png" class="cover-image">
</div>
CSS
div {
height: 8em;
width: 15em;
}
Custom jQuery plugin
(function ($) {
$.fn.coverImage = function(contain) {
this.each(function() {
var $this = $(this),
src = $this.get(0).src,
$wrapper = $this.parent();
if (contain) {
$wrapper.css({
'background': 'url(' + src + ') 50% 50%/contain no-repeat'
});
} else {
$wrapper.css({
'background': 'url(' + src + ') 50% 50%/cover no-repeat'
});
}
$this.remove();
});
return this;
};
})(jQuery);
Use the plugin like this
jQuery('.cover-image').coverImage();
It will take an image, set it as a background image on the image's wrapper element and remove the img tag from the document. Lastly you could use
Pure CSS
You might use this as a fallback. The image will scale up to cover it's container but it won't scale down.
CSS
div {
height: 8em;
width: 15em;
overflow: hidden;
}
div img {
min-height: 100%;
min-width: 100%;
width: auto;
height: auto;
max-width: none;
max-height: none;
display: block;
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Hope this might help somebody, happy coding!
Thanks to CSS3
img
{
object-fit: contain;
}
https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
IE and EDGE as always outsiders:
http://caniuse.com/#feat=object-fit
That's impossible with just HTML and CSS, or at least wildly exotic and complicated. If you're willing to throw some javascript in, here's a solution using jQuery:
$(function() {
$(window).resize(function() {
var $i = $('img#image_to_resize');
var $c = $img.parent();
var i_ar = $i.width() / $i.height(), c_ar = $c.width() / $c.height();
$i.width(i_ar > c_ar ? $c.width() : $c.height() * (i_ar));
});
$(window).resize();
});
That will resize the image so that it will always fit inside the parent element, regardless of it's size. And as it's binded to the $(window).resize() event, when user resizes the window, the image will adjust.
This does not try to center the image in the container, that would be possible but I guess that's not what you're after.
You can use object-fit: cover; on the parent div.
https://css-tricks.com/almanac/properties/o/object-fit/
Set width and height of the outer container div. Then use below styling on img:
.container img{
width:100%;
height:auto;
max-height:100%;
}
This will help you to keep an aspect ratio of your img
If you want to set a max width or height (so that it will not be very large) while keeping the images aspect-ratio, you can do this:
img{
object-fit: contain;
max-height: 70px;
}
I came across this question searching for a simular problem. I'm making a webpage with responsive design and the width of elements placed on the page is set to a percent of the screen width. The height is set with a vw value.
Since I'm adding posts with PHP and a database backend, pure CSS was out of the question. I did however find the jQuery/javascript solution a bit troblesome, so I came up with a neat (so I think myself at least) solution.
HTML (or php)
div.imgfill {
float: left;
position: relative;
background-repeat: no-repeat;
background-position: 50% 50%;
background-size: cover;
width: 33.333%;
height: 18vw;
border: 1px solid black; /*frame of the image*/
margin: -1px;
}
<div class="imgfill" style="background-image:url(source/image.jpg);">
This might be some info
</div>
<div class="imgfill" style="background-image:url(source/image2.jpg);">
This might be some info
</div>
<div class="imgfill" style="background-image:url(source/image3.jpg);">
This might be some info
</div>
By using style="" it's posible to have PHP update my page dynamically and the CSS-styling together with style="" will end up in a perfectly covered image, scaled to cover the dynamic div-tag.
To make this image stretch to the maximum size possible without overflowing it's or skewing the image.
Apply...
img {
object-fit: cover;
height: -webkit-fill-available;
}
styles to the image.
Using this method you can fill in your div with the image varying ratio of divs and images.
jQuery:
$(window).load(function(){
$('body').find(.fillme).each(function(){
var fillmeval = $(this).width()/$(this).height();
var imgval = $this.children('img').width()/$this.children('img').height();
var imgClass;
if(imgval > fillmeval){
imgClass = "stretchy";
}else{
imgClass = "stretchx";
}
$(this).children('img').addClass(imgClass);
});
});
HTML:
<div class="fillme">
<img src="../images/myimg.jpg" />
</div>
CSS:
.fillme{
overflow:hidden;
}
.fillme img.stretchx{
height:auto;
width:100%;
}
.fillme img.stretchy{
height:100%;
width:auto;
}
This did the trick for me
div img {
width: 100%;
min-height: 500px;
width: 100vw;
height: 100vh;
object-fit: cover;
}
if you working with IMG tag, it's easy.
I made this:
<style>
#pic{
height: 400px;
width: 400px;
}
#pic img{
height: 225px;
position: relative;
margin: 0 auto;
}
</style>
<div id="pic"><img src="images/menu.png"></div>
$(document).ready(function(){
$('#pic img').attr({ 'style':'height:25%; display:none; left:100px; top:100px;' })
)}
but i didn't find how to make it work with #pic { background:url(img/menu.png)}
Enyone?
Thanks
I had similar issue. I resolved it with just CSS.
Basically Object-fit: cover helps you achieve the task of maintaining the aspect ratio while positioning an image inside a div.
But the problem was Object-fit: cover was not working in IE and it was taking 100% width and 100% height and aspect ratio was distorted. In other words image zooming effect wasn't there which I was seeing in chrome.
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.
HTML:
<style>
#foo, #bar{
width: 50px; /* use any width or height */
height: 50px;
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
}
</style>
<div id="foo" style="background-image: url('path/to/image1.png');">
<div id="bar" style="background-image: url('path/to/image2.png');">
JSFiddle
...And if you want to set or change the image (using #foo as an example):
jQuery:
$("#foo").css("background-image", "url('path/to/image.png')");
JavaScript:
document.getElementById("foo").style.backgroundImage = "url('path/to/image.png')";
Many of the solutions found here have some limitation: some not working in IE ( object-fit) or older browsers, other solutions do not scale up the images (only shrink it), many solution do not support resize of the window and many are not generic, either expect fix resolution or layout(portrait or landscape)
If using javascript and jquery is not a problem I have this solution based on the code of #Tatu Ulmanen. I fixed some issues, and added some code in case the image is loaded dinamically and not available at begining. Basically the idea is to have two different css rules and apply them when required: one when the limitation is the height, so we need to show black bars at the sides, and othe css rule when the limitation is the width, so we need to show black bars at the top/bottom.
function applyResizeCSS(){
var $i = $('img#imageToResize');
var $c = $i.parent();
var i_ar = Oriwidth / Oriheight, c_ar = $c.width() / $c.height();
if(i_ar > c_ar){
$i.css( "width","100%");
$i.css( "height","auto");
}else{
$i.css( "height","100%");
$i.css( "width","auto");
}
}
var Oriwidth,Oriheight;
$(function() {
$(window).resize(function() {
applyResizeCSS();
});
$("#slide").load(function(){
Oriwidth = this.width,
Oriheight = this.height;
applyResizeCSS();
});
$(window).resize();
});
For an HTML element like:
<img src="images/loading.gif" name="imageToResize" id="imageToResize"/>
try this
HTML:
<div class="container"></div>
CSS:
.container{
background-image: url("...");
background-size: 100%;
background-position: center;
}

Resources