Center the wrapper on a horizontal website - javascript

I'm making a website that is horizantal with a total width of 12500px, it's build in 5 pages.
http://70.33.241.140/~flori281/website/
The problem is that i don't know how i can center the wrapper? Because there are a lot of different screenwidth. Is there a way to let the div ".box" automaticly scale to screenwidth?

Centering horizontally via CSS is done using the auto setting for the margin-left and margin-right properties:
.centered {
margin-left: auto;
margin-right: auto;
}

Your wrapper holder div css is
.box {
float: left;
line-height: 22px;
width: 2400px;
}
It has 2400px width, so that is the reason you wont see it as center, but it is centered.

You're gonna have to change some stuff in your css:
#content{
height:100%;
width:100%;
left:0;
top:0;
position:absolute;
}
.box{
line-height:22px;
}
Now I understand what you're trying to do. In that case you're gonna have to use javascript. But leave the CSS like the example I'm giving so it will look good when it's loading.
$(document).ready(function(){
var actualContentWidth = $("#content").width();
var boxes = $("#content .box").length;
var newWidth = boxes * actualContentWidth;
newWidth += "px";
$("#content").css({width:newWidth });
$("#content .box").css({width:actualContentWidth + "px",float:'left'});
});
If you want it to resize when the window resizes:
function reCalculateSizes(){
$("#content").css({width:"100%"});
var actualContentWidth = $("#content").width();
var boxes = $("#content .box").length;
var newWidth = boxes * actualContentWidth;
newWidth += "px";
$("#content").css({width:newWidth });
$("#content .box").css({width:actualContentWidth + "px",float:'left'});
}
$(document).ready(reCalculateSizes);
$(window).resize(reCalculateSizes);

Related

How to align the popup div direction in css?

I am working on a website that while mouse over a DVD shows the details like you see in picture 1, however, it doesn't work on those DVD placed to the right of the screen as you can see in picture 2, the content got chopped.
How to let it automatically choose which direction to display the content? Like if this DVD is close to the right screen, show content to the left?
Many thanks!
.imgbox .imgbox_content{
display: none;
}
.imgbox:hover .cover{
display: none;
}
.imgbox:hover .imgbox_content{
display: block;
z-index:2;
width:600px;
border-radius: 1%;
border:1px solid gray;
-webkit-transition: 1s;
position:absolute;
background: black;
color:white;
}
Here's a quick solution using JS. Not seeing any JS/HTML though, so you'll need to adapt it to whatever your code looks like:
var imgboxes = document.querySelectorAll('.imgbox');
imgboxes.forEach(function (imgbox) {
var rect = imgbox.getBoundingClientRect(),
screen_width = document.body.clientWidth,
popup_width = <<POPUP_CONTENT_WIDTH>>;
if (rect.right + popup_width > screen_width) {
imgbox.classList.add('to_left');
}
});
and then change your CSS to something like this for the popup:
.imgbox:hover .imgbox_content{
display: block;
z-index:2;
width:600px;
border-radius: 1%;
border:1px solid gray;
-webkit-transition: 1s;
position:absolute;
background: black;
color:white;
}
imgbox:hover .imgbox_content.to_left {
/* this assumes you've got a position:relative item wrapping the imgbox and that .imgbox_content is a child */
right: 0;
}
In order to get even more complete, you can handle screen resizes too:
window.addEventListener('resize', calculate_pos_imgboxes)
var calculate_pos_imgboxes = function() {
var imgboxes = document.querySelectorAll('.imgbox');
imgboxes.forEach(function (imgbox) {
var rect = imgbox.getBoundingClientRect(),
screen_width = document.body.clientWidth,
popup_width = <<POPUP_CONTENT_WIDTH>>;
if (rect.right + popup_width > screen_width) {
imgbox.classList.add('to_left');
} else {
imgbox.classList.remove('to_left');
}
});
}
calculate_pos_imgboxes();
The easiest way to do this is to just force your popups to appear at the center of the screen. You can do this using position:absolute. However, if you want the popups bounded to the location of the item - then you have to do some calculations.
It would look like this.
Get width of your popup.
Get distance from left edge of target to right edge of screen.
Compare 1 and 2
If dist < width, then offset to the left. Otherwise, offset to the right.
The code for this would look something like (using jQuery).
var padding = 20;
var elem = $(yourpopup);
var popupwidth = elem.width();
var position = p.position();
var dist = position.left - popupwidth;
// if the popup is wider than distance to edge plus padding, then offset margin using negative value.
if (dist < popupwidth){
elem.css('margin-left', "'-" + popupwidth + padding + "px'" );
}

