DIV float with page - css

How can I get a DIV to float with my page? Currently I have it setup like this: http://g2n.us/Dev/TheHabbos_6975/
I can do this by using the following CSS:
Code:
.stayStill {
position: fixed;
width: 300px;
}
But how can I get it so when the header scrolls away, the right DIV moves up and stays 10 pixels away from the top and scrolls with the page, unless the header is there?

You need JavaScript to do this.
Your site is already using it, so there should be no problem with using JavaScript to do this.
A couple of tutorials:
http://jqueryfordesigners.com/fixed-floating-elements/
http://css-tricks.com/scrollfollow-sidebar/

This answer uses jQuery
You can put this in your $.ready() function
var int_header_height = 10; //put pixel value height of header here
if ($(document).scrollTop() <= int_header_height) {
$('div.stayStill').css('position','absolute').css('top','0px');
} else {
$('div.stayStill').css('position','fixed').css('top','10px');
}
This also assumes that the div is in a position: relative element below the header. Otherwise you should change the .css('top','0px') to .css('top',int_header_height + 'px')

Related

How do I create CSS scroll effects?

When the user scrolls the website downward and reaches a certain point, I want it to trigger a certain behavior. Example could be a change in text position.
Here's an example of what you are describing using javascript:
function winScroll() {
if (window.pageYOffset > 1000) {
window.alert('You have scrolled down the page more than 1000 pixels');
}
}
window.addEventListener('scroll',winScroll,false);
body {
height: 4000px;
}
<h1>Keep scrolling down...</h1>

CSS positioning with JavaScript-generated divs not working how I expected

First off, I must apologize. CSS positioning has always been the bane of my existence and this is likely something simple that I'm just completely missing...
Anyway, I have a JS script that's generating divs. Each div is within the parent #container which is absolute positioned. CSS below:
#container{
position: absolute;
}
#container div{
position: relative;
}
The function creating the divs is:
function newLine(){
var id_num = ++line;
var _new;
var i;
for(i = 0; i < width; i++){
_new = document.createElement('div');
_new.innerHTML = randomChar();
_new.id = id_num;
_new.style.left = i*10+'px';
_new.style.top = 0;
document.getElementById('container').appendChild(_new);
}
}
Everything above is properly initialized. The left positioning works perfectly. The only issue is the vertical positioning. Instead of all the row displaying next to each other, they're progressively increasing away from the top of the div. I'm sure this is something trivial that I'm completely looking over, but I'm stumped... Help would be very much appreciated!
The rows as position: relative - this lays them out statically and then moves them the specified number of pixels. You want to use absolute positioning.

how to fill div with full height of page in css? (page is taller than 100%) for ajax loading gif background

