Trying to set style as screen height and width CSS - javascript

What I am trying to do is get the height of the screen and the width of the screen and then use the document.getElement.style.property = newStyle to change the style to the obtained height of the screen and width of the screen. I tried making the height and width into Strings to use, I also tried putting just the values in. I want to know how to put in px values and % values. Thanks.
<!DOCTYPE html>
<html lang = "en/US">
<head>
<title>
cyclebg test
</title>
<style>
body {
background: url("http://i.dailymail.co.uk/i/pix/2016/03/22/13/32738A6E00000578-3504412-image-a-6_1458654517341.jpg")
no-repeat;
background-position: center top;
background-size: 200px 100px;
}
p {
padding: 50px; background-color: green; margin-left: -1%; margin-right: -1%; display: block;
}
</style>
</head>
<body>
<p style = "margin-top: 25%;"> Hello World </p>
<p> Yo </p>
</body>
<script>
var heightOfScreen = screen.height;
var widthOfScreen = screen.width;
var heightOfScreenString = heightOfScreen + " px";
var widthOfScreenString = widthOfScreen + " px";
document.getElementsByTagName("body")[0].style.backgroundSize = "heightOfScreenString widthOfScreenString";
</script>
</html>

You should try using
background-size: cover;
So the background will cover the whole size of the background and cropoff the excess.
If you want the full background to show (despite of blank spaces on top or sides) you can use "contain" instead
https://jsfiddle.net/0vps9x0s/

This shortest & simplest answer is to use CSS to cover the background image and crop the excess, using this:
background-size: cover;
If you want to "fit" the background image to the container, use this:
background-size: 100% 100%;
If you want use jQuery to get the width & height of the window and set the size of the background image, do this:
var width = $(window).width();
var height = $(window).height();
// NOTE: this does the same thing as "background-size: 100% 100%;"
$("body").css("background-size", width + "px " + height + "px");
If you just want to use Vanilla JavaScript to get the width & height of the window and set the size of the background image, use this:
var width = window.innerWidth;
var height = window.innerHeight;
// NOTE: this does the same thing as "background-size: 100% 100%;"
document.getElementsByTagName("body")[0].style.backgroundSize = width + "px " + height + "px";
Good luck and all the best.

Related

Optimal fit of image to display

Is there a way that css/html5 can fit an image optimally to a viewport such that no cropping will occur?
I would appreciate a solution above. Here's how it might be done in code:
If the aspect ratio of the image (H/W) is larger than the display, then the image css would be height:100%, width:auto;
If the aspect ratio of the image (H/W) is smaller than the display, then the image css would be height:auto, width:100%
This seems like a lot of work, is there a simpler solution?
Sam
Try this and see if it works for you. the vh unit means viewport height.
.that-image {
display: block;
height: 100vh;
position: absolute;
}
There is a corresponding unit for width, vw.
You can set is as your div background and give this styles
<div class='my-image.jpg'></div>
.my-image {
background-repeat: no-repeat;
background-position: center;
background-size: cover;
text-align: center;
height: 100vh;
width: 100vw;
background-image: url("https://images.pexels.com/photos/457882/pexels-photo-457882.jpeg");
}
Here's what I went with to avoid distorting the image aspect ratio:
function fitImage() { // Optimally fit an image to the viewport
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
var viewportHeight = $(window).height(); // The viewport height/width
var viewportWidth = $(window).width();
var aspectImage = parseFloat(height)/parseFloat(width); // Need Floating point
var aspectViewport = parseFloat(viewportHeight)/parseFloat(viewportWidth);
if (aspectImage > aspectViewport) { // height:100%;width:auto;
$(this).width("auto"); // Image aspect ratio > Viewport
$(this).height("100%");
} else { // height:auto;width:100%
$(this).width("100%"); // Image aspect ration <= Viewport
$(this).height("auto");
}
}

YouTube video height ratio, stretch to window width & stretching outside parent container

