Center an image and scale height/width to fit inside flexbox parent? - javascript

I'm trying to center and scale an image inside a container. In the following diagrams, the pink box is a 16:9 container and the blue box is the image.
If the image is wider than the container, it will scale to fit.
If the image is taller than the container, it will also scale to fit.
If the image fits in the container, it will simply be centered.
As you can see in the diagrams, there is also a caption div aligned to the bottom left of the image, and a close icon aligned to the top right.
Here is the code I have now:
/* The page */
.container {
width: 100%;
height: 100%;
}
/* 16:9 container */
.imageWrapper {
padding-bottom: 56.25%;
position: relative;
width: 100%;
border: 1px solid red;
}
.imageInnerWrapper {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
align-items: center;
justify-content: center;
}
/* The image, footer and close button all need to fit inside the container */
.imageAndFooterWrapper {
display: inline-flex;
flex-direction: column;
position: relative;
border: 1px solid lightblue;
}
.image {
max-height: 100%;
object-fit: contain;
}
.footer {
text-align: left;
}
.closeButton {
position: absolute;
top: -30px;
right: -30px;
}
<div class="container">
<div class="imageWrapper">
<div class="imageInnerWrapper">
<div class="imageAndFooterWrapper">
<img class="image" src="https://images.theconversation.com/files/204986/original/file-20180206-14104-1hyhea9.jpg?ixlib=rb-1.1.0&rect=0%2C1212%2C5550%2C2775&q=45&auto=format&w=1356&h=668&fit=crop">
<div class="footer">
Caption
</div>
<div class="closeButton">X</div>
</div>
</div>
</div>
</div>
The following CodePen contains the above code, with some examples of different sized images.
https://codepen.io/anon/pen/NMKxxm

