CSS position elements along ring of a circle [duplicate] - javascript

How can I position several <img> elements into a circle around another and have those elements all be clickable links as well? I want it to look like the picture below, but I have no idea how to achieve that effect.
Is this even possible?

2020 solution
Here's a more modern solution I use these days.
I start off by generating the HTML starting from an array of images. Whether the HTML is generated using PHP, JS, some HTML preprocessor, whatever... this matters less as the basic idea behind is the same.
Here's the Pug code that would do this:
//- start with an array of images, described by url and alt text
- let imgs = [
- {
- src: 'image_url.jpg',
- alt: 'image alt text'
- } /* and so on, add more images here */
- ];
- let n_imgs = imgs.length;
- let has_mid = 1; /* 0 if there's no item in the middle, 1 otherwise */
- let m = n_imgs - has_mid; /* how many are ON the circle */
- let tan = Math.tan(Math.PI/m); /* tangent of half the base angle */
.container(style=`--m: ${m}; --tan: ${+tan.toFixed(2)}`)
- for(let i = 0; i < n_imgs; i++)
a(href='#' style=i - has_mid >= 0 ? `--i: ${i}` : null)
img(src=imgs[i].src alt=imgs[i].alt)
The generated HTML looks as follows (and yes, you can write the HTML manually too, but it's going to be a pain to make changes afterwards):
<div class="container" style="--m: 8; --tan: 0.41">
<a href='#'>
<img src="image_mid.jpg" alt="alt text"/>
</a>
<a style="--i: 1">
<img src="first_img_on_circle.jpg" alt="alt text"/>
</a>
<!-- the rest of those placed on the circle -->
</div>
In the CSS, we decide on a size for the images, let's say 8em. The --m items are positioned on a circle and it's if they're in the middle of the edges of a polygon of --m edges, all of which are tangent to the circle.
If you have a hard time picturing that, you can play with this interactive demo which constructs the incircle and circumcircle for various polygons whose number of edges you pick by dragging the slider.
This tells us that the size of the container must be twice the radius of the circle plus twice half the size of the images.
We don't yet know the radius, but we can compute it if we know the number of edges (and therefore the tangent of half the base angle, precomputed and set as a custom property --tan) and the polygon edge. We probably want the polygon edge to be a least the size of the images, but how much we leave on the sides is arbitrary. Let's say we have half the image size on each side, so the polygon edge is twice the image size. This gives us the following CSS:
.container {
--d: 6.5em; /* image size */
--rel: 1; /* how much extra space we want between images, 1 = one image size */
--r: calc(.5*(1 + var(--rel))*var(--d)/var(--tan)); /* circle radius */
--s: calc(2*var(--r) + var(--d)); /* container size */
position: relative;
width: var(--s); height: var(--s);
background: silver /* to show images perfectly fit in container */
}
.container a {
position: absolute;
top: 50%; left: 50%;
margin: calc(-.5*var(--d));
width: var(--d); height: var(--d);
--az: calc(var(--i)*1turn/var(--m));
transform:
rotate(var(--az))
translate(var(--r))
rotate(calc(-1*var(--az)))
}
img { max-width: 100% }
See the old solution for an explanation of how the transform chain works.
This way, adding or removing an image from the array of images automatically arranges the new number of images on a circle such that they're equally spaced out and also adjusts the size of the container. You can test this in this demo.
OLD solution (preserved for historical reasons)
Yes, it is very much possible and very simple using just CSS. You just need to have clear in mind the angles at which you want the links with the images (I've added a piece of code at the end just for showing the angles whenever you hover one of them).
You first need a wrapper. I set its diameter to be 24em (width: 24em; height: 24em; does that), you can set it to whatever you want. You give it position: relative;.
You then position your links with the images in the center of that wrapper, both horizontally and vertically. You do that by setting position: absolute; and then top: 50%; left: 50%; and margin: -2em; (where 2em is half the width of the link with the image, which I've set to be 4em - again, you can change it to whatever you wish, but don't forget to change the margin in that case).
You then decide on the angles at which you want to have your links with the images and you add a class deg{desired_angle} (for example deg0 or deg45 or whatever). Then for each such class you apply chained CSS transforms, like this:
.deg{desired_angle} {
transform: rotate({desired_angle}) translate(12em) rotate(-{desired_angle});
}
where you replace {desired_angle} with 0, 45, and so on...
The first rotate transform rotates the object and its axes, the translate transform translates the object along the rotated X axis and the second rotate transform brings back the object into position.
The advantage of this method is that it is flexible. You can add new images at different angles without altering the current structure.
CODE SNIPPET
.circle-container {
position: relative;
width: 24em;
height: 24em;
padding: 2.8em;
/*2.8em = 2em*1.4 (2em = half the width of a link with img, 1.4 = sqrt(2))*/
border: dashed 1px;
border-radius: 50%;
margin: 1.75em auto 0;
}
.circle-container a {
display: block;
position: absolute;
top: 50%; left: 50%;
width: 4em; height: 4em;
margin: -2em;
}
.circle-container img { display: block; width: 100%; }
.deg0 { transform: translate(12em); } /* 12em = half the width of the wrapper */
.deg45 { transform: rotate(45deg) translate(12em) rotate(-45deg); }
.deg135 { transform: rotate(135deg) translate(12em) rotate(-135deg); }
.deg180 { transform: translate(-12em); }
.deg225 { transform: rotate(225deg) translate(12em) rotate(-225deg); }
.deg315 { transform: rotate(315deg) translate(12em) rotate(-315deg); }
<div class='circle-container'>
<a href='#' class='center'><img src='image.jpg'></a>
<a href='#' class='deg0'><img src='image.jpg'></a>
<a href='#' class='deg45'><img src='image.jpg'></a>
<a href='#' class='deg135'><img src='image.jpg'></a>
<a href='#' class='deg180'><img src='image.jpg'></a>
<a href='#' class='deg225'><img src='image.jpg'></a>
<a href='#' class='deg315'><img src='image.jpg'></a>
</div>
Also, you could further simplify the HTML by using background images for the links instead of using img tags.
EDIT: example with fallback for IE8 and older (tested in IE8 and IE7)

Here is the easy solution without absolute positioning:
.container .row {
margin: 20px;
text-align: center;
}
.container .row img {
margin: 0 20px;
}
<div class="container">
<div class="row">
<img src="https://ssl.gstatic.com/s2/oz/images/faviconr2.ico" alt="" width="64" height="64">
<img src="https://ssl.gstatic.com/s2/oz/images/faviconr2.ico" alt="" width="64" height="64">
</div>
<div class="row">
<img src="https://ssl.gstatic.com/s2/oz/images/faviconr2.ico" alt="" width="64" height="64">
<img src="https://ssl.gstatic.com/s2/oz/images/faviconr2.ico" alt="" width="64" height="64">
<img src="https://ssl.gstatic.com/s2/oz/images/faviconr2.ico" alt="" width="64" height="64">
</div>
<div class="row">
<img src="https://ssl.gstatic.com/s2/oz/images/faviconr2.ico" alt="" width="64" height="64">
<img src="https://ssl.gstatic.com/s2/oz/images/faviconr2.ico" alt="" width="64" height="64">
</div>
</div>
http://jsfiddle.net/mD6H6/

Using the solution proposed by #Ana:
transform: rotate(${angle}deg) translate(${radius}px) rotate(-${angle}deg)
I created the following jsFiddle that places circles dynamically using plain JavaScript (jQuery version also available).
The way it works is rather simple:
document.querySelectorAll( '.ciclegraph' ).forEach( ( ciclegraph )=>{
let circles = ciclegraph.querySelectorAll( '.circle' )
let angle = 360-90, dangle = 360 / circles.length
for( let i = 0; i < circles.length; ++i ){
let circle = circles[i]
angle += dangle
circle.style.transform = `rotate(${angle}deg) translate(${ciclegraph.clientWidth / 2}px) rotate(-${angle}deg)`
}
})
.ciclegraph {
position: relative;
width: 500px;
height: 500px;
margin: calc(100px / 2 + 0px);
}
.ciclegraph:before {
content: "";
position: absolute;
top: 0; left: 0;
border: 2px solid teal;
width: calc( 100% - 2px * 2);
height: calc( 100% - 2px * 2 );
border-radius: 50%;
}
.ciclegraph .circle {
position: absolute;
top: 50%; left: 50%;
width: 100px;
height: 100px;
margin: calc( -100px / 2 );
background: teal;
border-radius: 50%;
}
<div class="ciclegraph">
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
</div>

Building off #Ana's excellent answer, I created this dynamic version that allows you to add and remove elements from the DOM and maintain proportionate spacing between the elements - check out my fiddle: https://jsfiddle.net/skwidbreth/q59s90oy/
var list = $("#list");
var updateLayout = function(listItems) {
for (var i = 0; i < listItems.length; i++) {
var offsetAngle = 360 / listItems.length;
var rotateAngle = offsetAngle * i;
$(listItems[i]).css("transform", "rotate(" + rotateAngle + "deg) translate(0, -200px) rotate(-" + rotateAngle + "deg)")
};
};
$(document).on("click", "#add-item", function() {
var listItem = $("<li class='list-item'>Things go here<button class='remove-item'>Remove</button></li>");
list.append(listItem);
var listItems = $(".list-item");
updateLayout(listItems);
});
$(document).on("click", ".remove-item", function() {
$(this).parent().remove();
var listItems = $(".list-item");
updateLayout(listItems);
});
#list {
background-color: blue;
height: 400px;
width: 400px;
border-radius: 50%;
position: relative;
}
.list-item {
list-style: none;
background-color: red;
height: 50px;
width: 50px;
position: absolute;
top: 50%;
left: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<ul id="list"></ul>
<button id="add-item">Add item</button>

Here is a version I made in React from the examples here.
CodeSandbox Example
import React, { useRef, useEffect } from "react";
import "./styles.css";
export default function App() {
const graph = useRef(null);
useEffect(() => {
const ciclegraph = graph.current;
const circleElements = ciclegraph.childNodes;
let angle = 360 - 90;
let dangle = 360 / circleElements.length;
for (let i = 0; i < circleElements.length; i++) {
let circle = circleElements[i];
angle += dangle;
circle.style.transform = `rotate(${angle}deg) translate(${ciclegraph.clientWidth /
2}px) rotate(-${angle}deg)`;
}
}, []);
return (
<div className="App">
<div className="ciclegraph" ref={graph}>
<div className="circle" />
<div className="circle" />
<div className="circle" />
<div className="circle" />
<div className="circle" />
<div className="circle" />
</div>
</div>
);
}

You can certainly do it with pure css or use JavaScript. My suggestion:
If you already know that the images number will never change just calculate your styles and go with plain css (pros: better performances, very reliable)
If the number can vary either dynamically in your app or just may vary in the future go with a Js solution (pros: more future-proof)
I had a similar job to do, so I created a script and open sourced it here on Github for anyone who might need it. It just accepts some configuration values and simply outputs the CSS code you need.
If you want to go for the Js solution here's a simple pointer that can be useful to you. Using this html as a starting point being #box the container and .dot the image/div in the middle you want all your other images around:
Starting html:
<div id="box">
<div class="dot"></div>
<img src="my-img.jpg">
<!-- all the other images you need-->
</div>
Starting Css:
#box{
width: 400px;
height: 400px;
position: relative;
border-radius: 100%;
border: 1px solid teal;
}
.dot{
position: absolute;
border-radius: 100%;
width: 40px;
height: 40px;
left: 50%;
top: 50%;
margin-left: -20px;
margin-top: -20px;
background: rebeccapurple;
}
img{
width: 40px;
height: 40px;
position: absolute;
}
You can create a quick function along these lines:
var circle = document.getElementById('box'),
imgs = document.getElementsByTagName('img'),
total = imgs.length,
coords = {},
diam, radius1, radius2, imgW;
// get circle diameter
// getBoundingClientRect outputs the actual px AFTER transform
// using getComputedStyle does the job as we want
diam = parseInt( window.getComputedStyle(circle).getPropertyValue('width') ),
radius = diam/2,
imgW = imgs[0].getBoundingClientRect().width,
// get the dimensions of the inner circle we want the images to align to
radius2 = radius - imgW
var i,
alpha = Math.PI / 2,
len = imgs.length,
corner = 2 * Math.PI / total;
// loop over the images and assign the correct css props
for ( i = 0 ; i < total; i++ ){
imgs[i].style.left = parseInt( ( radius - imgW / 2 ) + ( radius2 * Math.cos( alpha ) ) ) + 'px'
imgs[i].style.top = parseInt( ( radius - imgW / 2 ) - ( radius2 * Math.sin( alpha ) ) ) + 'px'
alpha = alpha - corner;
}
You can see a live example here

There is no way to magically place clickable items in a circle around another element with CSS.
The way how I would do this is by using a container with position:relative;. And then place all the elements with position:absolute; and using top and left to target it's place.
Even though you haven't placed jquery in your tags it might be best to use jQuery / javascript for this.
First step is placing your center image perfectly in the center of the container using position:relative;.
#centerImage {
position:absolute;
top:50%;
left:50%;
width:200px;
height:200px;
margin: -100px 0 0 -100px;
}
After that you can place the other elements around it by using an offset() of the centerImage minus the offset() of the container. Giving you the exact top and left of the image.
var left = $('#centerImage').offset().left - $('#centerImage').parent().offset().left;
var top = $('#centerImage').offset().top - $('#centerImage').parent().offset().top;
$('#surroundingElement1').css({
'left': left - 50,
'top': top - 50
});
$('#surroundingElement2').css({
'left': left - 50,
'top': top
});
$('#surroundingElement3').css({
'left': left - 50,
'top': top + 50
});
What I've done here is placing the elements relative to the centerImage. Hope this helps.

