CSS -calc() or JQuery calc() not working for top - javascript

I have four absolute positioned divs on the screen which need to maintain their positions in a ratio at all the resolutions.
div1 - height 150px, top 0px
div2 - height 30%, top 150px
div3 - height 50px, top (30% + 150px)
div 4 - height (70% - 200px), top (30% + 200px)
Working
var calcHeight;
calcHeight = attr["#value"].split('+');
$CompFrame.css('height', calcHeight[0].trim()).css('height', "+=" + calcHeight[1].trim());
Not Working
var calcTop;
calcTop = attr["#value"].split('+');
$CompFrame.css('top', calcTop[0].trim()).css('top', "+=" + calcTop[1].trim());
Code for "-" is also present
I can't use floats due to design reasons

Actually it does work. The jquery calc() implementation

Related

Increment negative value of property based on window size by less than 1px

This question is very similar with other.
The only difference (and for me is a huge difference because I cannot figure it out) is the value of the CSS value increment.
I have an element on the page with negative margin and in the other question I wanted it to increment by 1 pixel each time the screen was larger by 1 pixel, starting on 1400px wide upwards.
.element {
margin-left: -195px;
}
So, if the window size was 1440px wide the margin-left of the element should be -195px, if the window size was 1441px wide the margin-left of the element should be -194px or if the window size was 1451px wide the margin-left of the element should be -184px and so on.
The answers were awesome and I got it resolved (with CSS or javaScript).
.........................
However now that is implemented I noticed that instead of 1 pixel the element's margin needs only 0.1 pixels of increment:
So:
if window size is 1440px wide the margin-left of the element should be -195px.
If the window size is 1441px wide the margin-left of the element should be -194.9px
or if the window size is 1452px wide the margin-left of the element should be -193.8px and so on.
Starting at 1400px wide upwards.
I am aware that the questions are very similar. However I feel this one is a different level somehow.
IMPORTANT NOTE: What I want is a dynamic value for the margin-left that increases based on screen size and not a kind of media query which would make the value always remain the same between an interval of screen sizes. What I want would force me to add a massive number of media queries.
Is this possible with javaScript or jQuery? (or even CSS?)
CSS version:
#media screen and (min-width: 1440px) {
.element {
margin-left: calc(-195px + (100vw - 1440px) * 0.1);
}
}
JS version:
var element = $('.element'), windowWidth, x;
$(window).resize(function () {
if ($(window).width() > 1440) {
windowWidth = $(window).width();
x = (windowWidth - 1440) * 0.1;
element.css('margin-left', -195 + x);
} else {
element.css('margin-left', -195)
}
});
$(window).trigger('resize');
CODEPEN EXAMPLE (CSS)
CODEPEN EXAMPLE (JS)
This code can work, but I don't think that this is the best way to do it ...
var elements = document.getElementsByTagName('element');
window.onresize = function(){
if (window.innerWidth >= 1400) {
var margin, i;
margin = -195 - (0.1*(window.innerWidth - 1400));
for (i=0; i < elements.length; i++) {
elements[i].style.marginLeft = margin + "px";
}
}
}

What is offsetHeight, clientHeight, scrollHeight?