I have a YouTube embed inside a div. This div, .entry-content, has a max-width of 30em. The YouTube embed I want to be full window width, stretching outside the #container. To do this, I have a JS script which I have successfully used to make img elements stretch outside entry-content. The img has width:100vw determined in the CSS.
The iframe is within a div, fluid-width-video-wrapper, as the FitVids jQuery plugnin is used.
Here's the "stretch outside parent element" script:
var bodyWidth = $('body').width();
var elemWidth = $('.entry-content p').width();
var margin = bodyWidth-elemWidth;
var dividedMargin = margin / 2; // Divide the margin by 2
var negativeMargin = dividedMargin * -1; // set number to negative number
$('.entry-content iframe').css("margin-left", negativeMargin + "px");
I also use this for $(window).resize() so that it regardless of margins/paddings stretches full screen.
width:100vw width did not work for my iframe in the CSS, so I used a script from this fiddle.
$('.entry-content iframe').css({ width: $(window).innerWidth() + 'px', height: $(window).innerHeight() + 'px' */});
However, as you can see in that fiddle it makes the video full screen. I want full width with correct aspect ratio. What should I use as height in this script?
It has to be fluid, as the window size varies. I use it with $(window).resize(); too, which slows the page down as hell but that's not a problem for now.
No JS needed. Here's all you need to make a responsive player that's 100% of its parent's width and 16:9 aspect ratio.
body{
margin:0;
}
.videoContainer {
width: 100vw; /*now it is 100% of viewport (window) width.*/
display: inline-block;
position: relative;
}
.videoContainer::after {
padding-top: 56.25%; /* 16:9 ratio - divide height by width and multiply by 100 */
display: block;
content: '';
}
.videoContainer>iframe{
display:block;
width:100%;
height:100%;
position:absolute;
top:0;
left:0;
}
<div class="videoContainer">
<iframe src="https://www.youtube.com/embed/U5LwcvVAKDg" frameborder="0" allowfullscreen></iframe>
</div>
I think I've found a container-free solution now, that also works with my snap-to-edge-script.
$('.entry-content iframe').css({ width: $(window).innerWidth() + 'px', height: (($(window).innerWidth())*0.5625) + 'px' });
As the height of the video should be 56.25%, and the width is 100% of the window inner width, it means the height should be 56.25% of the window width.
is there a possibility if you use "100%" in stead of "px" you get what you're after?
edit *
i'm sorry i posted the answer and after i posted i red the comment of Ilpo Oksanen but i think this is the solution. and if not please elaborate your question

JavaScript and CSS positioning an image for any resolution