You could do it like this: fiddle
Don't mind the positioning, its a quick example

The first step is to have 6 long columnar boxes:
The second step is to use position: absolute and move them all into the middle of your container:
And now rotate them around the pivot point located at the bottom center. Use :nth-child to vary rotation angles:
div {
transform-origin: bottom center;
#for $n from 0 through 7 {
&:nth-child(#{$n}) {
rotate: (360deg / 6) * $n;
}
}
Now all you have to do is to locate your images at the far end of every column, and compensate the rotation with an anti-rotation :)
Full source:
<div class="flower">
<div class="petal">1</div>
<div class="petal">2</div>
<div class="petal">3</div>
<div class="petal">4</div>
<div class="petal">5</div>
<div class="petal">6</div>
</div>
.flower {
width: 300px;
height: 300px;
// We need a relative position
// so that children can have "position:abolute"
position: relative;
.petal {
// Make sure petals are visible
border: 1px solid #999;
// Position them all in one point
position: absolute; top: 0; left: 50%;
display: inline-block;
width: 30px; height: 150px;
// Rotation
transform-origin: bottom center;
#for $n from 0 through 7 {
&:nth-child(#{$n}) {
// Petal rotation
$angle: (360deg / 6) * $n;
rotate: $angle;
// Icon anti-rotation
.icon { rotate: -$angle; }
}
}
}
}
See CodePen

