I don't know if this question has an easy or hard answer.
The situation is that I have an element on the page with negative margin:
.element {
margin-left: -195px;
}
It works well with a screen size 1440x532 (check with Chrome's inspector element).
What I want is kind of simple to explain.
I want an increase of 1 pixel (for instance) in the margin-left of the element anytime the window is larger by one pixel:
So, if window size is 1441, the margin-left of the element be -194px. If the window size is 1451, the margin-left of the element be -184px.
In the same way, I want this to work from 1440px upwards.
IMPORTANT NOTE: What I want is a dynamic value for the margin-left that increases based on screen size and not a kind of media query which would make the value always remain the same between an interval of screen sizes. What I want would force me to add a massive number of media queries.
Is this possible with javaScript or jQuery? (or even CSS?)
The Jquery solutions that other users gave you works perfectly for this use, but if you prefere you can also use a CSS-only alternative (it works even if the user has disabled scripts!).
It has got also a good support among browsers
You can implement your CSS in this way:
#element{
margin-left: -195px;
}
#media screen and (min-width: 1440px){
#element{
margin-left: calc(-195px + 100vw - 1440px); //100vw is the width of the screen
}
}
It adds a pixel for each pixel above 1440
Tell me if this is what you mean
This is not possible with CSS since there is no property or method to capture the window size. If there would be, this could be done using calc().
However, this is possible with JavaScript.
function resizeScreen() {
var windowWidth = $(window).width();
var $element = $('.element');
if (windowWidth > 1440) {
// Calculate the new (negative) margin by subtracting the windows width by 1440 (e.g. 1500-1440 = 60). The new margin would be: -195 + 60 = -135.
var newMargin = $element.css('margin-left') + (windowWidth - 1440);
$('.element').css('margin-left', newMargin)
}
}
$(window).resize('resizeScreen');
Yes is it possible with Jquery with resize()
$(window).resize(function() {
if (($(window).width() <= 1441)) {
$('.element').css('margin-left', "-194px")
}else if($(window).width() <= 1451){
$('.element').css('margin-left', "-184px")
}
});
But i suggest to you to use media queries with css:
#media screen and (max-width: 1441px) {
.element {
margin-left: -194px;
}
}
#media screen and (max-width: 1451px) {
.element {
margin-left: -184px;
}
}
Related
I have a UI element that is designed to work best at exactly '200px' width. But if the size of the UI needs to change based on window / media size, it would be a pain to have to adjust this Component bit by bit and change the width away from 200px.
Is changing the size of a component by using transform: scale(x) to adjust to window / media size an acceptable practice? Is it costly in performance? In practical reality, window / media size will be set from the beginning, so the scale function would only have to be run once anways.
if (screen width < 600px) {
element.style.transform = "scale(.7)"
} else {
element.style.transform = "scale(1)"
}
Is transform: scale(x) a costly operation?
No, the transform operation doesn't require a DOM update. A browser makes a rendering update. Its pros are its performance costs are low, it works fast. Its cons are scaling could greatly downgrade its visual quality (for example, blur images), the downscaled component with its content could be hard to use or read.
A JS usage to set CSS is definitely a costly way to make changes. The most efficient way is to use CSS only (media query).
It looks weird to 'scale' a component for a small screen. A common way to solve it now is to make a responsive layout. But think, you don't need to let its content be dynamic inside. Such a task could be solved with CSS. Just make another step forward. Tie the inner content with outer sizes at CSS - use em/rem units instead of px for all its measures. And the media query will change its base font-size only. Different size, no potential scaling visualization issues, same content position. :)
The CSS could be like this below. Sorry, a minimal working HTML, CSS, JS to demonstrate the concept. To check JS in different screen sizes in this snippet - change your screen size, refresh the snippet. The CSS option works without a refresh.
function setSizeJs() {
const element = document.getElementById('target-element-px');
element.style.transform = window.innerWidth < 600 ? 'scale(.7)' : 'scale(1)';
}
.parent {
font-size: 14px;
}
#target-element-px {
/* original width */
width: 200px;
/* colorize element to show its size */
background-color: green;
}
#target-element-em {
/* main style, will be applied always */
/* an equivalent of 'width 200px' in EMs, where EM is taken as '14px' from the 'parent' class */
width: 14.28571428571429em;
background-color: grey;
}
#media screen and (max-width: 600px) {
/* additional style, will be applied only when the screen size will be less than 600px */
/* it will overwrite the main style */
#target-element-em {
font-size: 0.7em;
}
}
<div class="parent">
<div id="target-element-px" class="target-element" onload="setSizeJs">
Some content for original 200px width
</div>
<div id="target-element-em" class="target-element">
Some content for original 200px width
</div>
</div>
I customized the sap.m.CustomTile with some sap.m.FormattedText. I need this CustomTile to be resizable according to display resolution e.g. from 500 px to 320 px. I used for this:
#media only screen and (max-width: 500px) {
.tileSmall.sapMCustomTile {
width: 80.9vw !important;
height: 80.9vw !important;
}
}
#media only screen and (max-width: 320px) {
.tileSmall.sapMCustomTile {
width: 200px !important;
height: 200px !important;
}
}
I can not use % because it behaves strange in my app. So I am trying to use vw instead. I did demo. I would like to keep it all the time as it for resolution 530px in the:
But when the resolution is change to e.g. 417px I got:
The resolution 357px I got:
Is there any way how to anchor footer and subfooter (last two rows)?
Or how to change height of the gap (created by br tag) according to tile height?
Thanks for any advice.
Because you are using VBox inside the custom tile, it is fairly easy to achive what you want. You can check out the Size Adjustments Explored demo for more examples.
The basic idea is that you can play around with the grow / shrink factors of each item inside the VBox. By default, all the items of a VBox are treated equally and are stretched to fill in the available space. Because you want your header and footer to be fixed, you should set the shrinkFactor (default = 1) and growFactor(default = 0) to 0 for these items.
The center of the tile should be just "whitespace" to fill in the rest of the available space, so you can give it growFactor and shrinkFactor equal to 1. You also don't need to put brs in there, because the item will grow / shrink dynamically to fill in the remaining space.
You can add these factors for each UI5 Element using the layoutData aggregation and passing a FlexItemData element.
Another small change is that you should specify width: "100%" and height: "100% for the VBox to make sure its size adjusts based on the tile's size.
Header / footer
new sap.m.FormattedText({
htmlText: "whatever you have now",
layoutData: new sap.m.FlexItemData({
shrinkFactor: 0
})
});
Center
new sap.m.FormattedText({
htmlText: "no need to put anything here",
layoutData: new sap.m.FlexItemData({
shrinkFactor: 1,
growFactor: 1
})
});
You can find a working version of this solution here: http://jsbin.com/tirizanaje/1/edit?html,css,output
Is there anyway to specify an aspect ratio in CSS such as 4:3 or 16:9 and then have the div (container) block fit the current window width and height?
Quite a simple question hopefully it has a relatively simple answer.
Edit: those still interested a great example of achieving this using only styles would be Bootstrap's responsive helpers classes.
For this I fear you'll need some JS. I used jQuery here:
function preserveAspect() {
var scaled = $("#scaled");
scaled.height("100%");
scaled.width("100%");
scaled.css("box-sizing", "border-box");
var ratio = 16/9;
var w = scaled.outerWidth();
var h = scaled.outerHeight();
if (w > ratio*h) {
scaled.width(ratio*h);
// horizontal centering is done using margin:auto in CSS
} else if (h > w/ratio) {
var newHeight = w/ratio;
scaled.height(newHeight);
// for vertical centering:
scaled.css({marginTop: ($("body").height()-newHeight)/2});
}
}
$(document).ready(function() {
preserveAspect();
$(window).resize(preserveAspect);
});
Explanation:
First we scale up our div to 100% in width and height so that we know how much space it has.
Then we look up if it is too wide which means that the width is more
than height times ratio.
If so, change width. Height is at 100% already.
Otherwise it might be too high, in which case we want the scale to be width divided through ratio. To center vertically we use a margin-top set to (window_height - element_height) / 2.
If neither of both rules apply, the div is scaled properly already.
In the end we add event listeners for when document is fully loaded and whenever the window size changes.
Full code and working example here:
http://jsbin.com/efaRuXE/5/
This question's a few weeks old now, but there is a pure CSS way to accomplish this. Thanks to Danield for using it to answer this question. It uses the vw and vh units, like so:
#wrapper {
height:75vw;
max-height:100vh; /* max-height / height = aspect ratio */
width:100vw;
max-width:133.3333vh; /* max-width / width = aspect ratio */
position:absolute;
}
The bad news is that support is iffy in current mobile browsers and in IE before version 11.
Found a way. This may be rough but it should get you going. Set the element's height to zero and then use a percentage for the padding.
jsFiddle example
For example, 4:3:
div {
height: 0;
padding-bottom: 75%;
background: #999;
}
For example, 16:9
div {
height: 0;
padding-bottom: 56%;
background: #999;
}
Unfortunately no.
I've proposed once on www-styles WG # W3C construction like this:
div {
width: 50%;
height: width(56.25%); /* 16:9 ratio */
}
but no one from browser vendors expressed any interest at that moment.
And anyway that solution above allows to define ratio of boxes only. But layout model used by CSS does not allow to define inscribing declaratively.
How can I make an alert popup if the width of the page is less than 1200px, and made responsive?
Thanks!
You can use something like the breakpoints module. Then you setup a breakpoint to trigger at 1200px and show a dialog and either add a css class that changes the layout, or use straight javascript to make the changes.
breakpoints(1200, function(oldPoint, newPoint) {
alert('The screen width just changed');
});
if you just wanted native jQuery:
$(window).resize(function() {
var width = $(window).width();
if (width < 1200){
alert('Your screen is too small');
}
});
For completeness, heres the CSS media query (still doesn't take care of the alert, but can help with making the website "responsive").
/* some normal style */
.myclass {
font-size: 22pt;
}
/* alter the style when the screen's smaller */
#media screen and (max-width: 1200px) {
.myclass {
font-size: 18pt;
}
}
For future Googlers, a 2019 solution is to use JavaScript's window.matchMedia(). It is supported in all major browsers and IE 10 onwards.
You can use it like this:
if (window.matchMedia('(max-width: 1200px)').matches) {
// functionality for screens smaller than 1200px
}
To make this responsive, you just need to wrap it in a resize function:
$(window).resize(function() {
if (window.matchMedia('(max-width: 1200px)').matches) {
// functionality for screens smaller than 1200px
}
});
This is arguably the most easiest way to check a screen size and it doesn't bloat the code.
Check the Mozilla docs about matchMedia to learn more and this one for more info on Testing media queries programmatically.
I have my div (#box) centering in the middle of the browser window which is groovy for browsers that are 600px vertical or taller. If the window is smaller than that, content at the top of the div gets sheared off, and the scroll bar only scrolls the page up (when I pull the scroll bar down), so it's impossible to see anything hidden above the top edge of the window even when the scroll bar is at its top-most position.
Here's how I center my div--you can see why the top of the div gets cut off in smaller browser windows.
{position: absolute; top: 50%; left: 50%; width: 1930px; height: 607px; margin-left: -965px; margin-top: -302px;}
(It's really wide to accommodate the animation working on even the widest screens--the width isn't an issue.)
Here's a page to look at: http://ianmartinphotography.com/test-site/
And my CSS: http://ianmartinphotography.com/test-site/css/basic.css
This is easily fixed in my CSS style sheet, but it seems like I can't have it both ways for monitors greater than 600px and monitors smaller than 600px.
So, how do I detect a browser window size and then select one of two different CSS style sheets? One for small windows, another for larger windows? Is there a jquery script that will do this for me?
Or, is there another way to make my div center in the middle of the browser window with CSS that will allow scrolling so that the top of the div can be accessed on smaller browser windows?
Thanks for your thoughts!
#media queries are my preference (saw that you don't like them as a solution per se), but they really could do the trick - especially if you adjust your css a little to accommodate.
<link...media="only screen and (max-height: 600px)" href="small-device.css" />
small-device.css = div.container { ... height:500px; margin:50%; ...}
<link...media="only screen and (min-height: 601px)" href="big-device.css" />
big-device.css = div.container {... height:600px; margin:50%; ...}
You may also have a little more luck by removing your absolute positioning and taking advantage of normal document flow. It would help you to add things like { overflow-y:scroll; }
to those hidden-by-screen-height divs.
I think in the end, if you're trying to design around hand-held devices, you'll need media queries to some extent. My Android screen (for example) has 3 display options (low, medium, hi def). All 3 crop pages differently.
You can determine window size by Jquery
$(window).width();
$(window).height();
or
$(document).width();
$(document).height();
then change css
$("link").attr("href", "blue.css");
Something like this:
$(document).ready(function(){
if($(document).height() > 600 or $(window).height() > 600){
$("link").attr("href", "600+.css");
} else {
$("link").attr("href", "600-.css");
}
});
A solution that works in all major browsers. No JS needed. Vertically/horizontally centered, scrollable, sticks to the top when content is larger than viewport.
HTML:
<div id="body">[your content goes here]</div>
CSS:
html, body {
width: 100%;
height: 100%;
}
html {
display: table;
}
body {
display: table-cell;
vertical-align: middle;
}
#body {
margin: 0 auto;
}
Don't forget to apply the last rule, it will actually perform the horizontal centering.
Just did a bit of googling and found this:
http://www.ilovecolors.com.ar/detect-screen-size-css-style/
does that work for you?
Try the Less CSS Framework: http://lessframework.com/,
You do not need JavaScript, but rather you can use CSS #Media to set styles based on resolution/ screen size.
Best of luck
Use the following JavaScript conditional to detect screen size.
function x() will handle inserting the CSS link in the <head> tag. All you need to do is call the function and pass in the CSS file name.
< script type = "text/javascript" >
<!--
function x(y) {
var styles = y;
var newSS = document.createElement('link');
newSS.rel = 'stylesheet';
newSS.href = 'data:text/css,' + styles;
document.getElementsByTagName("head")[0].appendChild(newSS);
}
if ((screen.width >= 1024) && (screen.height >= 768)) {
x('file.css');
}
else {
x('file1.css');
}
//-->
< /SCRIPT>
If "document_height" not work, try "window_height" i comment it in code!
$("link").attr("href", "css_file_path"); // here must insert path to your css, replace it in the code below
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function(){
document_height = $(document).height();
//window_height = $(window).height();
//if(window_height > 600){
if(document_height > 600){
alert('Bigger than 600px height: ' + $(document).height());
$("link").attr("href", "600+.css"); // Here load css if window is bigger then 600px;
} else {
alert('Smaller than 600px height: ' + $(document).height());
$("link").attr("href", "600-.css"); // Here load css if window is smaller then 600px;
}
});
</script>