Is it possible to achive the following configuration in CSS please ?
I have a long page with a footer in the bottom (the footer display property is flex)
In the visible area of the page I need the fixed area to be always in the bottom as long as the scrolling has not reached the footer.
Once the scrolling has reached the footer, the fixed area should scroll up to be on the top of the footer like in the following screenshots:
The fixed area is in the bottom of the visible region of the page.
When scrolling, if the footer is not reached, the fixed are will remain at the bottom of the page
When reaching the footer, the fixed position is on the top of the footer
I tried something like:
FixedArea {
position: fixed;
bottom: 0;
width: 100%;
}
but when I scroll until the footer the fixed region disappears.
You can nest the body content together with the fixed content in a element that has a height: 100vh on it, and overflow: auto on the actual content of that page, in that way the content will scroll independently of the fix element, and once reached the end the body scroll will continue on till the end of page (footer)
I created an example. Try: https://jsfiddle.net/pvviana/wwc8LgLm/
I am changing the div css property "position" at the bottom of page.
Code:
<div class="foo">Hello</div>
<footer>OKAY</footer>
Javascript(Jquery):
var $logo = $('.foo');
$(document).scroll(function() {
$logo.css({position: $(this).scrollTop()>100 ? "relative":"fixed"});
});
Css :
.foo {
position: fixed;
bottom: 0px;
}
Here is a (another) possible jQuery solution.
During scroll, calculate the distance remaining until the bottom of the window, and start setting the bottom style property on your fixed area the height of the footer minus the distance remaining, otherwise make sure it's set (back) to the original, as follows (note, I set the height of the content block to 800px, so make sure you try this so that the result window has a smaller height than that):
var originalBottom = 0; // get this depending on your circumstances
var footerHeight = 72; // get this depending on your circumstances
$(window).scroll(function () { // start to scroll
// calculating the distance from bottom
var distanceToBottom = $(document).height() - $(window).height() - $(window).scrollTop();
if (distanceToBottom <= footerHeight) // when reaching the footer
$("#fixed-area").css('bottom', (footerHeight - distanceToBottom) + 'px');
else // when distancing from the footer
$("#fixed-area").css('bottom', originalBottom + 'px'); // only need to specify 'px' (or other unit) if the number is not 0
});
body {
padding: 0;
margin: 0;
}
#content {
height: 800px;
}
#fixed-area {
position: fixed;
bottom: 0;
padding: 5px;
margin: 5px;
border: 1px solid green;
width: calc(100% - 22px); /* padding (2*5) + border (2*1) + margin (2*5) */
text-align: center;
}
#footer {
height: 40px;
position: relative;
bottom: 0;
padding-top: 20px;
margin: 5px;
border: 1px solid black;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fixed-area">Fixed Area</div>
<div id="content"></div>
<div id="footer">Footer</div>
Related
I need to change the height of a svg on mousewheel/scroll, but while this svg resizes, I need to make the text below follow this scaleY. I've tried implementing a position: relative but this does not work. How can I do that? Here's a PS of what I try to achieve.
Here's a PS of what I have now - images and text are just placeholder.
This is my relevant HTML code:
<div className="main_container">
<div className="main_container_inner">
<div className="img_container">
<img src={img_link} />
</div>
<div className="text_container">
<h1>fvdfv</h1>
<p>fvdfv</p>
</div>
</div>
</div>
This is my relevant CSS code:
.main_container{
display: block;
position: fixed;
width: 100vw;
}
body{
height: 400vh;
}
.main_container .main_container_inner{
display: inline-flex;
width: 33.33%;
flex-direction: column;
}
.main_container img{
width: 100%;
transform-origin: top;
}
This is what I have for now:
As you can see, when I change the scaleY value of the image, the text does not adjust to the new height.
The issue here is the flex containers do not have a setted height property.
So when you scale an image, it is quite hard to set its container height accordingly, so it "pushes" the other divs below. The image simply overflow its container.
I found a way anyway! Because I sticked (maybe for too long) on that weird challenge.
It requires a couple calculations.
I assumed you wish to scale up for the original height of the image to 100% of the viewport height. This assumption may be wrong... I this case, just play with those calculations. You have the example well commented below.
Another thing I noticed is you seem to use React. If so, I guess you should store the img height and its container height in the component state.
I'm leaving that challenge to you ;)
// Get the elements
let main_container = document.querySelector(".main_container")
let imgContainer = document.querySelector(".img_container")
let img = document.querySelector(".img_container img")
// Some global variables to be filled when the image has fully loaded or on window resize
let viewportHeight, scrollHeight, scrollable, currentImgHeight, maxScale
// When the img has loaded...
function imgLoaded(){
// Get some dimentions
viewportHeight = window.innerHeight
scrollHeight = document.documentElement.scrollHeight
scrollable = scrollHeight-viewportHeight
// Calculate the maxScale for an img height == 100% of the viewport
currentImgHeight = img.getBoundingClientRect().height
maxScale = viewportHeight/currentImgHeight
// Set an initial height to the .img_container - Same as the img.
imgContainer.style.height = currentImgHeight+"px"
}
// If the image has already fully loaded (cache), else wait for the load event
if(img.complete){
imgLoaded()
}else{
img.addEventListener("load", imgLoaded)
}
// On window resize
window.onresize = function(){
img.style.transform = "scale(1)"
window.scrollTo(0,0)
imgLoaded()
}
// Scroll handler
function scrollHandler(){
// update the current img height value
currentImgHeight = img.getBoundingClientRect().height
// Calculate a new scale for the img -- The +1 is to avoid a negative value at the bottom of the page
let newScale = scrollable/(scrollable + 1 - document.documentElement.scrollTop)
// Apply the newScale if less or equal to maxScale
let scale = (newScale>maxScale)?maxScale:newScale
img.style.transform = `scaleY(${scale.toFixed(3)})`
// Adjust the img_container, so it pushes the div below
imgContainer.style.height = currentImgHeight+"px"
// Just for this demo...
console.log(imgContainer.style.height,scale.toFixed(3)+"% ")
}
// Add the event listener
document.addEventListener("scroll", scrollHandler)
/* Just for this demo... Styling the SO console which is in the way! */
.as-console{
background: transparent !important;
text-align: right;
}
.as-console-wrapper{
max-height: 1em !important;
border-top: 0 !important;
}
.as-console-row-code{
padding: 0 !important;
border: 0 !important;
}
/* added to your CSS */
*{
box-sizing: border-box;
margin: 0;
padding: 0;
}
/* Your css unchanged */
.main_container {
display: block;
position: fixed;
width: 100vw;
}
body {
height: 400vh;
}
.main_container .main_container_inner {
display: inline-flex;
width: 33.33%;
flex-direction: column;
}
.main_container img {
width: 100%;
transform-origin: top;
}
<div class="main_container">
<div class="main_container_inner">
<div class="img_container">
<img src="https://via.placeholder.com/400" />
</div>
<div class="text_container">
<h1>fvdfv</h1>
<p>fvdfv</p>
</div>
</div>
</div>
Run in full screen mode! or CodePen
I have two divs side by side, the first on about 60% of the page is positioned as "relative" on the left, the second is placed as "absolute" on the right as it is the only way I managed to place them side by side.
The div on the right is only about 10% (measures about 1 view port height) of the full height of the webpage. The div on the left which measures roughly 10 viewport heights defines the full height of the webpage. Hence, I would like to be able to have the right div slide down as the user scrolls down so as to not leave a blank space on the right of the left div below the right div.
The issue is that I can't manage to have the right div set as sticky and scroll down and still keep them right next to eachother at the top when the page first loads. The sticky div will be on top whhile the left div starts just when the sticky div finishes. Basically it behaves the same as if I set both of them relative but I need the right divv to behave as an absolute div before it becomes sticky to preserve the positioning.
With absolute positioning:
.mainbodyfx {
width: 60vw;
padding-left: 10vw;
right: 40vw;
margin-left: 0;
margin-right: 0;
height: 10vh;
}
.floatingfxbuy {
position: absolute;
background-color: transparent;
width: 20vw;
left: 75%;
height:1vh;
}
<div> Content of full height and width slider </div>
<div class=floatingfxbuy> Right div that needs to slide down with scroll </div>
<div class="mainbodyfx"> Left div that defines the height of the whole webpage</div>
With sticky positioning:
.mainbodyfx {
width: 60vw;
padding-left: 10vw;
right: 40vw;
margin-left: 0;
margin-right: 0;
height: 10vh;
}
.floatingfxbuy {
position: sticky;
background-color: transparent;
width: 20vw;
left: 75%;
height:1vh;
}
<div> Content of full height and width slider </div>
<div class=floatingfxbuy> Right div that needs to slide down with scroll </div>
<div class="mainbodyfx"> Left div that defines the height of the whole webpage</div>
So, it's hard to tell exactly what you're asking for but I think I'm close to what you're asking for. Essentially if you want a floating side div you need to treat it as completely separate from the other div. Really as far as the css and html goes the .floatingfxbuy div is separate from the entire page.
If you want the floating div to be absolute positioned until you scroll to a certain height you need to use JavaScript to change the position to fixed for the div when the window scrolls to a certain point.
You also need to have the z-index slightly higher on the floating div so that it doesn't interact with any elements "underneath" it.
Here is a quick example I threw together. Sorry about the terrible colors.
$(document).ready(function() { // at document ready run this function
var $window = $(window); // local variable to window
$window.on('scroll resize', function() { // on window scroll or resize run this function
if ($window.scrollTop() > 50) { // if the top of the window is lower than 50px then add the fix class to the .floating-side-div
$('.floating-side-div').addClass('fix');
} else { // if the top of the window is heigher than 100px remove the fix class
$('.floating-side-div').removeClass('fix');
}
});
});
body {
margin: 0;
/* get rid of some default body styles */
}
.page-container {
min-height: 200vh;
/* set height of page so we can scroll to test */
width: 100%;
background-color: green;
}
.content-div {
width: 60vw;
/* width you suggested */
height: 50vh;
/* random height for content */
margin-left: 10vw;
/* some left margin you want */
background-color: red;
}
.floating-side-div {
height: 10vh;
/* 10% viewport height like you want */
width: 20vw;
/* width you have in your css */
background-color: blue;
position: absolute;
/* to start we want absolute position */
right: 0;
/* put it at the right of the page */
top: 0;
/* put it all the way at the top. you can change this if you want */
z-index: 99;
/* increase z-index so we're over top of the other elements on the page and don't distort the page when scrolling */
}
.floating-side-div.fix {
position: fixed;
/* change from absolute to fix so we 'fix' the div to a spot in the viewport. in this example top: 0, right: 0; */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="page-container">
<!-- our page container -->
<div class="content-div"></div>
<!-- the content div(your .mainbodyfx) -->
<div class="floating-side-div"></div>
<!-- the floating div(your .floatingfxbuy) -->
</div>
I'm trying to add a crosshair-style cursor effect to a div that contains a D3 Datamap. I've got it working using jQuery but the crosshairs seem to overlap their parent div on the bottom and right, but not the top and left.
I've created this fiddle to demonstrate.
I've tried changing the position property of the crosshair div to no avail.
On my page, changing position to absolute seems to correctly confine the crosshairs to the container, but the center point is offset from the cursor (e.pageX, e.pageY). However, I cannot recreate this in the fiddle, as fixed, static, relative, absolute make no difference.
One solution I've found is to set the width and height properties of the container and hairs to fixed values. However, I need the container to be responsive.
First, the vertical and horizontal lines also overlapping the box on the top and left, it was not visible because of the body-viewport ;).
Second, I did some investigation and found out that the best solution would be to place the crosshair-lines inside the map-container which are positioned absolute to the map-container. Therefore we have better control of the position and behavior of the crosshair-lines and the map-container can be flexible aswell!
I added the default cursor for better testing. — https://jsfiddle.net/9r4rtcz9/6/ – code snippet below
//Map Hover Crosshairs
$(function() {
var cH = $('#crosshair-h'),
cV = $('#crosshair-v');
$('.map_wrapper').on('mouseover', function() {
cH.css('visibility', 'visible');
cV.css('visibility', 'visible');
$('.map_wrapper').bind('mousemove', function(e) {
cH.css('top', e.pageY);
cV.css('left', e.pageX);
});
});
$('.map_wrapper').on('mouseout', function() {
cH.css('visibility', 'hidden');
cV.css('visibility', 'hidden');
$('.map_wrapper').unbind("mousemove");
});
});
.map_wrapper {
position: relative;
height: 100px;
width: 300px;
border: 1px solid black;
overflow: hidden;
cursor: default;
}
.hair {
float: left;
position: absolute;
background-color: rgba(100, 100, 100, 0.5);
z-index: 10;
pointer-events: none;
}
#crosshair-h {
width: 100%;
height: 2px;
margin-top: -8px;
visibility: visible;
}
#crosshair-v {
height: 100%;
width: 2px;
margin-left: -8px;
visibility: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="map_wrapper">
<div class="hair" id="crosshair-h"></div>
<div class="hair" id="crosshair-v"></div>
</div>
<p class="datamaps">D3 Data Maps Here</p>
I have a main container DIV for the content of my page, that is horizontally centered:
HTML:
<div id="master_container">
.. my content here ...
</div>
CSS:
#master_container {width: 960px; margin: 0 auto;}
Client wants to have adverts at both sides of the page, outside of the master_container. I tried various CSS to try and position those divs but when window is resized, they overlap with the master_container. Also, I am asked to have them float when the page is scrolled.
Can anyone please direct me to the correct solution? Thanks in advance...
>> DEMO <<
[Note that I used a 700px width for #master_container]
1. Positioning
Most important CSS is the styling and positioning of the adverts, which I have given the class .advertis:
.advertis {
position: fixed; /*creates floating effect */
top: 20px; /* divs will always stay 20px from top */
width: 220px;
padding: 10px;
background: white;
border: #ccc 1px solid;
border-radius: 4px;
}
#left {
margin-left: -613px; left: 50%; /* positioning of left ads */
}
#right {
margin-right: -613px; right: 50%; /* positioning of right ads */
}
I can hear you wonder: how do I calculate the margin that I need? Simple:
Get width of #master_container (including padding) = 720px. Divide it by 2 = 360px. Add the width of the ad (including padding and border) = 242px. 240px + 360px = 600px. Add the space that you want to have between the container and the ad = 11px (in my case).
242px (full width of ad) + 360px (half of container) + 11px (space between ad and container) = 613px (margin needed)
2. Hiding when window too small
Now you want to hide the ads when they don't fit in the window any more. You have options for that:
Media Queries
jQuery (or JavaScript or another of its libraries)
In the first jsFiddle I have used media queries (not supported by all browsers). In this Fiddle, I have used jQuery to get the same effect.
function widthCheck() {
var ads = $(".advertis");
if ($(window).width() < 1225) {
ads.hide();
}
else {
ads.show();
}
}
widthCheck(); // Execute onLoad
$(window).resize(function(){
widthCheck(); // Execute whenever a user resizes the window
});
It's up to you to choose which one you want to use. I'll list a few pros and cons, so you can choose for yourself.
Pros media queries:
modern, progressive
works, even when JS is disabled
Cons:
not supported by all browsers
Pros jQuery:
supported by (as good as) all browsers
Cons:
does not work when JS is disabled
not as progressive as media queries
How about that:
Demo: http://jsfiddle.net/insertusernamehere/Ct5BM/
HTML
<div id="master_container">
<div class="ad left">Advertising</div>
<div class="ad right">Advertising</div>
The real content …
</div>
CSS
<style>
body {
width: 100%;
}
#master_container {
position: relative;
width: 960px;
height: 500px;
margin: 0 auto;
border: 1px solid red;
}
div.ad {
position: absolute;
top: 0px;
width: 200px;
height: 400px;
margin: 0px 0px 0px 0px;
border: 1px solid blue;
}
div.ad.left {
left: -220px;
}
div.ad.right {
right: -220px;
}
</style>
Edit: How it works
When you position the main element relative it's not taken out of its flow within its content but it opens a new space for positioning, z-indexes etc. So a child element within this container which has an absolute position is related to the position of its parent. So in this example the "ad" element has a width if 200px and with left -220px it's moved outside the container on the left side with a little "margin" added.
Here's what I'm trying to accomplish:
I need a button which is positioned a certain distance from the right side of a div, and is always that same distance from the side of the div no matter the size of the viewport, but will scroll with the window.
So it is x pixels from the right side of the div at all times, but y pixels from the top of the view port at all times.
Is this possible?
Position Fixed Element Horizontally Based Off Another Element
(Disclaimer Note: The solution offered here is not technically "absolute horizontally" as the question title stated, but did achieve what the OP originally wanted, the fixed position element to be 'X' distance from the right edge of another but fixed in its vertical scroll.)
I love these types of css challenges. As a proof of concept, yes, you can get what you desire. You may have to tweak some things for your needs, but here is some sample html and css that passed FireFox, IE8 and IE7 (IE6, of course, does not have position: fixed).
HTML:
<body>
<div class="inflow">
<div class="positioner"><!-- may not be needed: see notes below-->
<div class="fixed"></div>
</div>
</div>
</body>
CSS (borders and all dimensions for demonstration):
div.inflow {
width: 200px;
height: 1000px;
border: 1px solid blue;
float: right;
position: relative;
margin-right: 100px;
}
div.positioner {position: absolute; right: 0;} /*may not be needed: see below*/
div.fixed {
width: 80px;
border: 1px solid red;
height: 100px;
position: fixed;
top: 60px;
margin-left: 15px;
}
The key is to not set the left or right at all for the horizontal on the div.fixed but use the two wrapper divs to set the horizontal position. The div.positioner is not needed if the div.inflow is a fixed width, as the left margin of the div.fixed can be set to known width of the container. However, if you desire than container to have a percentage width, then you will need the div.positioner to push the div.fixed to the right side of the div.inflow first.
Edit: As an interesting side note, when I set overflow: hidden (should one need to do that) on the div.inflow had no effect on the fixed position div being outside the other's boundaries. Apparently the fixed position is enough to take it out of the containing div's context for overflow.
After much digging (including this post) I couldn't find a solution that I liked. The Accepted Answer here doesn't do what the OP's title read, and the best solutions I could find admittedly resulted in jumpy elements. Then, it hit me: Have the element be "fixed", detect when a horizontal scroll occurs, and switch it to be absolutely positioned. Here is the resulting code:
View it as a Code Pen.
HTML
<div class="blue">
<div class="red">
</div>
</div>
CSS
/* Styling */
.blue, .red {
border-style: dashed;
border-width: 2px;
padding: 2px;
margin-bottom: 2px;
}
/* This will be out "vertical-fixed" element */
.red {
border-color: red;
height: 120px;
position: fixed;
width: 500px;
}
/* Container so we can see when we scroll */
.blue {
border-color: blue;
width: 50%;
display: inline-block;
height: 800px;
}
JavaScript
$(function () {
var $document = $(document),
left = 0,
scrollTimer = 0;
// Detect horizontal scroll start and stop.
$document.on("scroll", function () {
var docLeft = $document.scrollLeft();
if(left !== docLeft) {
var self = this, args = arguments;
if(!scrollTimer) {
// We've not yet (re)started the timer: It's the beginning of scrolling.
startHScroll.apply(self, args);
}
window.clearTimeout(scrollTimer);
scrollTimer = window.setTimeout(function () {
scrollTimer = 0;
// Our timer was never stopped: We've finished scrolling.
stopHScroll.apply(self, args);
}, 100);
left = docLeft;
}
});
// Horizontal scroll started - Make div's absolutely positioned.
function startHScroll () {
console.log("Scroll Start");
$(".red")
// Clear out any left-positioning set by stopHScroll.
.css("left","")
.each(function () {
var $this = $(this),
pos = $this.offset();
// Preserve our current vertical position...
$this.css("top", pos.top)
})
// ...before making it absolutely positioned.
.css("position", "absolute");
}
// Horizontal scroll stopped - Make div's float again.
function stopHScroll () {
var leftScroll = $(window).scrollLeft();
console.log("Scroll Stop");
$(".red")
// Clear out any top-positioning set by startHScroll.
.css("top","")
.each(function () {
var $this = $(this),
pos = $this.position();
// Preserve our current horizontal position, munus the scroll position...
$this.css("left", pos.left-leftScroll);
})
// ...before making it fixed positioned.
.css("position", "fixed");
}
});
I arrived here looking for a solution to a similar problem, which was to have a footer bar that spans the width of the window and sits below the (variable height and width) content. In other words, make it appear that the footer is "fixed" with respect to its horizontal position, but retains its normal postion in the document flow with respect to its vertical position. In my case, I had the footer text right-aligned, so it worked for me to dynamically adjust the width of the footer. Here is what I came up with:
HTML
<div id="footer-outer">
<div id="footer">
Footer text.
</div><!-- end footer -->
</div><!-- end footer-outer -->
CSS
#footer-outer
{
width: 100%;
}
#footer
{
text-align: right;
background-color: blue;
/* various style attributes, not important for the example */
}
CoffeeScript / JavaScript
(Using prototype.js).
class Footer
document.observe 'dom:loaded', ->
Footer.width = $('footer-outer').getDimensions().width
Event.observe window, 'scroll', ->
x = document.viewport.getScrollOffsets().left
$('footer-outer').setStyle( {'width': (Footer.width + x) + "px"} )
which compiles into:
Footer = (function() {
function Footer() {}
return Footer;
})();
document.observe('dom:loaded', function() {
return Footer.width = $('footer-outer').getDimensions().width;
});
Event.observe(window, 'scroll', function() {
var x;
x = document.viewport.getScrollOffsets().left;
return $('footer-outer').setStyle({
'width': (Footer.width + x) + "px"
});
});
This works nicely in FireFox, and pretty well in Chrome (it's a little jittery); I haven't tried other browsers.
I also wanted any spare space below the footer to be a different colour, so I added this footer-stretch div:
HTML
...
</div><!-- end footer -->
<div id="footer-stretch"></div>
</div><!-- end footer-outer -->
CSS
#footer-outer
{
height: 100%;
}
#footer-stretch
{
height: 100%;
background-color: #2A2A2A;
}
Note that for the #footer-stretch div to work, all the parent elements up to the body element (and possibly the html element - not sure) must have a fixed height (in this case, height = 100%).