Thought of explaining what is the difference between offsetHeight, clientHeight and scrollHeight or offsetWidth, clientWidth and scrollWidth?
One must know this difference before working on the client side. Otherwise half of their life will be spent in fixing the UI.
Fiddle, or inline below:
function whatis(propType) {
var mainDiv = document.getElementById("MainDIV");
if (window.sampleDiv == null) {
var div = document.createElement("div");
window.sampleDiv = div;
}
div = window.sampleDiv;
var propTypeWidth = propType.toLowerCase() + "Width";
var propTypeHeight = propType + "Height";
var computedStyle = window.getComputedStyle(mainDiv, null);
var borderLeftWidth = computedStyle.getPropertyValue("border-left-width");
var borderTopWidth = computedStyle.getPropertyValue("border-top-width");
div.style.position = "absolute";
div.style.left = mainDiv.offsetLeft + Math.round(parseFloat((propType == "client") ? borderLeftWidth : 0)) + "px";
div.style.top = mainDiv.offsetTop + Math.round(parseFloat((propType == "client") ? borderTopWidth : 0)) + "px";
div.style.height = mainDiv[propTypeHeight] + "px";
div.style.lineHeight = mainDiv[propTypeHeight] + "px";
div.style.width = mainDiv[propTypeWidth] + "px";
div.style.textAlign = "center";
div.innerHTML = propTypeWidth + " X " + propTypeHeight + "( " +
mainDiv[propTypeWidth] + " x " + mainDiv[propTypeHeight] + " )";
div.style.background = "rgba(0,0,255,0.5)";
document.body.appendChild(div);
}
document.getElementById("offset").onclick = function() {
whatis('offset');
}
document.getElementById("client").onclick = function() {
whatis('client');
}
document.getElementById("scroll").onclick = function() {
whatis('scroll');
}
#MainDIV {
border: 5px solid red;
}
<button id="offset">offsetHeight & offsetWidth</button>
<button id="client">clientHeight & clientWidth</button>
<button id="scroll">scrollHeight & scrollWidth</button>
<div id="MainDIV" style="margin:auto; height:200px; width:400px; overflow:auto;">
<div style="height:400px; width:500px; overflow:hidden;">
</div>
</div>
To know the difference you have to understand the box model, but basically:
clientHeight:
returns the inner height of an element in pixels, including padding but not the horizontal scrollbar height, border, or margin
offsetHeight:
is a measurement which includes the element borders, the element vertical padding, the element horizontal scrollbar (if present, if rendered) and the element CSS height.
scrollHeight:
is a measurement of the height of an element's content including content not visible on the screen due to overflow
I will make it easier:
Consider:
<element>
<!-- *content*: child nodes: --> | content
A child node as text node | of
<div id="another_child_node"></div> | the
... and I am the 4th child node | element
</element>
scrollHeight: ENTIRE content & padding (visible or not)
Height of all content + paddings, despite of height of the element.
clientHeight: VISIBLE content & padding
Only visible height: content portion limited by explicitly defined height of the element.
offsetHeight: VISIBLE content & padding + border + scrollbar
Height occupied by the element on document.
* offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar.
* clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin.
* scrollHeight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar. The height is measured in the same way as clientHeight: it includes the element's padding, but not its border, margin or horizontal scrollbar.
Same is the case for all of these with width instead of height.
My descriptions for the three:
offsetHeight: How much of the parent's "relative positioning" space is taken up by the element. (ie. it ignores the element's position: absolute descendents)
clientHeight: Same as offset-height, except it excludes the element's own border, margin, and the height of its horizontal scroll-bar (if it has one).
scrollHeight: How much space is needed to see all of the element's content/descendents (including position: absolute ones) without scrolling.
Then there is also:
getBoundingClientRect().height: Same as scrollHeight, except that it's calculated after the element's css transforms are applied.
Offset Means "the amount or distance by which something is out of line". Margin or Borders are something which makes the actual height or width of an HTML element "out of line". It will help you to remember that :
offsetHeight is a measurement in pixels of the element's CSS
height, including border, padding and the element's horizontal
scrollbar.
On the other hand, clientHeight is something which is you can say kind of the opposite of OffsetHeight. It doesn't include the border or margins. It does include the padding because it is something that resides inside of the HTML container, so it doesn't count as extra measurements like margin or border. So :
clientHeight property returns the viewable height of an element in
pixels, including padding, but not the border, scrollbar or margin.
ScrollHeight is all the scrollable area, so your scroll will never run over your margin or border, so that's why scrollHeight doesn't include margin or borders but yeah padding does. So:
scrollHeight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using
a vertical scrollbar. The height is measured in the same way as
clientHeight: it includes the element's padding, but not its border,
margin or horizontal scrollbar.

jQuery - resizing image to fit div [duplicate]

