CSS calc and JS calculate are not equal each other - javascript

I calculate item width in css , and do the same in js.
First one for element style, second one for carousel track calculation.
My CSS:
.category-carousel .carousel-item {
width: calc((100vw - 80px) / 7); // result is 262.544px
}
and my JS:
var itemWidth = (window.innerWidth - 80) / 7; // result is 262.857px
Result is 262.544 and 262.857.
(I use more then 200 elements , so 200 * 0.313 give me 62px of issue)
Why its work this way ?
DEMO
https://jsfiddle.net/2nwLq7vd/5/
Width and console result are not equal

You can what I changed in your code it is regarding to border padding when set 0 then it give to me same value You should add border, margin in your js calculation for each element

It is because of the border you have set, please refer the image above. You can also find my fiddle here, https://jsfiddle.net/hamzeen/xour0ndm Here is my css:
div {
width: calc((100vw - 80px) / 7);
height: 50px;
display: inline-block;
border: 0px solid;
background-color: red;
}

Related

Maintain aspect ratio of a video when resizing the browser

I'm working on a Video editing tool, and I need to maintain the 16:9 aspect ratio of the video when resizing the screen horizontally and vertically. So far I got it to work as expected when resizing horizontally, and when resizing down vertically, but can't get it to work when sizing up vertically. The Javascript code I used to calculate the height of the video and resize it is below (notice how the else clause is empty because that's where the code should go):
const calculateHeight = () => {
// Get the other elements on the page
const header = document.querySelector('.main-navigation');
const meshTopBar = document.querySelector('.mesh__top-bar');
const footer = document.querySelector('.mesh__bottom-bar');
// Get the section to apply the window height to it
const mainSection = document.querySelector('.insert-level-container');
// Get the video elements
const editor = document.querySelector('.mesh__insert-editor-container');
const video = document.querySelector('.mesh__insert-editor-video-container');
// Apply the height to the main section by calculating the window height minus the other elements' height
if(mainSection !== null) {
mainSection.style.height = (window.innerHeight - header.offsetHeight - meshTopBar.offsetHeight - footer.offsetHeight) + 'px';
}
// This should be the ideal height for the video
video.style.minHeight = ((video.offsetWidth * 9) / 16) + 'px';
// If the video height is bigger than the section height (calculated above), then resize it
if(video.offsetHeight + 115 > mainSection.offsetHeight) {
video.style.minHeight = video.offsetHeight - 1 + 'px';
editor.style.maxWidth = video.offsetHeight * 16 / 9 + 'px';
} else {
// This is where the logic for the vertical resizing should go
}
}
The relevant CSS for these items is:
.mesh__insert-editor-container {
margin-left: auto;
margin-right: auto;
}
.mesh__insert-editor-video-container {
position: relative;
width: 100%:
}
And the HTML:
<section class="mesh__insert-editor-container flex__one flex-container flex-column horizontally-left-aligned" id="video-main-container">
<div class="mesh__insert-editor-video-container flex-container horizontally-right-aligned flex-wrap">
<video class="mesh__insert-editor-video-placeholder"></video>
</div>
</section>
All this code is:
Get the height of all the elements on the page, sum them and calculate the main section height by subtracting that height;
If the video height gets bigger than the section height, I reduce its height by -1px each time the window gets resized, and calculate the new width.
All the above code is giving me this result, which works great for most scenarios, but I need the video to size up when the condition on the if statement is not met. Everything I tried inside the else statement gets "jumpy".
Any better alternatives to solve this would be much appreciated. Thanks all!
The CSS aspect ratio trick might be a good solution: https://css-tricks.com/aspect-ratio-boxes/
The approach takes advantage of a quirk in CSS where padding based on a percentage value will be relative to the element's width. Create a container using this trick, the important bit is this line:
padding-top: calc(9/16 * 100%);
The value is calculating the correct height based on the aspect ratio you want (9 tall over 16 wide in this case) and generating it relative to the width of the element by multiplying by 100%.
With the container maintaining aspect ratio, just place the content inside an absolute positioned inner div and you should be good. This solution is fully responsive at that point.
* { box-sizing: border-box }
.outer-max-width {
max-width: 960px;
margin: 0 auto;
}
.aspect-ratio-box {
width: 100%;
padding-top: calc(9/16 * 100%);
position: relative;
border: 2px solid red; /* for demo visibility, remove */
}
.aspect-ratio-box-content {
position: absolute;
width: 100%;
top: 0;
left: 0;
border: 2px solid blue; /* for demo visibility, remove */
}
.video-placeholder {
display: block;
width: 100%;
height: auto;
}
<div class="outer-max-width">
<div class="aspect-ratio-box">
<div class="aspect-ratio-box-content">
<img class="video-placeholder" src="https://placeimg.com/640/360/nature" />
</div>
</div>
</div>
Got it to work! I used this amazing CSS-only solution: https://codepen.io/EightArmsHQ/pen/BvNzrm similar to BugsArePeopleToo's suggestion, from eightarmshq:
.content{
position: absolute;
top: 0;
bottom: 0;
width: 100%;
height: 100%;
background: #555;
box-shadow: inset 1vh 1vh 10vh 0 rgba(0,0,0,0.5);
display: flex;
box-sizing: border-box;
border: 25px solid #cecece;
}

Set div width that is equal half of window with minus 25px using Javascript or JQuery

I want to subtract 25px or any number of px from two divs that have width set to half of window width
Here is https://jsfiddle.net/vzwa2fjL/8/
Here is what i got so far with JS
$(window).resize(setHeightAndWidth);
$(document).ready(setHeightAndWidth);
function setHeightAndWidth() {
var halfWidth = $('.left, .right').width($(window).width() / 2);
$('.section').height($(window).height());
halfWidth;
}
I just need to do halfWidth - 25px; but i am not sure how.
Use CSS calc with relative viewport width.
Fiddle Demo
.left, .right {
....
width: calc(50vw - 25px);
}
Browser Compatibility
As calc is not reliable to use across mobile browsers, jQuery can be used.
Updated Fiddle
$('.left, .right').width($(window).width() / 2 - 25);
Also,
$('.section').height($(window).height());
is not necessary when the same can be done in CSS.
.section {
height: 100vh;
}

Recreating an animation using jQuery and CSS

I've been working on a scrolling effect for my site that has been driving me crazy, and it's probably not even worth it but I can't stop now.
I have been able to simulate the effect using adobe edge and muse. Can anyone think of a simpler method of creating this effect? The animation can be seen here. As you scroll, the header shape changes and resizes. I have tried doing this with svg animate, div rotation animate, etc. with no luck.
Any help would be appreciated.
Normally we don't provide full solutions for questions, but I had some free time and this was a pretty fun project. If my answer works for you I hope you'll accept it.
I'm sure there are more efficient ways to do this (manipulating an SVG for example), but I kept this as succinct as I possibly could. This is using CSS and Javascript / jQuery. I'll let the comments in the javascript portion do the explaining.
HTML
<div id="animation">
<div id="box"></div>
<div id="ang"></div>
</div>
CSS
#animation {
width: 500px;
position: fixed;
top: 0;
left: 50%;
margin-left: -250px;
}
#box {
width: 500px;
height: 125px;
background: #333;
}
#ang {
width: 0;
height: 0;
border-top: 175px solid #333;
border-right: 500px solid transparent;
}
Javascript
$(window).scroll(function() {
var pos = $(window).scrollTop(), // Current scroll position
max = 300, // How quickly we want the animation to finish (in pixels)
box = 50, // Collapsed height of the box
ang = 0; // Collapsed height of the angle
/* Only make changes if we are within the limit of our max variable
* If this condition is not met, the box and angle will be collapsed
* I found this necessary because scrollTop doesn't produce consistent
* values and quite often the box wouldn't fully collapse */
if (pos <= max) {
// Max height - (scroll percentage x (max height - min height))
box = 125 - (pos / max * 75);
ang = 175 - (pos / max * 175);
}
// Adjust the height of the box and the angle
$('#box').css({ 'height': box + 'px' });
$('#ang').css({ 'border-top-width': ang + 'px' });
});
See my JS Bin for a demo.