Related

Resizing images of different aspect ratios to fit a div without stretching it

I'm making a portfolio website and I am trying to make a simple image browser. I have a container div with size relative to the size of the browser window. I want that div to be able to contain images of different aspect ratios and a caption of fixed height and the width relative to the width of the image. I don't want the div to stretch to contain the images, I want to resize the image (you can see what I mean in the picture below).
illustration of the problem here
I was trying to use javascript to calculate the size of the image, but failed, because I couldn't calculate the element's size before it is actually loaded. This is how I tried to do it (not thinking about the titlebar):
var divAspectRatio = containerDiv.offsetHeight/containerDiv.offsetWidth;
var imageAspectRatio = image.offsetHeight/image.offsetWidth;
if(divAspectRatio>imageAspectRatio){
image.style.height = content_in.offsetHeight;
}else{
image.style.width = content_in.offsetWidth;
}
captionDiv.style.width = image.offsetWidth;
How do I make it work?
If your background image is in a div element, add this to your css, inside the div block:
background-size: cover;
If it's in an img element, add this to your css, inside the img block:
object-fit: cover;
Try using this css element:
object-fit: cover
This way, your image will get resized to fit the containing box!
The desired layout needs some calculation as the placing of an image that has aspect ratio bigger than the aspect ratio of the container differs from one that doesn't. Also to note is that the caption area is required to be only as wide as the displayed image but has a fixed height.
The imgs are wrapped in an 'innerdiv' which will also contain the caption. On loading the image's aspect ratio is found and stored as a CSS variable. Other CSS variables are set up in advance - see the head of this snippet for those that can be chosen. Remaining calculations are done in CSS.
window.onload = function () {
const imgs = document.querySelectorAll('.container .innerdiv .img');
imgs.forEach(img => {
img.parentElement.style.setProperty('--imgratio', img.naturalWidth / img.naturalHeight);
img.parentElement.classList.add(( (img.naturalWidth / img.naturalHeight) > getComputedStyle(img).getPropertyValue("--containerratio") ) ? 'wider' : 'thinner');
});
}
* {
padding: 0;
margin: 0;
}
.container {
/* SET THE NEXT 4 VARIABLES TO WHAT YOU REQUIRE */
--unit: 1vmin; /* the basic unit - must be fixed e.g. vmin, px, ch not % */
--containerw: 40; /* width of a container in these units */
--containerratio: 1.5; /* the ratio of width to height */
--captionh: 4vmin; /* height of a caption including its units (which must be fixed e.g. vmin, px, em */
--containerh: calc(var(--containerw) / var(--containerratio));
display: inline-block;
width: calc(var(--containerw) * var(--unit));
height: calc(var(--containerh) * var(--unit));
position: relative;
border: solid;
}
.innerdiv {
display: inline-block;
position: absolute;
top: 0;
left: 0;
}
.innerdiv.thinner {
width: calc(var(--imgratio) * ((var(--containerh) * var(--unit)) - var(--captionh)));
height: 100%;
left: 50%;
transform: translateX(-50%);
}
.innerdiv.wider {
width: 100%;
height: calc((var(--containerw) / var(--imgratio)) * var(--unit) + var(--captionh));
top: 50%;
transform: translateY(-50%);
}
.img {
width: 100%;
height: auto;
}
.caption {
font-size: 2vmin;
background-color: yellow;
text-align: center;
width: 100%;
height: var(--captionh);
position: absolute;
top: calc(100% - var(--captionh));
left: 0;
}
<div class="container">
<div class="innerdiv">
<img class="img" src="https://picsum.photos/id/1016/200/300">
<div class="caption">CAPTION</div>
</div>
</div>
<div class="container">
<div class="innerdiv">
<img class="img" src="https://picsum.photos/id/1016/500/200">
<div class="caption">CAPTION</div>
</div>
</div>
<div class="container">
<div class="innerdiv">
<img class="img" src="https://picsum.photos/id/1016/300/300">
<div class="caption">CAPTION</div>
</div>
</div>

