Width of div changes when position becomes fixed from relative - javascript

The width of the div "topNav" changes by few pixels when its position style is changed from relative to fixed. I found a jquery plugin (http://imakewebthings.github.com/jquery-waypoints/) which can perform the same functionality I'm looking for elegantly, but I feel it is a overkill for this purpose.
EDIT: My question is how to avoid changing the div sizes.
Check out the code at :
http://jsbin.com/azace5/edit

You need to remove the page's "default margin". This will do it in "every browser":
html, body {
margin: 0;
padding: 0
}
See: http://jsbin.com/azace5/2

Or you can add a minimum width.
min-width:600px;

Related

How to set height in CSS from JavaScript Variable?

So, I am using the Slick slider and wanted to apply some code only when the slider is active.
.specialist-description-wrapper {
height: 0rem;
}
.slick-current.slick-active .specialist-description-wrapper {
height: 20rem;
}
But the problem is, I don't want to have a fixed height. I want an "Auto" height so if my content gets bigger then it'll fit automatically. If I try to make height from 0rem to Auto then "Transition" doesn't work.
So, I have decided to use JavaScript to calculate the height of the element.
let descriptionWrapper = document.querySelector(".slick-current.slick-active .specialist-description-wrapper")
let height = descriptionWrapper.offsetHeight
descriptionWrapper.style.height = height;
But it's not working for me. Did I miss something?
Keeping the height to auto will only take height used by itself and will not take full height.
To make the height responsively adjust according to the parent's height, you can use
height: 100%;
This will make the element take all the height of its parent element.
But still, if anything breaks, you can adjust the content of the element. Because the 100% height is important.
Also, you have not provided enough code regarding your markup. Please always provide the code so that everyone can write better answers for you.

Setting the height of a button as a % of the window

I'm trying to set the height of a button as a % of the user's window. It seems this works :
#mybutton {
padding: 10%;
}
But obviously doesn't quite achieve what I need (in addition, it's not responsive to the browser's size).
This doesn't work :
#mybutton {
height: 10%;
}
I've also tried doing it with javascript (I really don't master it), but none of those two tries work either.
document.getElementById('mybutton').style.height = "10%";
document.getElementById('mybutton').style.height = window.outerHeight / 10;
How can I do that ?
PS : I've also tried with fixed values (100px) to see if I could change the height, and it seems I can't at all.
NB : I'd like it to be responsive to the user's window, meaning that if I reduce the size of my browser, the button should keep a height of 10% of it.
Thanks.
You can use viewport units:
#mybutton {
height: 10vh;
}
Viewport-relative lengths are supported by all modern browsers.
Though the answer has been selected I wanted to note three things here.
Note #1
#mybutton {
height:10%;
}
does not work because the height is relative to the parent and the parents, html and body, are not 100%. Checkout this fiddle, http://jsfiddle.net/3sLafksx/1/
Note #2
The reason padding worked is because padding is not relative to the parent's height but to the parent's width. Which in case of a div element or plainly in the body is 100% of the window size.
Refer: https://stackoverflow.com/a/8211457/1799502 and http://www.w3schools.com/cssref/pr_padding.asp
Note #3
Using the viewport height vh and viewport width vw units is a very good idea but #rnevius was not kidding when he said all modern browsers, you need at least IE9 or Android 4.4
IF your element is a span, it won't work like you wish, but using a div, your code will work.
document.getElementById('b').style.height = (window.outerHeight / 10) + 'px';
Using css, your button will be X% of your parent container, so if you have a parent container with 300px height, your button'll be 30px height (using height: 10%).
You can also use the vh unit like #rnevius pointed out. But remember that a span won't work as you want, because it isn't a block element. (unless you force it by using display: (inline-)block).
Try putting a !important
#mybutton {
height: 10% !important;
}

constant distance to baseline while dynamically changing font-size - html - text element