How to create a grid of elements (divs/spans) in perfect squares with their backgrounds set to images

I've been working on a website that serves as a gallery for fantasy art, an evolving project, and I've currently hit a barricade in where to go from something I can't get to work. I tried Masonry and Wookmark both, and had issues with both, so I'm trying to do something else. I'm wanting to spawn in either divs or spans (I'm not sure which to use) within grid with the class identifier images and set their backgrounds to specific image sources that "cover", centered, so I basically have a grid of square windows into these images and when clicked, they bring up a lightbox (which I've succesfully created). Right now I've managed to get the images to show but the containers are smooshed down and have no padding left or right.
Truth be told, I have no idea what to do with the relative/absolute positioning and inline/block display parameters, and I feel this is where I'm going wrong but I don't know really what these things entail.
Segment of the HTML:
<div id="grid" class="grid"></div>
<br>
CSS:
.grid {
z-index:2;
display: inline-block;
}
.images {
display:inline-block;
position:relative;
width:25%;
height:25%;
z-index:2;
padding-right: 0.25em;
padding-left: 0.25em;
padding-top: 0.5em;
background-size: cover;
background-attachment: fixed;
background-repeat: no-repeat;
background-position: center;
}
Javascript:
var mix = shuffle(Object.keys(backInfo));
function unlockImages () {
setTimeout(function () {
if (mix !== undefined) {
var input = mix.shift();
var entry = backInfo[input];
var elem = document.createElement("div");
elem.setAttribute("class", "images");
elem.setAttribute("id", input);
elem.setAttribute("title", entry.caption);
elem.setAttribute("onclick", "javascript:changeImage(" + input + ");");
document.getElementById("grid").appendChild(elem);
document.getElementById(input).style.backgroundImage = "url(" + entry.image + ")";
$("#" + input).fadeTo(0,0);
$("#" + input).fadeTo(20000,1);
unlockImages();
}
}, 0)
}
And a live preview of what's going on at the moment: http://www.dreamquest.io
I think the problem you are describing is css. I played with your css a little and came up with this:
.grid {
z-index:2;
display: inline-block;
height: 500px;
width: 1500px;
}
.images {
display:inline-block;
position:relative;
width:25%;
height:25%;
z-index:2;
margin-right: 0.25em;
margin-left: 0.25em;
margin-top: 0.5em;
background-size: cover;
background-repeat: no-repeat;
background-position: center;
}
Some things to note with your css:
when you are setting a percentage width x height, your parent container has to have a value. Since you didn't set a height value in the .grid class your images get squished because it is taking 25% of 0 height.
background-attachment: fixed; forces your picture not to auto resize, which i am assuming you want
you were using padding that is why you are not getting the spacing between images. Padding is for the interior of the element. If you want space between elements then you need to use margin, which I have used in the above css. hth
I assume that you want to create dynamic grid and populate images for each box. Use below code to achieve it.
create container div with id "wrapper".
Add Javascript function and called it where ever you want.
function DrawGrid() {
var rows = 2;
var columns = 2;
$("#wrapper").empty();
for (var i = 0; i < rows; i++) {
var $row = $("<div />", {
class: 'row'
});
//add columns to the the temp row object
for (var c = 0; c < columns; c++) {
var $square = $("<div />", {
class: 'square'
});
//Set your imageHere
$square.append("<img></img>");
$row.append($square.clone());
}
$("#wrapper").append($row.clone());
}
}

How to keep div in center-height when I resize the browser window?

I am trying to center in height a div, however it does not work when I resize the browser screen.
How to edit this to achieve the adjustable margin-top on resize?
Thank you
<script>
var h = $(window).height();
var parentHeight = h;
var childHeight = $('#a-middle').height();
$('#a-middle').css('margin-top', (parentHeight - childHeight) /2);
</script>
Edit:
The answer should be in js since flexbox won't work on IE-9
you should stick to a CSS solution though, there are several way to achive this
.alignVertical {
position:relative;
display:inline-block;
top:50%;
transform:translateY(-50%);
}
jsfiddle: https://jsfiddle.net/jorjmt70/
or using flexbox
.parent {
display:flex;
height:100vh;
background-color:red;
justify-content:center;
align-items:center;
flex-direction:column;
}
jsfiddle: https://jsfiddle.net/mdh9h876/
if you want to use flex box use autoprefixer to get deeper browsersupport:
https://github.com/postcss/autoprefixer
Although you can easily do this with pure CSS, your bounty stated that you want a JS answer.
If you are interested in a pure CSS answer, see this answer that has multiple different methods on how to center elements vertically/horizontally.
You could simplify your jQuery to the following:
$('#a-middle').css('margin-top', function () {
return ($(window).height() - $(this).height()) / 2
});
Then you could just place this within a resize event listener and chain the .resize() method in order to trigger the event initially when the browser loads.
Example Here
$(window).on('resize', function () {
$('#a-middle').css('margin-top', function () {
return ($(window).height() - $(this).height()) / 2
});
}).resize();
JavaScript equivalent (without jQuery):
Example Here
var verticalCentering = function () {
var el = document.querySelector('#a-middle');
el.style.marginTop = (window.innerHeight - el.offsetHeight) / 2 + 'px';
}
window.addEventListener('resize', verticalCentering);
verticalCentering();
For a div called 'center-me':
$(document).ready(centerDiv);
$(window).resize(centerDiv);
function centerDiv() {
var winHeight = $(document).innerHeight(),
divHeight = $('.center-me').height();
$('.center-me').css('marginTop', (winHeight - divHeight) / 2 );
}
You need to call it when the document is ready, to get it centered in the first place, then on resize-event, to keep it centered.
Here is the fiddle for it: Fiddle
A CSS solution could do the trick for you.
div.center {
height: 100px;
width: 300px;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -150px;
position: absolute;
background-color: red;
}
<div class="center">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
This CSS code work fine in IE8+, Firefox and Chrome.
But you must know the sizes of the DIV that you want to adjust correctly. If the height and width are dynamic, you just have to update the style accordingly with JavaScript. Don't forget to apply the class center in JS on need to your DIV.
Explanations :
margin-top : - height / 2 because top : 50% only centered vertically the top of the DIV.
margin-left : - width / 2 because left : 50% only centered horizontally the left of the DIV.
position : absolute so that the DIV can center over all the page.
This can be achieved using simple CSS with deep browser support back to IE8.
html, body {
height: 100%;
}
.parent {
display: table;
table-layout: fixed;
width: 100%;
height: 100%;
}
.child {
display: table-cell;
vertical-align: middle;
text-align: center;
background: red;
}
<div class="parent">
<div class="child">This is always centered.</div>
</div>
Using table-layout makes it simple: the child can be vertically aligned (top, middle, bottom) and will take up all the available height. You're not resorting to JavaScript, CSS with patchy support or having to hard-code any figures, it should just work.
Depending on the specifics of what you're looking to do, flexbox or - as a last resort - JavaScript might be required, but for most cases display: table-cell is your friend.
That said, if it's acceptable for older browsers to get a different layout, just use #Victor's answer: this is what flexbox is for.
To make a div always stay at the center of the screen, the properties you could use are top and left attributes after setting the position attribute to absolute. However you will need to set these properties dynamically when the browser is resized. This can be done using the JQuery method - resize().
/*css code*/
.div{
position:absolute;
top:100px;
left:50px;
background:black;
}
/*JS Code*/
function keep_div_centered()
{
window_height = $(window).height();
window_width = $(window).width();
obj_height = $('.keepincenter').height();
obj_width = $('.keepincenter').width();
$('.keepincenter').css('top',(window_height/2)-(obj_height/2)).css('left',(window_width/2)-(obj_width/2))
}
keep_div_centered();
$(window).resize(function(){
keep_div_centered();
})
/* HTML Code */
<div class="keepincenter"></div>
Link to the fiddle - http://jsfiddle.net/y0937t06/
$(window).resize(function () {
var h = $(document).height();
var parentHeight = h;
var childHeight = $('#imagegallery').height();
$('#imagegallery').css('margin-top', (parentHeight - childHeight) / 2);
});
For me, this is the holy grail of CSS :)
The most reliable method I found is setting the container element as follows:
display: -webkit-flex;
-webkit-justify-content: center; /* horizontal */
-webkit-align-items: center; /* vertical */
It is simple and has no prerequisites on any other CSS properties.
The fiddle below places content 30px above vertical center:
#container {
width: 500px;
height: 300px;
background-color: red;
display: -webkit-flex;
-webkit-justify-content: center;
-webkit-align-items: center;
}
#content {
background-color: green;
margin-bottom: 30px;
}
<div id="container">
<span id="content">Content</span>
</div>
Handle window_resize event of the current window and try putting above code there.
It should give you expectd functionality.
This approach is very useful when you want to center both vertically and horizontally an absolute position div. It work also on IE8
You need to set the both outer and inner divs as
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin:auto;
margin:auto it's fundamental to center divs in this case.
You could also set the height and width of the .in div and still you would see it centered vertically and centered also when you resize the browser.
* {
margin: 0;
padding: 0;
}
html, body {
position: relative;
height: 100%;
width: 100%;
}
.in, .out {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin:auto;
}
.in {
background-color: red;
height: 50%;
width:50%;
}
.out {
background-color: blue;
}
EXAMPLE 1 JSFIDDLE height, width: in percentages: http://jsfiddle.net/a_incarnati/1o5zzcgh/3/
EXAMPLE 2 - JSFIDDLE fixed height, fixed width
http://jsfiddle.net/a_incarnati/1o5zzcgh/4/
Give display: table-cell; to the parent and align the contents vertically using vertical-align and give the padding to adjust the necessary spacing from top.
.child{
display:table-cell;
vertical-align:top;
padding-top: 50px;
}
This will keep the margin uniform throughout.
use css
first give a height to your element.
#a-middle {
height: 20px;
position: fixed;
top: calc(50% - 10px);
left: 0;
}
or use js
$(function(){
$('#a-middle').each(function(){
var t = $(window).height()/2 - $(this).outerHeight()/2;
$(this).css({top: t + "px"});
});
});
$(window).resize(function(){
$('#a-middle').each(function(){
var t = $(window).height()/2 - $(this).outerHeight()/2;
$(this).css({top: t + "px"});
});
});
The problem with the previous solutions is that you won't be able to center the div, if he's larger than the available vertical size.
If you want your div to take 50% of the page you can use the CSS vertical height based unit:
.mydiv {
height: 50vh;
top: 50%;
left: 50%;
position: fixed;
width: 50vh;
margin-top: -25vh;
margin-left:-25vh;
border: solid black 1px;
}
So your DIV will not only be centered but also maintain its ratio.
Play with margin-left and margin-top of that div, using the width and height of the window and div.
$(function () {
makeDivCenter();
$(window).resize(function () {
makeDivCenter();
});
});
function makeDivCenter() {
var windowWidth = $(window).width();
var divWidth = $(".center").width();
var windowHeight = $(window).height();
var divHeight = $(".center").height();
$(".center").css({
'margin-left': (windowWidth / 2) - (divWidth / 2) + "px",
'margin-top': (windowHeight / 2) - (divHeight / 2) + "px"
});
}
Here is jsfiddle for your reference https://jsfiddle.net/fnuud7g6/