ok there are several similar questions but not quite anything that I want.
I have few ajax requests on page and I want to show the image in the center of the screen, and its all working OK.
Just to make it look more prominent, I wanted to place that image on a div with translucent background, so its more obvious for the end users. Now comes the tricky part.
I made the div with css like this:
.divLoadingBackground
{
filter: Alpha(Opacity=40); -moz-opacity:0.4; opacity: 0.4;
width: 100%;
height: 100%;
background-color: #333;
position: fixed;
top: 0px;
left: 0px;
}
This fills the page up alright, or, I should say, this fills the viewport. If I scroll the page down, the page is again normal. I want this div to span the ENTIRE LENGTH of the page, no matter how long the page is.
Here is an example mockup of the problem I made to quickly demonstrate:
As you can see, I took the example of SO for the mockup ;) image 1 shows that its okay when it appears. image 2 shows that it goes up with the page on scroll.
I'm a c# developer and css is as alien to me as ancient latin.
How to make this divLoadingBackground div to fill out the entire length of the page?
Many thanks for any help.
If you need any additional info, please comment!
One thing I dont see in your css is z-index. Fixed, although, fixes this problem, sometimes, based on how other divs are positioned, your divLoadingBackground div could end up in one of the divs.
try adding
z-index: 9999;
or something similar and see if it works.
Would have put this in a comment, but it seems I have too low rep to comment.
Where is the .divLoadingBackground div located in the DOM tree? Since it has fixed position, it shouldn't scroll with the page. This makes me belive that the element is too deeply nested. Try putting it right in the body level of the page and see if that helps.
Also, are you sure that some other css directive isn't changing the position attribute to absolute or something?
Also, make sure to use the right DOCTYPE. That has some impact on fixed position elements.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Oh, and ofcourse, fixed position isn't supported in IE6 and below.
I believe you will need JavaScript/jQuery to dynamically set the height of the div in question to the height of the page once rendered.
And if you're entering the world of web, it's time to learn that new language "CSS" as well as perpahs-not-quite-as-daunting JavaScript.
When I needed such a functionality some years ago, I examined how Google Calendar did it.
Basically, they use a timer-driven JavaScript file that checks for the height of the window and adjust the height of a contained DIV tag accordingly (or of an IFRAME tag, just any container tag that you like).
Here is a code snippet from a page I worked on:
<script type="text/javascript">
document.getElementsByTagName("body")[0].style.height = "100%";
document.getElementsByTagName("html")[0].style.height = "100%";
document.getElementsByTagName("body")[0].style.minHeight = "100%";
document.getElementsByTagName("html")[0].style.minHeight = "100%";
function height()
{
try
{
height_iframe();
}
catch(err)
{
}
}
window.onload=height;
// --
var ie6WorkaroundIFrameResize = 1;
function height_iframe()
{
var any = false;
var offset = 300;
var c = document.getElementById("iframecontent");
if ( c!=null )
{
c.style.height = (GetClientHeight()-offset)+"px";
any = true;
var d = document.getElementById("iframeie6");
if ( d!=null )
{
d.style.height = (GetClientHeight()-(offset+ie6WorkaroundIFrameResize))+"px";
any = true;
ie6WorkaroundIFrameResize = 0;
}
}
if ( any )
{
setTimeout( 'height_iframe()', 300 );
}
}
function GetClientHeight()
{
return document.documentElement.clientHeight;
}
</script>
Basically, the script regularly checks for the height of the window via the GetClientHeight() function and adjusts the element in concern ("iframecontent") accordingly.
I subtract some offsets of fixed-height headers and footers.
AFAIK you would need to set the size of this divthrough javascript. I would recommend using jQuery, in this way :
//$(document).height() gives the size of the document
//(as opposed to $(window).height() that would give the size of the viewport
$("div#overlay").css('height',$(document).height());

Large background images using css