Get width of an element after the browser has determined its width

I have a pop up box that I want to be perfectly centered on the window. It has the following CSS properties:
#pop_up {
position: fixed;
display: inline-block;
border: 2px solid green;
box-shadow: 0px 0px 8px 5px white;
width: -webkit-max-content;
width: -moz-max-content;
width: max-content;
border-radius: 5px;
background-color: grey;
}
I also have some jQuery stuff that sets this element's left and top properties.
$(document).ready(function() {
window_height = $(window).height();
window_width = $(window).width();
pop_up_height = $('#pop_up').outerHeight();
pop_up_width = $('#pop_up').outerWidth();
pop_up_left = (window_width / 2) - (pop_up_width / 2);
pop_up_top = (window_height / 2) - (pop_up_height / 2);
$('#pop_up').css('left', pop_up_left);
$('#pop_up').css('top', pop_up_top);
});
I had it alert me of all of the variables and the window variables were right but for pop_up_height and pop_up_width it would alert me '4'. This obviously means that it is only getting the border. If I change it to .innerHeight(); and .innerWidth(); it alerts '0'. So, it is returning the width before the browser decides according to my width: max-content; property. Trying to figure how to get the width after the browser auto's it.
Also, when I specify a left property does it position the element according to the border or to the actual inside of the element? So if I gave an element 2px border and a left of 20px, would the border be 20px from the left or the actual inside of the element? Just a side question.
function popCenter()
{
$('#pop_up').css({'top':($(window).height()-$('#pop_up').height())/2,'left':($(window).width()-$('#pop_up').width())/2});
}
$(document).ready(function() {
popCenter();
})
$(window).resize(function() { //if resize the window, keep the selector in center;
popCenter();
})
No the border will not be 20 px.
And the element will stick to left .
Try using $("#pop_up").width(); and .height()