Parallax Scrolling (Inception Style) in Website Display Effects

I want to create one page website using a Parallax effect like this one: Parallax Effect. I did all my research but I didn't find any example explaining how to do it, or what is the name of this parallax effect. I really need help!
This effect zooms into the page on scroll, as shown in the GIF below.
Here's what I have so far:
html {
height: 600vh;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
body {
padding: 0;
margin: 0;
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
position: fixed;
align-items: center;
justify-content: end;
}
#parent {
padding: 0;
margin: 0;
height: 600vh;
width: 100vw;
display: flex;
flex-direction: column;
transform-style: preserve-3d;
perspective: 250px;
}
.page {
padding: 0;
margin: 0;
height: 100vh;
width: 100vw;
position: absolute;
background: rgba(0, 0, 0, 0.1);
text-align: center;
box-shadow: inset 5px 5px red, inset -5px -5px red;
}
.page:nth-child(1) {
transform: scale(1);
}
.page:nth-child(2) {
bottom: -98%;
transform: translate3d(0, 0, -500px);
}
.page:nth-child(3) {
bottom: -196%;
transform: translate3d(0, 0, -1000px);
}
.page:nth-child(4) {
bottom: -294%;
transform: translate3d(0, 0, -1500px);
}
.page:nth-child(5) {
bottom: -392%;
transform: translate3d(0, 0, -2000px);
}
.page:nth-child(6) {
bottom: -490%;
transform: translate3d(0, 0, -2500px);
}
<div id="parent">
<div class="page">Page 1</div>
<div class="page">Page 2</div>
<div class="page">Page 3</div>
<div class="page">Page 4</div>
<div class="page">Page 5</div>
<div class="page">Page 6</div>
</div>
I am stuck at the animation via JavaScript part:
On body scroll the pages should scale to a maximum and then disappear one after the other,
The next page page2 should take the place of page1 and so on. To make the scroll sticky, scroll-snap-type: y; can be used.
I'm not quite sure what you'd call this scrolling effect - scaling page scrolling? - but it can be achieved in modern browsers with the CSS scale transform and a little JavaScript.
Style your page sections
I stacked my sections on top of each other by giving them a position absolute and fixing their CSS coordinates.
HTML:
<section style="background-color: red;">
<h1>This is section number one!!</h1>
</section>
<section style="background-color: blue;">
<h1>This is section number two!!</h1>
</section>
CSS:
html, body {
position: relative;
margin: 0;
height: 100%;
overflow: hidden;
}
section {
position: absolute;
width: 100%;
height: 100%;
left: 0; right: 0;
top: 0; bottom: 0;
text-align: center;
}
Set the initial scale of each section.
I wanted each section to be one third the size of the previous section. This meant the scale of the first section would be 1; the scale of the second would be 1/3; the third would be 1/9, the fourth 1/27 and so on. Therefore, if n is the index number of each section, the sections should be scaled by (1/3)^n. Scaling the sections is quite easy with the CSS3 transform feature.
JavaScript:
document.addEventListener( 'DOMContentLoaded', function() {
var sections = document.getElementsByTagName( 'section' ),
i = 0;
for ( i; i < sections.length; i++ ) {
sections[i].style.transform = 'scale(' + Math.pow( 1/3, i ) + ')';
}
} );
Alter the scale on scroll
Since the page does not overflow we need to listen to the wheel event. We must also keep a variable consisting of how far we've scrolled between a minimum (0) and a maximum (I picked 1000; you can change sensitivity of the scroll with a larger or smaller value). When the wheel event occurs we find how much the user has scrolled from the event's deltaY property, adjust our scroll counter by that much, and scale our sections accordingly.
To calculate how much we must scale each section is only a little more complex than calculating the initial scales. It's still a power of 1/3, although we must now subtract the scale multiplied by the total number of sections divided by the maximum counter value from our n.
You might also like to use requestAnimationFrame for a smoother experience.
JavaScript:
var counter = 0,
counter_max = 1000,
total = document.getElementsByTagName( 'section' ).length;
window.addEventListener( 'wheel', function( e ) {
counter += e.deltaY;
if ( counter > counter_max ) counter = counter_max;
if ( counter < 0 ) counter = 0;
requestAnimationFrame( applyScale );
} );
function applyScale() {
var sections = document.getElementsByTagName( 'section' ),
i = 0;
for ( i; i < sections.length; i++ ) {
var scale = Math.pow( 1/3, i - counter * total / counter_max );
sections[i].style.transform = 'scale(' + scale + ')';
}
}
Result
A pen that implements the above may be found at https://codepen.io/jla-/pen/aMNgxy
This should be a useful framework to get you started. Adding the anchors at the top of the page would involve a click listener that animates the counter variable to the appropriate value, calling the applyScale function on each animation frame.