How can I load images to cover the whole background like some websites, using CSS. Not the usual background-image property but I want to load the images quickly.
Examples:
http://www.marinayachting.it/
http://alexandraowen.co.nz/
background-image is the only way to place images in CSS. If you want it to be vary large put it on the body element or a container div that fills the entire viewport.
body {
margin: 0;
padding: 0;
width: 100%;
background-image: url('my_big_image.jpg') norepeat;
}
If you use a container div you can set position:fixed; top:0; left:0 and the image will remain stationary when the page scrolls.
There's no magic to it. As far as getting it to load quickly I don't think there's much you can do if it doesn't repeat. If it does repeat then make sure your image is the size of one module. This can be as little as one pixel tall or wide depending on the content.
There is no magic to making a background image load quickly, you just:
Have a fast server.
Compress the image as much as possible.
Make your page HTML small so that the rest can start loading as soon as possible.
Don't have many other images that also has to load.
Don't have a lot of scripts and other external files that has to load.
I found this tutorial helpful. ->
http://css-tricks.com/perfect-full-page-background-image/
Bing is loading a normal background image with a fixed size. It´s not particularly fast (for me...), but perhaps it seems fast because the image is cached after the first time you load it.
You can set the style inline so that the image can start downloading without waiting for any css file to be ready.
If you set an image let's say a picture as a background you need to make it large enough to accommodate large screen sizes. You don't want the experience on your site to be, that your picture repeats multiple times on the screen. Probably at the least width should be 1260px. If background is just a simple gradient, you can cut a small part of it in photoshop and apply it on the body like this:
body {
margin:0;
padding:0;
background:#fff url(your/image/location.jpg) repeat-x scroll 0 0;
}
This method could be applied to divs too, Good luck.
In your second example site, alexandraowen.co.nz, if you took a second to look at the JS they use, you would have seen the following:
// backgrounds --------------------------------------------------------------//
var Backgrounds = {};
Backgrounds.init = function()
{
$('body').each
(
function()
{
var imgsrc = $(this).css('background-image');
if(imgsrc != 'none')
{
imgsrc = imgsrc.slice( imgsrc.indexOf('(') + 1 , -1);
$(this).css('background-image', 'none');
$(this).prepend('');
if($.browser.msie)
{
// ie 7 is the slow kid and we have to strip out quote marks ffs!
$(this).find('div.bg img').attr('src', imgsrc.split('"').join(''));
}
else
{
$(this).find('div.bg img').attr('src', imgsrc);
}
}
}
);
Backgrounds.resizeHandler();
$(window).resize(Backgrounds.resizeHandler);
$('div.bg img').load(Backgrounds.resizeHandler);
}
Backgrounds.resizeHandler = function()
{
var w = $(window).width();
var h = $(window).height();
$('div.bg img').each
(
function()
{
var wr = w / $(this).width();
var hr = h / $(this).height();
var r = Math.max(wr, hr);
var imgw = Math.round($(this).width() * r);
var imgh = Math.round($(this).height() * r);
$(this).width( imgw );
$(this).height( imgh );
var l = Math.round((w/2) - (imgw/2));
$(this).css('margin-left', l+'px');
}
);
}
As well as the HTML on the page:
<body style="background-image: none; ">
If you dig into their scripts a bit more, you can see what they did. But I guarantee you it's nothing faster than just setting the background-image property.
<img id="foo" src="bar" alt=""> with #foo { width: 100%; height: 100%; }(use position: absolute; / position: relative; & z-index for layering as desired)
Here's an old example.

fixed vertical positioning of css within an iframe