resize image to browser proportionally checking width and height

I'm building a fluid website in which an image must scale to a maximum size depending on the viewport of the browser (minus some margins). I don't want the image to crop or lose its original proportions, so depending on the width or height it should resize to the maximum size possible without cropping.
I wrote some javascript code, but since I'm not a hardcore coder I was wondering how to fix this in the right way. The script works, but has a bug when resizing. It seems that it only processes one if statement when resizing the browser window.
function setSizes() {
var margin_top = 100;
var margin_right = 85;
var margin_bottom = 10;
var margin_left = 85;
// get image width and height
var img_w = $('.gallery_img').width();
var img_h = $('.gallery_img').height();
// calculate viewport width and height
var vp_w = $(window).width() - margin_right - margin_left;
var vp_h = $(window).height() - margin_top - margin_bottom;
//
if (vp_w <= img_w || vp_w > img_w) {
// new width
var img_w_new=vp_w;
// calculate new height
var img_h_new=Math.round((img_h*img_w_new) / img_w);
}
//
if (vp_h <= img_h || vp_h > img_h) {
// new height
var img_h_new=vp_h;
// calculate new width
var img_w_new=Math.round((img_w*img_h_new) / img_h);
}
// change image width and height to new width and new height
$('.gallery_img').width(img_w_new);
$('.gallery_img').height(img_h_new);
}
// onload
$(window).load(function(){ setSizes(); });
// on resize
$(window).bind("resize", function() { setSizes(); });
I searched for a solution for quite some time, but most scripts I found only check and change the width.
Does somebody know how to fix this?
Thanx!
this might be a lame answer but why don't you just use css width setting?
see http://jsfiddle.net/dXm4r/
I think this is a wrong approach? It would be more natural to define width of enclosing container in percents and than define width 100% on image. Something like this:
div.img-container {
width: 30%;
}
div.img-container img {
display: block;
width: 100%;
}
<div class="img-conatiner">
<img src="...
</div>
Please pay attention to the fact that in img CSS rule there is no height specified, this will allow browsers to properly scale image without loosing quality.
You have a line to change the width; simply add a line to change the height, based on your height variable. You can figure out what the height should be by dividing the new width by the old width. Basically, that is the multiple of widths in the new width, which is equal to the multiple of heights in the new height. Therefore, if you multiply that number to the old height, you would get the new height.
Here is the equation you could use:
img_h_new = (img_w_new / img_w) * img_h;
And this is the function you could use with your width function:
$('.gallery_img').height(img_w_new);
http://blog.francois-becker.net/post/2012/08/16/HTMLCSS-container-of-a-maximized-image
you can done it by css ,just apply this css to your image element
.img { /* image*/
position: absolute;
top: 10px;
right: 85px;
bottom: 10px;
left: 85px;
width: calc( 100% - 170px); /* 170 = marging left + right*/
height: calc(100% - 20px); /* 20px = marging top + bottomt*/
background-size: cover;
box-sizing: border-box;
padding: 0px;
}
body { /* container*/
margin: 0px;
padding: 0px;
height: 100%
width:100%;
overflow:hidden;
}
<html>
<body>
<img class="img" src="http://kingofwallpapers.com/picture/picture-004.jpg" > </img>
</body>
</html>

Categories

Resources