Change image opacity when using GetElementById

Part of my Uni module requires me to make a webstory that uses random elements to mix up the story. I'm using GetElementById in JS to embed one random image from an array into a div, which works perfectly fine. The image becomes the background of the div, and I then have text on top of the image - again this all works perfectly fine.
However the issue is that I want the image to be slightly transparent so that the text is easier to read, however no matter what solution I try, I can't get it to work.
I've tried making the div transparent in both CSS and JS, however then the whole div including the text is effected which defeats the point. Then when I try the RGBA style in CSS, the image isn't effected.
So what I need is the image that is loaded into the div through JS to be slightly transparent, whilst the text that is also in the div in the HTML doument to remain untouched.
This is the JS I'm using to randomly select an image:
function randomGun() {
var imgCount = 3;
var dir = 'img/';
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
var images = new Array
images[1] = "gun1.jpg",
images[2] = "gun2.jpg",
images[3] = "gun3.jpg",
document.getElementById("left").style.backgroundImage = "url(" + dir + images[randomCount] + ")";
}
<div id="container">
<div id="left">
<a id="message">Drive a bit closer to see if anybody is there.</a>
</div>
<script>
window.onload = randomGun()
</script>
</div>
Use a nested div with semi-transparent white background.
<div id="container">
<div id="left">
<div id="nested" style="width:100%;height:100%; background-color: rgba(255,255,255,0.5)">
<a id="message">Drive a bit closer to see if anybody is there.</a>
</div>
</div>
<script>window.onload = randomGun()</script>
</div>
In addition, I would set everything relative to style in a stylesheet, or at least inside a <style></style>.
UPDATE
Added your JS and fixed it a little. Note the adjustment to the random expression.
Perhaps this'll help you.
Use an element that'll contain 2 other elements, give the container position:relative and z-index:-2
Then the 2 elements inside should have position:absolute.
Next give the top element z-index:-1, background:url(http://image-host.com/path/to/img.jpg), and opacity:.5
Then the second element should have text and whatever else you want visible. Give this element z-index:1.
The reason why opacity wasn't working the way you expected to work is because opacity applies to everything within the element as well. Here in the Snippet, we layered an element with content and an element with a background image separately.
REFERENCE: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index
SNIPPET
function randomBG() {
var imgCount = 3;
var path = 'http://imgh.us/';
var randomCount = Math.round(Math.random() * (imgCount));
var images = ['solar_system.jpg', 'kowloon.jpg', 'transparent-map.png'];
document.getElementById("fader").style.backgroundImage = "url(" + path + images[randomCount] + ")";
}
window.onload = randomBG;
html,
body {
height: 100%;
width: 100%;
font: 400 16px/1.5 Verdana;
box-sizing: border-box;
}
* {
margin: 0;
padding: 0;
border: 0;
}
#base {
position: relative;
z-index: -2;
width: 100vw;
height: 100vh;
}
#content {
position: absolute;
z-index: 1;
padding: 20px;
margin: 0 auto;
width: 75%;
height: auto;
top: 0;
left: 0;
background: none;
}
#fader {
position: absolute;
z-index: -1;
padding: 20px;
margin: 0 auto;
min-width: 75%;
min-height: 75%;
/*background: url(http://imgh.us/Lenna.png);*/
opacity: .5;
}
<main id='base'>
<section id='fader'></section>
<article id='content'>
<h1>This is the Text</h1>
</article>
</main>