I am trying to create a simple slide show of an image that is set up in and background div. I dont have problem with creating the slideshow code but i have problem with positioning the image that should change according to the the width of others monitors resolution.
In the image bellow i described were i want to place the image. The image should be placed in the red div.
Here is the image that i want to put in the red div to be like a background. The resolution is (1900px x 500px)
Here is a model what i managed to do. I tried in java script code to declared a global variable sw which I assigned the window.innerWidth (sw=window.innerWidth), after in CSS using jquery selecting the red div $('#rotator') and assigned the sw ($('#rotator').css('width', sw)), but the result wasn't what I need to obtain. I obtained the image that was cropped from the right according to the screen resolution.
If someone know how to solve this question i will be greatful!
Here is my CODES:
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="jquery-2.1.0.js"></script>
<script type="text/javascript" src="function.js"></script>
<script src="jquery.easing.1.3.js"></script>
</head>
<body >
<div id="rotator"></div>
<div class='slider'></div>
</body>
</html>
CSS
body{
margin: 0px;
margin-left: 0px;
}
.slider{
width: 940px;
height: 360px;
background-color: #FFDF00;
margin: 0 auto;
position: absolute;
left: 15%;
top: 20px;
}
#rotator {
position: relative;
height: 500px;
}
.puzzle {
width: 100px;
height: 100px;
background-position: -100px 0px;
float: left;
}
And JavaScript that also contain the function of slideshow effect (that is working).
$(document).ready(init)
sw=window.innerWidth;
if (sw % 100 == 0) {
sw=window.innerWidth
}
else{
sw=Math.floor(sw/100)*100
}
//counter of slider
current_slide=0;
image_list=new Array
(
"img/1.jpg",
"img/2.jpg",
"img/3.jpg",
"img/4.jpg",
"img/5.jpg"
);
function init ()
{
$('#rotator').css('width', sw)
change(image_list[current_slide]);
//start timer
setInterval( "change(image_list[current_slide])" ,2500);
}
function change(bg_image){
// this function creats cells inside <div id = 'rotator'>
rot = $('#rotator'); //constructor
rot.empty();
for(y = 1; y<=5; y++)
{
for(x = 1; x<=sw/100; x++)
{
rot.append('<div class = "puzzle p-' + x + '-' + y + ' "></div>');
//select the <div> using his class and setting up the cells coordinates
$('.p-' + x + '-' + y).css('background-position', (-(x-1)*100) + 'px ' + (- (y-1)*100) + 'px').css('background-image','url('+bg_image+')');
$('.p-' + x + '-' + y).css('opacity', 0).delay(parseInt(Math.random()*1000)).animate({opacity: 1}, {duration: 1000})
}
}
current_slide++;
if(current_slide >= image_list.length)current_slide=0
}
Thank you for your time and consideration!
You either have to put the image into a container div who's width is dynamic to the size of the page and set width of the image inside it to 100%, or use the CSS attribute background-size: cover; (which is only compatible with newer browsers).
Images set as the background image for a div will simply fill their container and be clipped by that container as it shrinks past the dimensions of the background image unless background-size: cover; is used. To gain the same effect in older browsers, the aforementioned 100% trick is used.
Cross-browser style:
http://jsfiddle.net/2D5Vw/
New(ish)-School:
http://jsfiddle.net/HLf2Q/

How to align 2 images by their centre using JavaScripts

I have 2 images, one of them has a Mask area. And the other image can be seen through the Masked area of the above image. I want to centre the second image within the Mask area of the first image.
Currently I'm do scale the image to mach with the mask area using below function (It has 3 lines of code that I tried to with alignment - didnt work though),
function scaleimage(img){
img.style.height = 'auto';
img.style.width = 'auto';
//Getting the image hight and width
var imgW = img.clientWidth;
var imgH = img.clientHeight;
//Getting the mask hight and width
var maskH = data.result.mask.maskhight;
var maskW = data.result.mask.maskwidth;
var scaleH = maskH / imgH;
var scaleW = maskW / imgW;
// Scaling
if (scaleH < scaleW) {
img.style.height = maskH + "px";
img.style.width = Math.round(imgW * scaleH) + "px";
} else {
img.style.width = maskW + "px";
img.style.height = Math.round(imgH * scaleW) + "px";
}
//Align image - commented below code since it didnt work
/*img.style.top = Math.round((mask1H - imgH) / 2) + 'px';
img.style.left = '50%';
img.style.marginLeft = Math.round(imgW/2) + 'px'; */
}
Current and Expected result as an Illustration. IMAGE 1 has a Mask area that can see through, and IMAGE 2 is behind IMAGE 1, but align its top left to the Mask Area's Top left. What I want is, IMAGE 2 centre = Mask Area Centre
I tried few things and didn't get any of them quite right, any feedback would be really helpful
If I understand correctly from your code. You want to resize image to fix into your mask. I have write a demo using your function here. Because I dont know your real HTML, I use my own code with a predefined value of maskW and maskH.
Another thing to note: you should set the position property of the image style to another value than the default static value if you want to layout it manually. In the demo, I set the position value of img element to absolute.
There is a css solution for this if you'd like to try:
Html:
<div>
<img class="image" src="http://dummyimage.com/300x200/0000ff/ffffff&text=image" alt="image">
</div>
Css:
div {
width: 150px;
height: 100px;
margin: 50px auto 0;
position: relative;
background: url(http://dummyimage.com/150x100/000/fff&text=mask) no-repeat center center;
}
.image {
width: 80%;
top: 50%;
left: 50%;
position: absolute;
margin: -27% 0 0 -40%;
}
Fiddle
I see at least two approaches here:
use negative left margin of second image
<img id="img"/><img id="mask"/>
<script>
mask.style.marginLeft = (imgW + maskW) / -2;
mask.style.marginTop = (imgH - maskH) / 2;
</script>
show images as background of two divs (one embeds another). Set their width and height same values (of bigger image) and use center alignment of inner background. But then, if you're getting images by AJAX, you should retrieve also sizes of the images.
<div id="img">
<div id="mask"></div>
</div>
<style>
#img {
background-position: top left;
background-repeat: no-repeat;
}
#mask {
width: inherit;
height: inherit;
background-position: center center;
background-repeat: no-repeat;
}
</style>
<script>
var imgDiv = document.getElementsById('img'),
maskDiv = document.getElementById('mask');
imgDiv.style.width = imgW + 'px'; // from AJAX
imgDiv.style.height = imgH + 'px';
imgDiv.style.backgroundImage = "url('img.jpg')"';
maskDiv.style.backgroundImage = "url('mask.jpg')";
</script>
This is juts an idea and should work with fixes