As the title says, I try to fix a text element to the baseline while dynamically changing its font-size on window resize.
I made a jsfiddle to illustrate. The problem is, when resizing the window, the distance to the bottom of the window is not constant.
<div class="foo">text</div>
<script>
var onResizeFunction = function() {
var newFontSize = Math.floor(0.2 * $(window).width());
$(".foo").css("font-size", newFontSize);
};
onResizeFunction();
$(window).resize(function() {
onResizeFunction();
});
</script>
I tried to fix it like that.
.foo {
position:fixed;
bottom: 0;
}
Obviously the problem is the "hitbox" of the text element. Anyway, maybe somebody knows a nice css trick or workaround?
Its running in angular, so no fancy jquery allowed;)
EDIT:
Its about the distance from the bottom of the text element to the bottom of the window. This need to be constant.
The problem here is your line-height in combination with the font you use. As you notice you set the bottom to 0, yet the text is not aligned with the bottom of the window, as you would expect.
This can be solved by setting the line height to a value without a unit. This way the line height will be relative to the font size. One would expect that setting the line height to one would solve this, but this depends on the font, and how much of it's available height it uses.
If you experiment a little you should be able to find the sweet spot though. It won't be 100% accurate, but pretty close. I updated your fiddle as follows, and as you can see with the help of the ruler I added it comes pretty close:
.foo {
position:fixed;
font-family: arial;
bottom: 10px;
line-height: .7; /* this will depend on the used font */
}
https://jsfiddle.net/u6bd9qfp/2/

How to set an element's width equal to window's width?

Using:
$(my_div).width(window.innerWidth)
Does not provide the desired result, because it does not account for the vertical scrollbar, so the element overflows the window, creating a horizontal scrollbar, as illustred below.
Illustration http://dl.dropboxusercontent.com/u/62862049/Screenshots/om.png
You could use width:100%
<div style="width:100%;height:1500px;background:red"></div>
Demo
window.innerWidth includes the width of the vertical scrollbar in some versions of Firefox:
https://developer.mozilla.org/en-US/docs/Web/API/window.innerWidth
however, w3schools seems to disagree (it says it doesn't include the width of the scrollbar):
http://www.w3schools.com/jsref/prop_win_innerheight.asp
There's even a bug concerning this in the Mozilla bug tracker:
https://bugzilla.mozilla.org/show_bug.cgi?id=156388#c14
The confusion above has been cleared a bit with CSS3, which has a specific property to calculate widths, box-sizing. Set box-sizing like this:
box-sizing: border-box
Which does the following (quoted from w3schools):
The specified width and height (and min/max properties) on this element determine the border box of the element. That is, any padding or border specified on the element is laid out and drawn inside this specified width and height. The content width and height are calculated by subtracting the border and padding widths of the respective sides from the specified 'width' and 'height' properties
You can use width:100% as noted, but bear in mind that this will ALSO include any extra spacing and padding you got - however, in CSS3-enabled browsers, this is resolved with the correct box-sizing property, as noted above. So, if you got, say a div like:
<div style="width:100%; padding: 20px;">
<div style="width:100%; background:red">Test</div>
</div>
The inner div will go off-bounds according to the CSS21 spec. Here's a jsFiddle that illustrates this problem.
So, make sure that you don't have any padding to avoid such issues.
If you want to use jQuery to get the width of the window, you could use jQuery's width() method (or css("width")).
Could you use
$(my_div).css('width', '100%');
?
$(my_div).css("width", "100%");
or
#my_div {
width: 100%;
}
You're also probably going to want to make sure your body or parent div has no padding or margin:
body {
padding: 0;
margin: 0;
}

Dynamic Background Scrolling