This question already has answers here:
Resize an image to fit in div
(5 answers)
Closed 9 years ago.
I have divs varying in height and width and wish for my images to be automatically resized to fill these divs 100%, and then of course centred.
At the moment my images are set to width 100% and then using the jQuery below centred, but this only works for images where the height are more than the div once resized.. how would I make it 100% for both height and width and center also.. completely filling the div (even if this means stretching the image)!
Thanks.
$('img.shelf-img').each(function(i, item) {
var img_height = $(item).height();
var top_margin = -(img_height / 2);
$(item).css({
'top': '50%',
'margin-top': top_margin
});
});
Use CSS to set both the Width and Height of the image to 100% and the image will be automatically stretched to fill the containing div, without the need for jquery.
Also, you will not need to center the image as it will already be stretched to fill the div (centered with zero margins).
HTML:
<div id="containingDiv">
<img src="">
</div>
CSS:
#containingDiv{
width: 200px;
height: 100px;
}
#containingDiv img{
width: 100%;
height: 100%;
}
That way, if your users have javascript disabled, the image will still be stretched to fill the entire div width/height.
OR
The JQuery way (SHRINK/STRETCH TO FIT - INCLUDES WHITESPACE):
$('img.shelf-img').each(function(i, item) {
var img_height = $(item).height();
var div_height = $(item).parent().height();
if(img_height<div_height){
//IMAGE IS SHORTER THAN CONTAINER HEIGHT - CENTER IT VERTICALLY
var newMargin = (div_height-img_height)/2+'px';
$(item).css({'margin-top': newMargin });
}else if(img_height>div_height){
//IMAGE IS GREATER THAN CONTAINER HEIGHT - REDUCE HEIGHT TO CONTAINER MAX - SET WIDTH TO AUTO
$(item).css({'width': 'auto', 'height': '100%'});
//CENTER IT HORIZONTALLY
var img_width = $(item).width();
var div_width = $(item).parent().width();
var newMargin = (div_width-img_width)/2+'px';
$(item).css({'margin-left': newMargin});
}
});
The JQuery way - CROP TO FIT (NO WHITESPACE):
$('img.shelf-img').each(function(i, item) {
var img_height = $(item).height();
var div_height = $(item).parent().height();
if(img_height<div_height){
//INCREASE HEIGHT OF IMAGE TO MATCH CONTAINER
$(item).css({'width': 'auto', 'height': div_height });
//GET THE NEW WIDTH AFTER RESIZE
var img_width = $(item).width();
//GET THE PARENT WIDTH
var div_width = $(item).parent().width();
//GET THE NEW HORIZONTAL MARGIN
var newMargin = (div_width-img_width)/2+'px';
//SET THE NEW HORIZONTAL MARGIN (EXCESS IMAGE WIDTH IS CROPPED)
$(item).css({'margin-left': newMargin });
}else{
//CENTER IT VERTICALLY (EXCESS IMAGE HEIGHT IS CROPPED)
var newMargin = (div_height-img_height)/2+'px';
$(item).css({'margin-top': newMargin});
}
});
If you want to keep the image ratio, I would set max-height and max-width to 100%. Here's a sample to show how that works. That will effectively shrink images that are larger than the div, but it will keep the aspect ratio.
For images that are smaller than the div, you will have to scale up with JavaScript. The basic algorithm is like so:
Find the aspect ratio of the image (width / height)
Find the aspect ratio of the div (width / height)
If the image's aspect ratio is less than the div's, set the image's height to 100%
If the image's aspect ratio is greater than the div's, set the image's width to 100%
Whichever dimension is not set, set it to auto
Obviously, you could use this algorithm for scaling up or down, but if you can be guaranteed that your div will always be smaller than your image, you can use the simpler CSS solution.
It looks like you've got code to do centering, so I'll leave that to you.

Handling negative-position images with overflow:auto

Consider the following markup: http://jsfiddle.net/gbWgH/. Because the list overflows its container and overlaps with the text below, I'd like it to be scrollable instead, so I set it to overflow:auto. However, this cuts off parts of the image: http://jsfiddle.net/gbWgH/1/. Removing this rule make the image appear properly.
How can I make the text scrollable without cutting off the image? Is the simplest option to just calculate the coordinates manually using Javascript, as suggested in this answer?
img {position:relative; top : 20px; left : 20px;}
I ended up just resorting to Javascript. Here, an image is positioned 50 pixels to the left and 40 pixels above a li with id "myli", inside a ul with id "myul", by calculating an offset from the li's absolute position within the page body. Note that you have to account for the amount the ul has been scrolled.
var img = document.createElement("img");
img.src = ...
var li = document.getElementById("myli");
var scrollTop = document.getElementById("myul").scrollTop;
img.style.left = li.offsetLeft - 50 + 'px';
img.style.top = li.offsetTop - 40 - scrollTop + 'px';
img.style.position = 'absolute';
document.body.appendChild(img);

element.height returns visible height - I want total?

So apparently this is only happening to me - and I can't think why but if it works, I'm happy :)
I have a full screen slideshow and I have created a function that will vertically center any images that are too large.
function fixImages(){
maxheight = $('.index-slide-container').height();
$('.index-slide-container img').each( function(index, ele){
if (ele.height > maxheight){
offset = ( maxheight - ele.height ) / 2;
$(ele).css('top', offset + 'px');
}
});
}
fixImages();
However, ele.height returns the height of the visible part of the image (the height of it's container, as it has overflow:hidden, even though when I console.log(ele) and expand the element, 'height' is clearly the correct value.
I have also tried $(ele).height(), $(ele).css('height'), $(ele).outerHeight() and ele.clientHeight; all of which return the same.
Thanks
I made some tests, and $('img').height(); is giving me the right height of the picture.
If you wish to center the picture vertically why don't you use the absolute positioning with css like this for example :
.index-slide-container img {
position:absolute;
top:50%;
}
And than, you could set the negative margin programmatically with jQuery :
$('.index-slide-container img').each( function(i, e){
var height = $(e).height() / 2;
$(e).css({'margin-top':'-'+height});
});

Categories

Resources