Automatically change the html element size using css.

Last updated 4 years, 11 months ago | 1313 views 75     5

Tags:- CSS

CSS | Fluid typography

Changing size of text, image, div or any html element automatically without using any jquery or media queries.

It is a fluid type technique that doesn't require any JavaScript.

Using viewport units and calc() function, we can adjust font-size (and other properties) based on the size of the screen. So rather than always being the same size, or jumping from one size to the next through media queries, the size can be fluid.

Credit Mike Riethmuller:

selector {
  properties : calc([minimum size]px + ([maximum size] - [minimum size])
 * ((100vw - [minimum viewport width]px) 
/ ([maximum viewport width] - [minimum viewport width])));
}


Explan:

Selector : required | selector can be any valid selector (i.e: id, class, html tags etc.)
Properties : required | Properties can be any valid properties (i.e: font-size, height, width etc.)

body {
  font-size: calc(14px + (26 - 14) * ((100vw - 300px) / (1600 - 300)));
}

In the above css code would scale font-size of body text from a minimum of 14px at the smallest viewport width of 300px to a maximum of 26px at the largest viewport width of 1600px.

<!DOCTYPE html>
<html>
<head>
<style>
body {
  font-size: calc(14px + (26 - 14) * ((100vw - 300px) / (1600 - 300)));
}
</style>
</head>
<body>

<h1>This is a Heading</h1>

<p>This is a paragraph. This is a paragraph. This is a paragraph.</p>

</body>
</html>

In the above example font size of the body will automatically get change based on device viewport. The minimum of font size can be 14px and the maximum font size can be 26px

 


 

Let's see an example of resizing image:

<!DOCTYPE html>
<html>
<head>
<style>

/* style with calc() function */
img {
  width: calc(100px + (800 - 100) * ((100vw - 300px) / (1600 - 300)));
}
</style>
</head>
<body>

<!-- image -->
<img src="workplace.jpg">

</body>
</html>

In the above example image size of workplace.jpg will automatically get change based on device viewport. The minimum of image width can be 100px and the maximum of image width can be 800px. You can also define height similarly.

Here's the code:

img{
height:calc(50px + (800 - 50) * ((100vw - 300px) / (1600 - 300)));
}

This code change height of the image from 50px to 800px.

 



Let's see an example of resizing div container:

<!DOCTYPE html>
<html>
<head>
<style>

/* style div */
div{
width: calc(300px + (800 - 300) * ((100vw - 300px)/(1600 - 300)));
height: calc(100px + (200 - 100) * ((100vw - 300px)/(1600 - 300)));
font-size: calc(16px + (100 - 16) * ((100vw - 300px)/(1600 - 300)));
background:red;
color: white;
text-align: center;
}

</style>
</head>
<body>

<!-- div tag -->
<div>
This is a div
</div>

</body>
</html>


In the above example div size will automatically get change based on your device viewport. In this example font size of text, height and weight of div all get change simultaneously.