Center an image inside of a responsive viewport without it losing its aspect ratio

What I'm trying to do is to center and resize an image that's inside of a viewport (or a parent element), without stretching it.
To make a very long story short, I want the images to keep their aspect ratio and be resized so that they cover up the viewport completely.
This is my HTML layout:
<div class="media-area" data-size="b" data-type="2">
<ul class="content-slider">
<li class="cs-item">
<img class="cs-background" src="assets/img/backgrounds/top-slider-1.jpg" alt="slider-element">
</li>
<li class="cs-item">
<img class="cs-background" src="assets/img/backgrounds/top-slider-2.jpg" alt="slider-element">
</li>
<li class="cs-item">
<img class="cs-background" src="assets/img/backgrounds/top-slider-3.jpg" alt="slider-element">
</li>
</ul>
</div>
This is my CSS:
.media-area {
width: 100%;
height: 100%; /* Standard height */
position: relative;
overflow: hidden;
}
.media-area .content-slider {
position: relative;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.media-area .content-slider .cs-item {
position: relative;
display: block;
float: left;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.media-area .content-slider .cs-item img {
display: block;
}
.media-area .content-slider .cs-background {
-webkit-transition: all .1s ease-in-out;
-moz-transition: all .1s ease-in-out;
-o-transition: all .1s ease-in-out;
transition: all .1s ease-in-out;
}
And this is my JS:
function mediazone() {
var defaults = {
elem: ".media-area",
elemWrap: ".media-area .content-slider",
elemSlide: ".media-area .content-slider .cs-item",
vh: $(window).height(),
vw: $(window).width()
};
$(defaults.elemSlide).find(".cs-background").each(function () {
var bkndImgW = $(this).width(); // Current image width
var bkndImgH = $(this).height(); // Current image height
var mediaViewPortW = $(this).parents(defaults.elem).width(); // Current media viewport width
var mediaViewPortH = $(this).parents(defaults.elem).height(); // Current media viewport height
// Used for viewport aspect ratio
var viewportratio = Math.round((mediaViewPortW / mediaViewPortH) * 100000 ) / 100000;
// Used for image aspect ratio
var imageratio = Math.round((bkndImgW / bkndImgH) * 100000 ) / 100000;
// Negative margins for when the height is larger than the width
var bkndImgPosW = ((bkndImgW - mediaViewPortW) / 2)*-1;
// Negative margins for when the width is larger than the height
var bkndImgPosH = ((bkndImgH - mediaViewPortH) / 2)*-1;
bkndImgPosW = Math.min(0, Math.max(bkndImgPosW, bkndImgPosW));
bkndImgPosH = Math.min(0, Math.max(bkndImgPosH, bkndImgPosH));
if (viewportratio > imageratio) {
$(this).removeAttr("style");
$(this).css("min-height", "100%");
$(this).css("width", "100%");
$(this).css("margin", bkndImgPosH+"px 0px");
} else if (viewportratio < imageratio){
$(this).removeAttr("style");
$(this).css("height", "100%");
$(this).css("min-width", "100%");
$(this).css("margin", "0px "+bkndImgPosW+"px");
} else if (viewportratio == imageratio) {
$(this).removeAttr("style");
}
});
}
The function is initialized here:
$(document).ready(function () {
mediazone();
});
$(window).resize(function () {
mediazone();
console.log('window resize event');
});
The problem I'm faced with right now is that when the page loads, the image is half-way out of the viewport, but when I resize the browser window, it fits perfectly.
Another problem I can't really find a way around right now is the one with the two aspect ratio's being equal ( i couldn't find a way to make the image cover the screen without having to deal with some white spaces). This makes the image flicker when the aforementioned scenario is under way.
It is important that I use the IMG tag in the DOM, otherwise maybe there would have been a way to make use of the "background-image" property in CSS.
Can anyone point out what I'm missing/ doing wrong/ I should delete?
Kind regards,
Alex
* Later Edit *
This is what I have right now:
http://jsfiddle.net/LexEckhart/Z5cjx/
After resizing, it seems to work fine and maintain the image balanced in the middle but when the page loads, the items are not positioned properly.
Since the OP specifically said he didn't want to use background-image as the image must be present in the DOM as an image, here's a jsfiddle showing a solution. I've dimmed the images using opacity to show the borders of the li's beneath it. I think the OP was overthinking the problem a bit. Anyway, hope this helps.
jsfiddle
if (viewportratio > imageratio) {
$(this).removeAttr("style");
$(this).css("width", "100%");
$(this).css("margin", bkndImgPosH+"px 0px");
} else if (viewportratio < imageratio){
$(this).removeAttr("style");
$(this).css("height", "100%");
$(this).css("margin", "0px "+bkndImgPosW+"px");
} else if (viewportratio == imageratio) {
$(this).removeAttr("style");
}
Keep in mind that images retain their aspect ratio if you only provide one attribute / property (width OR height). That's the key to the solution.
EDIT: Updated fiddle. I played around with the math logic until it worked for the images I had, replacing your images which I used before. The math logic below the first section is possibly wrong, so it'll need further testing, but this works for what I had.
You can give try for
"background-size" and "align-items" properties from css3.
set "background-size:100% 100%;";
it will cover (parent window);
For aligning contents in center you could use "align-items:center".
You can take advantage of the fact that percentage padding is always figured from the element's width. You can therefore use vertical padding with a percentage width to enforce an aspect ratio.
<div id=img></div>
// ... then in CSS:
#img {
background: url("http://placekitten.com/1280/720") no-repeat center center;
background-size: cover;
height: 0;
padding-bottom: 56.25%; /* 9:16, or 720/1280 */
}
Here is a jsfiddle to demonstrate. If you don't know the aspect ratio in advance, you can of course compute it and set the "padding-bottom" dynamically via JavaScript.
Thanks are due to the inimitable Dave Rupert for this technique.
edit ah, the <img> tag in that ending paragraph was hidden. You can employ a variation of this trick if you really need an <img> tag:
<div class=image-centerer>
<img src='http://whatever.com/your/image.png'>
</div>
// ... then in CSS:
.image-centerer {
position: relative;
height: 0;
padding-bottom: 56.25%;
}
.image-centerer img {
position: absolute;
display: block;
height: 100%;
}
Fiddle demo, and here is one demonstrating the handling of arbitrarily-proportioned images.

stick footer at the bottom of the page

please see this site in firefox:
http://www.imageworkz.asia/microtel
the footer does not stick at the bottom of the page like how it is with stackoverflow's footer. I tried several techniques as shown in some reference sites but still, no luck.
I need some css experts out there to help me out with this. Thank you!
There are mare ways to make sticky footers. A basic trick for a footer with fixed height
html, body {
height: 100%;
}
.wrapper {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -150px; /* the bottom margin is the negative value of the footer's height */
}
.footer {
height: 150px; /* .push must be the same height as .footer */
}
or
you can check this post (and many others) with the title "sticky footer"
add position:fixed; bottom:0; left:0 to footer and it will fix it in place. If you then add #container {padding-bottom:120px} (or something around that amount) your content won't be hidden by the footer when viewing the bottom of the page
Make it fixed position with bottom 0 value:
footer {
position: fixed;
bottom: 0;
}
<script type="text/javascript">
$(document).ready(function() {
var docHeight = $(window).height();
var footerHeight = $('#footer').height();
var footerTop = $('#footer').position().top + footerHeight;
if (footerTop < docHeight) {
$('#footer').css('margin-top', 10 + (docHeight - footerTop) + 'px');
}
});
</script>

Categories

Resources