Pure JavaScript horizontal slider

Hello I am working on a slideshow with thumbnails.
My slideshow works but I'd like to have a horizontal slide of my thumbnail since I don't have enough space to display them all.
It could be on hover or on click of a button prev/next.
My code needs to be in javascript only no librairies.
Here is where I'm at, the entire code is in one page.
-- EDIT
Here is my HTML
<div class="controls">
<a class="previous" href=""><img src="images/fleche_g.jpg" alt=""></a>
<div class="thumbs">
<ul id="thumbs">
</ul>
</div>
<a class="next" href=""><img src="images/fleche_d.jpg" alt=""></a>
</div>
My CSS
.controls {
width: 658px;
height: 76px;
margin-top: 10px;
}
#thumbs {
display: inline-block;
overflow: hidden;
height: 76px;
position: relative;
z-index: 99;
}
.controls .previous, .controls .next {
float: left;
width: 51px;
height: 76px;
position: relative;
z-index: 999;
}
.controls .previous {
background: transparent url('images/fleche_g.jpg') 0 0 no-repeat;
}
.controls .next {
background: transparent url('images/fleche_d.jpg') 0 0 no-repeat;
}
And the 2 simple functions I have tried calling onClick of the a prev/next button.
// Move thumbs to the left
function left() {
document.getElementById('thumbs').style.left = '-124px';
}
// Move thumbs to the right
function right() {
document.getElementById('thumbs').style.right = '-124px';
}
So far nothing works at all. What am I missing?
I think this is what you need to solve your problem. 1 new function getLeft(); the rest is adaptions of existing functions and css.
I think this ought to work for more images, so the client has to push the right-button multiple times to get to the end.
You might also want extra calculations to restrict the range; so all the images are not beyond the right or left of the .wrapper-thumbs (feel free to ask me).
Notice: maybe you want left and right to do the opposite (I've seen both) ; just swap the 500 <-> -500
Or do you only want as many images so that only 1 push of the button gets you totally left or right?
css:
#slideshow .controls .wrapper-thumbs {
overflow: hidden;
position: relative; /* this means: the upper-left corner of <div class="wrapper-thumbs"> is now the the new base/zero (for style.left) for all the children with position: absolute */
float: left; /* this is so the left- and right-button are kept in place */
margin: 0;
width: 556px;
height: 76px;
}
#thumbs {
display: inline-block;
width: 900px;
height: 76px;
position: absolute; /* So now, the new base of #thumbs is set to the base/zero of <div class="wrapper-thumbs"> */
z-index: 99;
}
script:
// function reads style.left; removes 'px'; returns the numeric value.
function getLeft() {
var left = document.getElementById('thumbs').style.left;
return Number(left.substr(0, left.length - 2)); // .substr removes the 'px'
}
// Move thumbs to the left
function left() {
var currentLeft = getLeft();
var newLeft = currentLeft -500;
document.getElementById('thumbs').style.left = newLeft + 'px';
}
// Move thumbs to the right
function right() {
var currentLeft = getLeft();
var newLeft = currentLeft +500;
document.getElementById('thumbs').style.left = newLeft + 'px';
}

