Reputation: 129
I know we can write media queries. But that we can do if we need a property to change for a range of screen width. My question is can we set width to be a fraction of the current screen width ?
For example, width = 0.5*current size, will always set the width to half of the current width ?
Upvotes: 0
Views: 2602
Reputation: 2114
in your example just do
width: 50vw
It will always occupy 50% of the current screen. Which work even you manually resize the window, if you wanna also change the div height when screen height changed. just add:
height: 50vh
if you wanna set the div to occupy all the screen, just do.
{
width: 100vw;
height: 100vh;
}
for the definition of vw
or vh
, go to https://developer.mozilla.org/en/docs/Web/CSS/length
Upvotes: 0
Reputation: 191
Things break down when you get to fractional pixels, but if your percentage values yield integer pixel value (e.g. 50.5% of 200px in the example) you'll get sensible, expected behavior.
For e.g.
<div id="percentage">
<div class="first">50%=100px</div>
<div class="second">50.5%=101px</div>
<div class="third">51%=102px</div>
</div>
<br />
<div id="pixels">
<div class="first">50px</div>
<div class="second">50.5px</div>
<div class="third">50.6px</div>
<div class="fourth">51px</div>
</div>
#percentage
{
width: 200px;
color: white;
}
#percentage .first
{
width: 50%;
height: 20px;
background-color: red;
}
#percentage .second
{
width: 50.5%;
height: 20px;
background-color:green;
}
#percentage .third
{
width: 51%;
height: 20px;
background-color:blue;
}
#pixels
{
color: white;
}
#pixels .first
{
width: 50px;
height: 20px;
background-color: red;
}
#pixels .second
{
width: 50.5px;
height: 20px;
background-color:green;
}
#pixels .third
{
width: 50.6px;
height: 20px;
background-color:blue;
}
#pixels .fourth
{
width: 51px;
height: 20px;
background-color:red;
}
Upvotes: 0
Reputation: 644
Why don't you just use '%' of the screen width
somecssselector{
width:50%;
}
but it won't work on some absolutely and relatively positioned elements which is nested .in that case like the above mentioned answers you must use 'vw'
Upvotes: 0
Reputation: 3559
Try with the resize
event:
$( window ).resize(function() {
var current_width = $(this).width();
var new_width = current_width * 0.5;
$( selector ).css('width' , new_width+'%');
});
Upvotes: 0
Reputation: 17687
for width use vw
where 100vw
= viewport width ( the browser window width )
for height use vh
where 100vh
= viewport height
so for what you want use width:50wh
for more info read here viewport units
Upvotes: 0