Here's a link to what I'll be referring to.
I'm having some trouble getting the background image to work the way I'd like it to.
I want the background to auto resize based on the width of the window, which it is already doing correctly. If you make your window smaller you'll see the background shrink with it.
Here's the issue. If you make your window wide (short) then the background will resize and go too high so you can't see the top of the background anymore (since the background is bottom positioned).
I want the background to be top position when you are at the top of the page, and as you scroll down it will slowly move to be bottom positioned. Sort of like the effect of an Android phone's background when you move left and right. Of course, keep in mind that I still want the background to auto-resize when you make the window smaller.
html {
background-color: #70d4e3;
height: 100%;
}
body {
height: 100%;
}
.background {
margin-top: 45px;
width: 100%;
position: fixed;
bottom: 0;
left: 0;
z-index: -9999;
}
.banner {
margin: 0px auto;
width: 991px;
margin-bottom: -9px;
}
.content {
background: url("http://i.imgur.com/daRJl.png") no-repeat scroll center center transparent;
height: 889px;
margin: 0 auto;
width: 869px;
}
.innerContent {
padding: 30px;
}
<img src="http://i.imgur.com/6d5Cm.jpg" alt="" class="background" />
<div class="banner">
<img src="http://i.imgur.com/JptsZ.jpg" alt="" />
</div>
<div class="content">
<div class="innerContent">
testing
</div>
</div>
Maybe some javascript or jquery would be needed to achieve this.
Well, this was fun, thanks!
I hope you don't mind me taking the liberty to use percentages to make my life a little bit easier and possibly the script slightly more robust since I can reliably use floats with percentages.
What I did is make the layout, html and css comply with the rules you need for the bg to be animated properly, they stayed largely the same from what you had.
Then it was just a question of figuring out the calculations needed with the right properties to figure out the percentage you were from the top, the *20 is actually the amount of space 'left' to fill by the background image in percentages (as the background height is 80%).
They I moved the calculations to a function so I could call that on scroll and on window resize, making sure it's initiated on any event that modifies the window somehow...
Didn't do extensive testing but it worked in Chrome and I'm tired :p
I believe this is what you are looking for:
http://jsfiddle.net/sg3s/RSqrw/15/ See edit 2
If you wanted this the other way arround just make the page background start at the top and modify that:
http://jsfiddle.net/sg3s/RSqrw/14/ See edit 2
Edit:
As a bonus, and since I had never actually written jquery script as a 'plugin', I decided to convert this into one. What I came up with should be easy to implement and use!
http://jsfiddle.net/sg3s/RSqrw/52/ See Edit 3
Functionality successfully tested in Chrome, Firefox 3.6, IE9 + compatibility mode
Edit 2:
Reading the question again checking if I did it right I noticed I didn't quite do what you want, so I updated the link in the first edit which gives you a plugin in which you can have several options for the scrolling background. It retains my 'old' interpetation while also doing what you want... Read comments in code for some extra descriptions.
Edit 3:
As I went to work today I was bothered with the fact that my plugin 'try' was a little bloated. And as you mentioned in the comment it didn't quite fit the requirements.
So I rewrote it to only do what you want and not much more, tested in Chrome Firefox, IE9 +compat etc etc.. This script is a lot cleaner.
http://jsfiddle.net/sg3s/vZxHW/
You can chose to make the background stick to the top or bottom if the height fits in the window. Nothing else, but that is already more than enough to do some pretty cool stuff :p
An exact solution: Fiddle: http://jsfiddle.net/srGHE/2/show/
View source
Thanks for the challenge. See below for the solution, which is complying with all requirements, including recommended yet optional (with steps on how to remove these) features. I only show the changed parts of your page, with an explanation after each section (CSS, HTML and JavaScript):
CSS (changes):
html,body{
margin: 0;
height: 100%;
padding: 0;
}
body{
background-color: #70d4e3;
}
#background { /*Previously: .background*/
/*Removed: margin-top: 45px;
No other changes*/
}
#banner /*Previously: .banner; no other changes */
#content /*Previously: .content; no other changes */
#innerContent /*Previously: .innerContent; no other changes */
Explanation of CSS revisions:
margin-top:45px at the background is unnecessary, since you're absolutely positioning the element.
All of the elements which are unlikely to appear more than once should be selected via the id (#) selector. This selector is more specific than the class selector.
HTML (changes):
All of the class attributes have been replaced by id. No other changes have been made. Don't forget to include the JQuery framework, because I've implemented your wishes using JQuery.
JavaScript (new):
Note: I have added a feature which you didn't request, but seems logical. The code will automatically reserve sufficient margin at the left side of the window in order to always display the background. Remove anything between the marked comments if you don't want this feature.
$(document).ready(function(){
//"Static" variables
var background = $("#background");
var marginTop = parseFloat(background.css("margin-top")) || 0;
var bannerWidth = $("#banner").width(); /*Part of auto left-margin */
var extraContWidth = (bannerWidth - $("#content").width())/2; /*Same as above*/
function fixBG(){
var bodyWidth = $("body").width();
var body_bg_width_ratio = bodyWidth/1920;
var bgHeight = body_bg_width_ratio * 926; //Calcs the visible height of BG
var height = $(document).height();
var docHeight = $(window).height();
var difHeight = bgHeight - docHeight;
var scrollDif = $(document).scrollTop() / (height - docHeight) || 0;
/*Start of automatic left-margin*/
var arrowWidth = body_bg_width_ratio * 115; //Arrow width
if(bodyWidth - bannerWidth > arrowWidth*2){
$("body > div").css("margin-left", "auto");
} else {
$("body > #banner").css("margin-left", arrowWidth+"px");
$("body > #content").css("margin-left", (arrowWidth+extraContWidth)+"px");
}
/*End of automatic left-margin*/
if(difHeight > 0){
background.css({top:(-scrollDif*difHeight-marginTop)+"px", bottom:""});
} else {
background.css({top:"", bottom:"0"});
}
}
$(window).resize(fixBG);
$(window).scroll(fixBG);
fixBG();
});
Explanation of the JavaScript code
The size of the background is determined by calculating the ratio of the background and document width. The width property is used, because it's the most reliable method for the calculation.
Then, the height of the viewport, document body and background is calculated. If applicable, the scrolling offset is also calculated, to prepare the movement of the background, if necessary.
Optionally, the code determines whether it's necessary to adjust the left margin (to keep the background visible at a narrow window).
Finally, if the background arrow has a greater height than the document's body, the background is moved accordingly, taking the scrolling position into account. The arrow starts at the top of the document, and will move up as the user scrolls (so that the bottom side of the arrow will be the bottom of the page when the user has fully scrolled down). If it's unnecessary to move the background, because it already suits well, the background will be positioned at the bottom of the page.
When the page has finished loading, this functionality is added to the Resize and scroll events, so that the background is always at the right location.
If you've got any other questions, feel free to ask them.
well, I'm not sure if I understand you and why do you want to do that, but you can try adding 2 backgrounds (see http://www.css3.info/preview/multiple-backgrounds/ ), one with the top bg and another with the bottom bg but I think that if the page is not too long it will cause issues, so the other answer with pure CSS is as follows: first add 3 horizontal divs with 100% width. Top div will have your top bg and its height, middle div will be transparent and auto height and bottom div will have your bottom bg and its height. All divs will have a 0 z-index. Then create a higher z-index div to act as a container and you'll be set. If I understand your question right, that's the close I can think of to achieve that. This being said, I'm pretty sure you can do this with JQuery with way better results
Using jQuery I was able to give you what I think you're asking for:
$(window).scroll(function() {
var h = Math.max($(document).height(), $(window).height());
var bottom = h - $(".background").height() - $(window).height();
$(".background").css("top", (($(window).scrollTop() / h) * bottom) + "px");
});
EDIT: Forgot to account for the way scrollTop reports position.
Or maybe:
.background {
margin-top: 45px;
max-width: 100%;
position: fixed;
bottom: 0;
left: 0;
z-index: -9999;
max-height: 100%;
}
I reccomend using jQuery Background Parallax
http://www.stevefenton.co.uk/Content/Jquery-Background-Parallax/
The function is as simple as
$("body").backgroundparallax();
Ask if you don't get it to work.
#abney; as i understand your question may that's you want http://jsfiddle.net/sandeep/RSqrw/60/
you need only css for this:
#background {
position: fixed;
width: 100%;
height:100%;
top: 0;
left:0;
z-index: -1;
}
The solution to your issue is a nice little lightweight plugin by Scott Robin. You can get more info, download it, and make your life easier for all of your projects by visiting his project page here.

Categories

Resources