HTML presentation slide, elements resize to keep the ratio

I am quite new to HTML and am not very fluent in HMTL terminology (English as well :). I am trying to create presentation slide (something like Powerpoint in MS Office). The functionality should be:
Everything (text, pictures, etc.) inside the slide must stay in position, size and ratio relative to the slide while the slide resizes.
The slide has 4:3 resolution.
The slide should be realized by <div> element.
The slide stays in the middle of the screen.
No inline styles should have to be used inside the slide.
Plain Javascript, css and HTML must be used.
So far I have managed to devise this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=utf-8" />
<title>
Image Resize Test
</title>
<style type="text/css">
*
{
margin: 0;
}
body
{
background-color: black;
width: 100%;
height: 100%;
}
#wrapper
{
font-size:100%;
background-color: white;
display: block;
position: absolute;
left: 50%;
}
#content
{
font-family:"Times New Roman";
font-size:80%;
}
h1 {font-size:2.5em;}
h2 {font-size:1.875em;}
p {font-size:0.875em;}
</style>
<script>
window.onload = function()
{
window.onresize();
}
window.onresize = function()
{
var width = window.innerWidth;
var height = window.innerHeight;
if (width / 4 > height / 3)
{
width = height / 3 * 4;
}
else
{
height = width / 4 * 3;
}
var wrapper = document.getElementById("wrapper");
wrapper.style.height = height + "px";
wrapper.style.width = width + "px";
wrapper.style.marginLeft = (-width/2) + "px";
wrapper.style.fontSize = (height) + "%";
}
</script>
</head>
<body>
<div id="wrapper">
<div id="content">
<H1>
aaaa
</H1>
<H2>
bbbb
</H2>
<p>cccc</p>
text
</div>
</body>
</html>
Is this a good solution to my problem or are there simpler/more efficient/more robust or more "pro" ways to do this?
Could it be solved without the Javascript? Atleast partially.
Is there a way to easily specify x/y offset relative to the side for any element within the slide (perhaps as attribute)?
How to apply styles for elements that would be variably deep within the slide element tree?
Help on any of the things I ask would be appreciated.
this is basically same as yours but without explicitly setting margin in javascript. so remove that part and make margin: 0 auto; at wrapper.
http://jsfiddle.net/btevfik/VuqJX/
it seems like you can keep the aspect ratio with only css and html but as far as i can tell this only works when you resize width of the window. when you change height it wont work.
Maintain the aspect ratio of a div with CSS

Categories