how to i get the image to center in my gallery

I have made a simple slider gallery for my site but have found that when I click next the image updates but it does not centre until I have done a full cycle of the images
how can i get the images to align from the start?
HERE IS THE JS FIDDLE > http://jsfiddle.net/8pScd/4
HTML
<div class="view_gallery">view gallery</div>
<div class="prev control"><<</div>
<div class="next control">>></div>
<div class="gallery">
</div>
<div class="overlay"></div>
CSS
.overlay{
display: none;
position: absolute; top: 0; right: 0; bottom: 0; left: 0;
width: 100%; height: 100%;
background: rgba(0,0,0,0.8);
z-index: 100;
}
.gallery{
z-index: 200;
padding: 10px;
position: absolute;
left: 50%;
background: #fff;
}
.control{
position: absolute;
top: 200px;
z-index: 300;
color: #fff;
text-transform: capitalize;
font-size: 2em;
cursor: pointer;
}
.prev{left: 0;}
.next{right:0;}
JQUERY
//images
var pics = new Array();
pics[0] = "cars.jpg";
pics[1] = "cats.png";
pics[2] = "dogs.png";
pics[3] = "bus.jpg"
//total amount of pictures to display
var pictot = pics.length-1;
var nxt = $(".next"),
prv = $(".prev"),
view = $(".view_gallery"),
gal = $(".gallery"),
overlay = $(".overlay"),
num = 0;
//view gallery
view.click(function(){
overlay.show();
gal.show();
// Start gallery off on the first image
gal.html('<img src="' + pics[0] + '" />');
});
nxt.click(function(){
// If on the last image set value to 0. Else add 1
if (num == pictot){num = 0;}else{num++;};
update();
});
prv.click(function(){
// If on first image set value to last image number. Else minus 1
if (num == 0){num = pictot;}else{num--;}
update();
});
function update () {
// update image with next/previous
gal.html('<img src="' + pics[num] + '" />');
//center image (not working very well)
var x = gal.width()/2;
gal.css("marginLeft", -x);
};
//hide
overlay.click(function(){
gal.hide();
$(this).hide();
});
The problem you have is that the "update" function is called immediately after clicking on prev/next. The image has not yet been loaded, so the code does not actually know the new gal.width yet. That's why it works after a full round: the images are now in the cache, and therefore already available.
The best solution would be to use javascript Image objects to preload the pictures; an easier way but possibly problematic is to use the 'load' event (it may not work well in all browsers).
You can align your gallery div with some simple css hack.
1)first define width. (you can define dynamic width with jquery).
2)add position:absolute;
3)add left:0 , right:0;
4)add margin:0 auto;
final code looks like this.
.gallery {
background: none repeat scroll 0 0 #FFFFFF;
left: 0;
margin: 0 auto !important;
padding: 10px;
position: absolute;
right: 0;
width: 600px;
z-index: 200;
}
your math is wrong, look at this example http://jsfiddle.net/8pScd/6/
i've just need to change your math at
var x = $('body').width()/2 - gal.width()/2;
gal.css("margin-left", x + 'px');
and i removed this line at your css
left: 50%;
.gallery{
z-index: 200;
padding: 10px;
position: absolute;
background: #fff;
}
Knowing that .gallery is 920px wide, set left: 50%; margin-left: -470px. Also remove the line in javascript which updates margin-left of the gallery container - gal.css("marginLeft", -x);

Categories

Resources