This may not be a direct answer to your question but usually when I have to do something like this, I use a div with a background image instead of an img tag. Using a div with a bg image allows you to use styles like background-image, background-position and background-size which allow you to create the effect as described by you.
Sample:
var imgDiv = $('.image')[0];
var closeButton = $('.fixed-el')[0];
var img = document.createElement('img');
img.src = getComputedStyle(imgDiv).backgroundImage.split('"')[1];
var calculate_positions = {
img_width: img.naturalWidth,
img_height: img.naturalHeight,
img_ratio: function() {
return calculate_positions.img_width / calculate_positions.img_height;
},
elm_ratio: function(elm) {
return $(elm).width() / $(elm).height();
},
img_offset: function(elm) {
var offset = []; //[x,y]
if (calculate_positions.elm_ratio(elm) > calculate_positions.img_ratio()) {
//centered x height 100%
var scale_percent = $(elm).height() / calculate_positions.img_height;
var scaled_width = calculate_positions.img_width * scale_percent;
var x_offset = ($(elm).width() - scaled_width) / 2;
offset = [x_offset, 0];
} else {
//centered y width 100%
var scale_percent = $(elm).width() / calculate_positions.img_width;
var scaled_height = calculate_positions.img_height * scale_percent;
var y_offset = ($(elm).height() - scaled_height) / 2;
offset = [0, y_offset];
}
return offset;
}
}
function updatePosition() {
var offset = calculate_positions.img_offset($('div.image'));
closeButton.style.top = offset[1] + 'px';
closeButton.style.left = offset[0] + 'px';
}
$(window).resize(updatePosition)
$(img).load(function() {
updatePosition();
});
div.image {
width: 100%;
background-image: url('http://via.placeholder.com/100x100');
background-position: center;
background-size: contain;
background-repeat: no-repeat;
flex: 1;
}
html,
body,
div.container {
width: 100%;
height: 100%
}
div.container {
display: flex;
position: relative;
flex-direction: column;
}
div.fixed-el {
position: absolute;
width: 20px;
height: 20px;
background: red;
}
div.caption {
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="image"></div>
<div class="caption">Some caption here</div>
<div class="fixed-el"></div>
</div>
EDIT:
You can change the image size in the styles and resize the window to see the scaling in action.
I also noticed the comment which mentioned that you do not want to use background image as it will clip the image. This will not happen if you use background-size:contain
EDIT 2:
It turns out you can actually figure out what the coordinates of the image are and position other elements around it. Have created a dirty hack to demonstrate this (mixed jQuery and vanilla JS, no proper scoping etc).. But you should be able to get the main idea and implement a neater solution. The main idea is derived from this question on SO

Related

How to Swap Two Divs With Animation

I have a project where I want a div to appear as a large box and three more to appear underneath as smaller boxes and when you click a smaller box, it switches sizes and places with the large box using css transitions to make the movement and size change smooth. Right now I'm attempting to use jQuery and the positioning is not working at all. Here's an example of what I have so far:
https://jsfiddle.net/v3pmhawj/1/
$(function () {
let { left: x1, top: y1 } = $('.full-size-card').offset()
$('.inactive-sheets .card').on('click', function() {
let { left: x2, top: y2 } = $(this).offset()
let curr = $('.full-size-card')
let diffX = x2 - x1
let diffY = y2 - y1
$(this).css({
left: -diffX,
top: -diffY
})
$(this).addClass('full-size-card')
curr.css({
left: diffX,
top: diffY
})
curr.removeClass('full-size-card')
})
})
If anyone has suggestions on ways that involve other libraries or other techniques, I'm all ears. I'd like to be able to move the divs around in the DOM as well but as far as I can tell, you can't css-transition them if you do that since the only way (I know of) is to delete and re-add a copy of the element where you want it in the DOM.
You can create animation effect using transitions only. To achieve this you will have to define width and height of your containers as well as top and left position of bottom elements.
On click, you just have to exchange classes of element that will become small and of element that will become large.
Here is fiddle of an example:
https://jsfiddle.net/fkd3ybwx/210/
HTML
<div class="card-container">
<div class="card large">A</div>
<div class="card small">B</div>
<div class="card small">C</div>
<div class="card small">D</div>
</div>
CSS
.card-container {
position: relative;
}
.card {
transition: all ease 1s;
position: absolute;
font-size: 24px;
border: white 4px solid;
box-sizing: border-box;
cursor: pointer;
}
.small {
width: 100px;
height: 100px;
background: blue;
left: 0;
top: 300px;
}
.small ~ .small {
left: 100px;
background: green;
}
.small ~ .small ~ .small {
left: 200px;
background: yellow;
}
.large {
width: 300px;
height: 300px;
background: red;
left: 0px;
top: 0px;
}
JavaScript
const smallCards = document.querySelectorAll('.card');
smallCards.forEach((smallCard) => {
smallCard.addEventListener('click', (event) => {
const largeCard = document.querySelector('.large');
largeCard.className = "card small";
event.target.className = "card large";
});
});

I want to create a zoom-in-down effect of a background which triggers only on scroll down and goes back on scroll up but does not do viceversa

I want to create my background circle so that it will cover my whole width of container but the problems that I am facing are:
I am using wheel method which I want to change with scroll method but won't able to give a exact scroll position to start scrolling scrollTop is using start of my website but I want to start my scroll after 3rd container div.
In wheel function my background zooms-in with wheel up as well as well down I only want it to work on scroll down.
I want my zoom to zoom out once it reached width of whole screen.
my code:
const zoomElement = document.querySelector(".zoom");
let zoom = 1;
const ZOOM_SPEED = 1;
document.addEventListener("wheel", function(e) {
if (e.deltaY > 0) {
zoomElement.style.transform = `scale(${zoom += ZOOM_SPEED})`;
} else {
zoomElement.style.transform = `scale(${zoom -= ZOOM_SPEED})`;
}
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
overflow-x: hidden;
}
.downarrow {
position: relative;
left: 50%;
font-size: 2rem;
color: #f0f0f0;
}
.zoom {
background: #282828;
width: 100px;
height: 100px;
border-radius: 50%;
position: relative;
left: 47.80%;
}
.container {
width: 100%;
height: 100vh;
}
<div class="container">
<div class="zoom"></div>
<p class="downarrow">↓</p>
</div>
I want to mimic this site downarrow effect:
https://lione.axiomthemes.com/

How to absolutely position shape elements relative to an underlying image?

The page has a centered image -- a map -- and I need to figure out how to mark points of interest on that map with small dots.
My plan is to draw the dots with very small circle elements, but how can I position them so that they will sit in the same place on the map every time the webpage is loaded on different sized screens? I would just photoshop the dots onto the image if I could, but I will need to write the javascript to have the dots be interactive (show a text box description on mouseover) so that won't work.
<!DOCTYPE html>
<html>
<head> <meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="example.css" />
</head>
<body>
<img src="example.jpg" style="margin-left:auto;margin-right:auto;"></img>
</body>
Wrap the image in a div, give it position:relative and the position the points (divs) absolutely using % values.
Here's an example I keep around:
Codepen Demo
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.map {
margin: 10px;
border: 5px solid red;
position: relative;
display: inline-block;
}
.map img {
max-width: 100%;
display: block;
}
.box {
width: 8%;
height: 8%;
background-image: url(http://www.clker.com/cliparts/W/0/g/a/W/E/map-pin-red.svg);
background-position: top center;
background-repeat: no-repeat;
background-size: contain;
position: absolute;
}
#pin-1 {
top: 25%;
left: 36%;
}
.box:hover>.pin-text {
display: block;
}
.pin-text {
position: absolute;
top: 50%;
transform: translateY(-50%);
left: 75%;
white-space: nowrap;
display: none;
}
.pin-text h3 {
color: white;
text-shadow: 1px 1px 1px #000;
}
<div class="map">
<img src="https://www.homesinc.com/wp-content/uploads/2017/05/1.jpg" alt="" />
<div id="pin-1" class="box">
<div class="pin-text">
<h3>My House</h3>
</div>
</div>
</div>
in case your points are dynamic and you can not set them in css, you could use canvas. this is a static example, it can be converted to dynamic if needed, could be considerably more work than positionning in percentages with css so if you know your point of interest positions you should go with CSS, if they are dynamic canvas is a good option
Codepen Demo
code bellow...
// You will need the background of the map and an array of points of interest
// containing x and y coordinates relative to the map
const mapImageUrl = 'http://via.placeholder.com/500x300'
const pointsOfInterest = [
{name:'point1', x:420, y:50},
{name:'point2', x:50, y:134},
{name:'point3', x:100, y:200}
]
// get refference to the canvas and to its context
const canvas = document.getElementById('map')
const ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 400;
// create a new image element that would hold your background
var mapImg = new Image();
// this block executes when the image is loaded
mapImg.onload = function () {
//setting the canvas size to the image size
canvas.width = mapImg.width;
canvas.height = mapImg.height;
//drawing the image to the canvas
ctx.drawImage(mapImg, 0, 0);
//for each point draw a red dot positioned to pointsOfInterest[i].x, pointsOfInterest[i].y
//here you could alose use the point of interest name or whatever you have availible on your json
for(let i = 0; i < pointsOfInterest.length; i ++) {
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(pointsOfInterest[i].x, pointsOfInterest[i].y,15,0,2*Math.PI);
ctx.stroke();
ctx.fill();
}
};
// set the url of the image, once loaded it will trigger image.onload
mapImg.src = mapImageUrl;
html, body {
height: 100%;
}
.mapContainer {
display: flex;
align-items: middle;
justify-content: center;
margin: 0;
height: 100%;
flex-wrap: wrap;
}
#map{
align-self: center
}
<div class="mapContainer">
<canvas id="map"> </canvas>
</div>

Detect When Mouse Enters Specific Area of Document (Not a Div Element)

I'm trying to figure out how Medium made their bottom action / menu bar slide up when your mouse enters the bottom of the document. The slide up effect is not triggered by moving the mouse over the invisible div (it slides up & down via transform translateY).
Besides, the menu bar is only 44px in height, but its is-visible class gets triggered way before your mouse is near it — but by what? When using Inspect Element, I can't see any hidden divs that could be triggering it..
I've searched for countless of ways, e.g. "show element when mouse enters specific part of document" but all search results involve when the mouse enters or moves over a div element, which is not the solution I'm looking for.
Obviously, you can solve this problem by putting the slide up menu inside a hidden container like I've done here, and then you get the desired result:
(function() {
var actionBar = document.querySelector('.action-bar');
var actionBarWrapper = document.querySelector('.action-bar-detection');
function showDiv() {
actionBar.classList.add('js-is-visible')
}
function hideDiv() {
actionBar.classList.remove('js-is-visible')
}
actionBarWrapper.onmouseover = showDiv;
actionBarWrapper.onmouseout = hideDiv;
})();
* {
margin: 0;
padding: 0;
box-sizing: border-box;
line-height: 1.5;
}
body {
height: 100%;
}
.wrapper {
width: 90%;
max-width: 600px;
margin: 5% auto;
}
.action-bar {
position: absolute;
left: 0;
bottom: 0;
border: 1px solid #252321;
background: #fff;
padding: 16px;
width: 100%;
min-height: 50px;
opacity: 0;
transform: translateY(100%);
transition: all .5s;
z-index: 99;
}
.action-bar-detection {
height: 150px;
width: 100%;
opacity: 1;
position: fixed;
bottom: 0;
left: 0;
z-index: 1;
}
.js-is-visible {
opacity: 1;
transform: translateY(0%);
}
<html>
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<div class="wrapper">
<p>When mouse enters the hidden action bar element, slides up.</p>
<p>But it's only happening because the action-bar is inside an invisible detection layer class (action-bar-detection) with a height of 150px.</p>
</div>
<div class="action-bar-detection">
<div class="action-bar">
Bottom Menu
</div>
</div>
</body>
</html>
However, this doesn't seem to be what Medium have done, and if this can be done without adding more HTML & CSS, I want to learn how! :-)
I think I'm not phrasing the problem correctly, since I can't find any solutions even remotely close (I've searched A LOT).
Any advice? What should I read up on? :-)
Get height of viewport, track onmousemove, and compare clientY from the mouse event to the viewport height:
(function() {
var actionBar = document.querySelector('.action-bar');
var viewHeight = window.innerHeight - 150;
function toggleDiv(e) {
if (e.clientY >= viewHeight) {
actionBar.classList.add('js-is-visible');
} else {
actionBar.classList.remove('js-is-visible');
}
}
window.onmousemove = toggleDiv;
})();
* {
margin: 0;
padding: 0;
box-sizing: border-box;
line-height: 1.5;
}
body {
height: 100%;
}
.wrapper {
width: 90%;
max-width: 600px;
margin: 5% auto;
}
.action-bar {
position: absolute;
left: 0;
bottom: 0;
border: 1px solid #252321;
background: #fff;
padding: 16px;
width: 100%;
min-height: 50px;
opacity: 0;
transform: translateY(100%);
transition: all .5s;
z-index: 99;
}
.action-bar-detection {
height: 150px;
width: 100%;
opacity: 1;
position: fixed;
bottom: 0;
left: 0;
z-index: 1;
}
.js-is-visible {
opacity: 1;
transform: translateY(0%);
}
<div class="wrapper">
<p>When mouse comes within 150px of the bottom part of the screen, the bar slides up.</p>
<p>When the mouse leaves this defined area of the screen, the bar slides down.</p>
</div>
<div class="action-bar-detection">
<div class="action-bar">
Bottom Menu
</div>
</div>
You could do this by listening to the mousemove event on the document, you will want to invest effort into making this performant as it will be triggered frequently. The most common way to regulate events like this is through throttling.
Once you are hooked into the mousemove event you will need to get the Y coordinate of the cursor and compare that to the height of the window, if it is within a threshold then you can reveal your panel, once it moves out you can proceed to hide it again.
Here is an example showing a basic implementation jsFiddle
// Using underscore for the throttle function though you can implement your own if you wish
document.addEventListener('mousemove', _.throttle(mouseMoveEventAction, 200));
function mouseMoveEventAction(e) {
doPanelStuff(isInsideThreshold(e.clientY));
}
function doPanelStuff(isActive) {
var panelElement = document.querySelector('.panel');
if (isActive) {
panelElement.style.background = 'red';
} else {
panelElement.style.removeProperty('background');
}
}
function isInsideThreshold(cursorY) {
var threshold = 200;
var clientHeight = document.documentElement.clientHeight;
return cursorY > (clientHeight - threshold);
}
html, body {
height: 100%;
}
.container, .content {
height: 100%;
width: 100%;
}
.panel {
height: 50px;
position: absolute;
bottom: 0;
width: 100%;
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<div class="container">
<div class="content"></div>
<div class="panel"></div>
</div>

Moving divs with javascript

This is my problem, I have a div and inside 2 divs, one is centered and the other one is fixed on the left, the problem is when I resize the screen the centered div overlaps the fixed one, what I wanted to do is detect when the centered div overlaps the other div and change its left value with javascript, but is not working, any ideas?
This is my design:
<div id="content-wrap">
<div id="content">
</div>
<div id="leftbar">
</div>
</div>
and the CSS:
#content-wrap
{
clear: both;
float: left;
width: 100%;
}
#content
{
text-align: left;
padding: 0;
margin: 0 auto;
height: 470px;
width: 760px;
overflow: auto;
}
#leftbar
{
background-color: transparent;
width: 200px;
height: 470px;
position: absolute;
top: 185px;
left: 50px;
}
and this is the javascript code:
window.onload = function Centrar() {
var leftBar = $get("leftbar");
if (leftBar != null) {
var content = $get("content");
var size = leftBar.offsetLeft + leftBar.offsetWidth;
if (content.offsetLeft < size) {
content.style.left = size + 20 + 'px';
}
}
}
Thanks in advance for any help.
The easiest fix would be to apply a min-width to your #content-wrap container that prevented the overlap from occurring:
#content-wrap {
clear: both;
float: left;
width: 100%;
/* #leftbar width x 2 + #content width */
min-width: 1160px;
}
However, if you want to use Javascript, you'll need to attach the code to the window load and resize events:
$(window).bind('load resize', function() {
var content = $('#content');
var leftbar = $('#leftbar');
// get the right edge of the #leftbar
var leftbarEdge = leftbar.width() + leftbar.offset().left;
// check if an overlap has occured and adjust #content left position if yes
if (leftbarEdge > content.offset().left) {
content.css({
left: leftbarEdge - content.offset().left
});
}
});
The last change you'll need to apply to get this working is to set #content to position: relative in the CSS so it respects the left property you're setting with Javascript:
#content {
position: relative;
/* remaining css */
}
You can see it in action here.

Categories

Resources