I am trying to get my bottom header to stick to the bottom of the screen inside of my iframe application and have it always appear in view for the user even when the page is scrolling. I have no control over the outer iframe as it is on a different domain. The header itself must be inside of the iframe as I have no control outside the iframe. The iframe always expands to the height of its contents so that it has no scrollbars, but the bar still has to be visible in the viewport at all times.
Another thing to note: The iframe height should be the same height as its contents so their is no need for scroll bars
Chrome has a bug that doesn't fix elements with position:fixed if:
a) you use CSS3 transform in any element, and/or
b) you have a child element positioned outside the box of it's parent element
Oddly enough, the bug was reported back in 2009 and it's still open: https://code.google.com/p/chromium/issues/detail?id=20574
You might want to play around with position: fixed;
#element {
position: fixed;
z-index: 1000;
bottom: 0;
}
EDIT:
I'm sorry, I think I miss understood your post. If I'm reading it correctly you want to create a header bar similar to blogger but to keep it always in view of the user when he/she scrolls.
What you can do is create a container div, and then you can nest both your header and iframe inside that container. You can then play around with the positioning, although I'm not sure if the exact behavior that you're looking for is possible without some javascript.
EDIT 2:
After playing around a bit, I got something that I think might help (if I understand your problem correctly).
http://digitaldreamer.net/media/examples/iframe-site.html
http://digitaldreamer.net/media/examples/iframe.html
I had to look for a long time for a possible solution, and I think I have found one that is using the Intersection Observer API to detect the scrolled position of the iframe within the parent document without needing to access the parent document DOM.
I'm creating a bunch of hidden 100px high elements in the iframe. These are positioned absolutely underneath each other so that together they fill the height of the whole iframe document. An intersection observer then observes the intersection between the (top-level document) viewport and each of the hidden elements and calculates the scroll position of the iframe based on the values it returns. A ResizeObserver creates additional hidden elements if the height of the body increases.
This approach assumes that your iframe is always minimum 100px high. If you expect a smaller height, you need to adjust the hidden container height. The reason is that once a hidden container is 100% visible, the intersection observer does not emit the callback while the parent document is being scrolled (since the intersection ratio stays at 1). This is also the reason why I need a lot of small containers rather than observing the intersection with the iframe body itself.
const CONTAINER_HEIGHT = 100;
const threshold = [...Array(CONTAINER_HEIGHT + 1).keys()].map((i) => i / CONTAINER_HEIGHT);
/**
* Registers an intersection handler that detects the scrolled position of the current
* iframe within the browser viewport and calls a handler when it is first invoked and
* whenever the scrolled position changes. This allows to position elements within the
* iframe in a way that their position stays sticky in relation to the browser window.
* #param handler Is invoked when the function is first called and whenever the scroll
* position changes (for example due to the user scrolling the parent document). The
* "top" parameter is the number of pixels from the top of the browser viewport to the
* top of the iframe (if the top of the iframe is above the top of the browser viewport)
* or 0 (if the top of the iframe is below the top of the browser viewport). Positioning
* an element absolutely at this top position inside the iframe will simulate a sticky
* positioning at the top edge of the browser viewport.
* #returns Returns a callback that unregisters the handler.
*/
function registerScrollPositionHandler(handler: (top: number) => void): () => void {
const elementContainer = document.createElement('div');
Object.assign(elementContainer.style, {
position: 'absolute',
top: '0',
bottom: '0',
width: '1px',
pointerEvents: 'none',
overflow: 'hidden'
});
document.body.appendChild(elementContainer);
const elements: HTMLDivElement[] = [];
let intersectionObserver: IntersectionObserver | undefined = undefined;
const resizeObserver = new ResizeObserver(() => {
intersectionObserver = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (entry.intersectionRatio > 0 && (entry.intersectionRect.top > entry.boundingClientRect.top || entry.target === elements[0])) {
handler(entry.intersectionRect.top);
}
}
}, { threshold });
const count = Math.ceil(document.documentElement.offsetHeight / CONTAINER_HEIGHT);
for (let i = 0; i < count; i++) {
if (!elements[i]) {
elements[i] = document.createElement('div');
Object.assign(elements[i].style, {
position: 'absolute',
top: `${i * CONTAINER_HEIGHT}px`,
height: `${CONTAINER_HEIGHT}px`,
width: '100%'
});
elementContainer.appendChild(elements[i]);
intersectionObserver.observe(elements[i]);
}
}
});
resizeObserver.observe(document.documentElement);
return () => {
resizeObserver.disconnect();
intersectionObserver?.disconnect();
elementContainer.remove();
};
}
This example code should create a toolbar that is sticky at the top of the browser viewport:
<div style="position: absolute; top: 0; left: 0; bottom: 0; right: 0; overflow: hidden; pointer-events: none; z-index: 90">
<div id="toolbar" style="position: absolute; top: 0; left: 0; right: 0; pointer-events: auto; transition: top 0.3s">
Line 1<br/>Line 2<br/>Line 3<br/>Line 4<br/>Line 5<br/>Line 6<br/>Line 7<br/>Line 8<br/>Line 9<br/>Line 10
</div>
</div>
<script>
registerScrollPositionHandler((top) => {
document.querySelector('#toolbar').style.top = `${top}px`;
});
</script>
Note that other than what you asked for, this will position the toolbar at the top of the viewport rather than at the bottom. Positioning at the bottom should also be possible, but is slightly more complex. If anyone requires a solution for this, please let me know in the comments and I will invest the time to adjust my answer.

Resources