Taming the VW-Unit (CSS) [duplicate] - html

I want to specify my font size using vw, as in
font-size: 3vw;
However, I also want to limit the font size to say 36px. How can I achieve the equivalent of max-font-size, which does not exist--is the only option to use media queries?

font-size: 3vw; means that the font size will be 3% of the viewport width. So when the viewport width is 1200px - the font size will be 3% * 1200px = 36px.
So a max-font-size of 36px can be easily implemented using a single media query to override the default 3vw font-size value.
Codepen demo (Resize Browser)
div {
font-size: 3vw;
}
#media screen and (min-width: 1200px) {
div {
font-size: 36px;
}
}
<div>hello</div>
Update: With the new CSS min() function, we can simplify the above code - without using media queries (caniuse)
div {
font-size: min(3vw, 36px);
}
In the above example, the font-size will be at most 36px, but will decrease to 3vw if the the viewport is less than 1200px wide (where 3vw computes to a value less than 36px )
That being said, using viewport units for font-size in the above way is problematic because when the viewport width is much smaller - say 320px - then the rendered font size will become 0.03 x 320 = 9.6px which is very (too) small.
In order to overcome this problem, I can recommend using a technique called Fluid Type AKA CSS Locks.
A CSS lock is a specific kind of CSS value calculation where:
there is a minimum value and a maximum value,
and two breakpoints (usually based on the viewport width),
and between those breakpoints, the actual value goes linearly from the minimum to the maximum.
So let's say we want to apply the above technique such that the minimum font-size is 16px at a viewport width of 600px or less, and will increase linearly until it reaches a maximum of 32px at a viewport width of 1200px.
This can be represented as follows (see this CSS-tricks article for more details):
div {
font-size: 16px;
}
#media screen and (min-width: 600px) {
div {
font-size: calc(16px + 16 * ((100vw - 600px) / 600));
}
}
#media screen and (min-width: 1200px) {
div {
font-size: 32px;
}
}
Alternatively, we could use this SASS mixin which does all of the math for us so that the CSS would look something like this:
/*
1) Set a min-font-size of 16px when viewport width < 600px
2) Set a max-font-size of 32px when viewport width > 1200px and
3) linearly increase the font-size from 16->32px
between a viewport width of 600px-> 1200px
*/
div {
#include fluid-type(font-size, 600px, 1200px, 16px, 32px);
}
// ----
// libsass (v3.3.6)
// ----
// =========================================================================
//
// PRECISE CONTROL OVER RESPONSIVE TYPOGRAPHY FOR SASS
// ---------------------------------------------------
// Indrek Paas #indrekpaas
//
// Inspired by Mike Riethmuller's Precise control over responsive typography
//
//
// `strip-unit()` function by Hugo Giraudel
//
// 11.08.2016 Remove redundant `&` self-reference
// 31.03.2016 Remove redundant parenthesis from output
// 02.10.2015 Add support for multiple properties
// 24.04.2015 Initial release
//
// =========================================================================
#function strip-unit($value) {
#return $value / ($value * 0 + 1);
}
#mixin fluid-type($properties, $min-vw, $max-vw, $min-value, $max-value) {
#each $property in $properties {
#{$property}: $min-value;
}
#media screen and (min-width: $min-vw) {
#each $property in $properties {
#{$property}: calc(#{$min-value} + #{strip-unit($max-value - $min-value)} * (100vw - #{$min-vw}) / #{strip-unit($max-vw - $min-vw)});
}
}
#media screen and (min-width: $max-vw) {
#each $property in $properties {
#{$property}: $max-value;
}
}
}
// Usage:
// ======
// /* Single property */
// html {
// #include fluid-type(font-size, 320px, 1366px, 14px, 18px);
// }
// /* Multiple properties with same values */
// h1 {
// #include fluid-type(padding-bottom padding-top, 20em, 70em, 2em, 4em);
// }
////////////////////////////////////////////////////////////////////////////
div {
#include fluid-type(font-size, 600px, 1200px, 16px, 32px);
}
#media screen and (max-width: 600px) {
div {
font-size: 16px;
}
}
#media screen and (min-width: 1200px) {
div {
font-size: 36px;
}
}
<div>Responsive Typography technique known as Fluid Type or CSS Locks.
Resize the browser window to see the effect.
</div>
Codepen Demo
Update: We can use the new clamp() CSS function (caniuse) to refactor the above code to simply:
div {
font-size: clamp(16px, 3vw, 32px);
}
see MDN:
clamp() allows you to set a font-size that grows with the size of the
viewport, but doesn't go below a minimum font-size or above a maximum
font-size. It has the same effect as the code in Fluid Typography but
in one line, and without the use of media queries.
p { font-size: clamp(1rem, 2.5vw, 1.5rem); }
<p>
If 2.5vw is less than 1rem, the font-size will be 1rem.
If 2.5vw is greater than 1.5rem, the font-size will be 1.5rem.
Otherwise, it will be 2.5vw.
</p>
--
Further Reading
Fluid Typography
How Do You Do max-font-size in CSS?
Fluid Responsive Typography With CSS Poly Fluid Sizing
Non-linear interpolation in CSS

Here is another idea. The calc function uses double precision float. Therefore it exhibits a step function near 1e18. For example,
width: calc(6e18px + 100vw - 6e18px);
This will snap to values 0px, 1024px, 2048px, etc. see pen https://codepen.io/jdhenckel/pen/bQNgyW
The step function can be used to create abs value and min/max with some clever maths. For instance
max(x, y) = x - (x + y) * step(y - x)
Given step(z) is zero when z<0 and one otherwise.
just an idea, not very practical, but maybe fun to try.
(Caution: this technique depends on an implementation detail that is not in any specification; currently, it works in Chrome and Safari, but not in Firefox, Edge or Internet Explorer, which don’t use double-precision floats for CSS values.)
UPDATE: this post is no longer useful (was it ever?) since CSS now supports min, max, and clamp.

Another way increases font size slowly, this will not limit max font size, but even on very wide screens, it will look better. Does not answer question in perfect way, but its 1 line...
font-size: calc(16px + 1vw);
Update: CSS improved and i recommend using clamp(min, preferred, max) function:
font-size: clamp(12px, 2vw, 20px);

At some point, the font-size exceeds the 36px scale right, find that. Assuming, it exceeds when the width: 2048px:
#media screen and (min-width: 2048px) {
.selector {
font-size: 36px;
}
}
Yes, unfortunately you need to use the #media queries. I hope that doesn't affect anything.

According to this website (there are ads in this site),
If you don't want to use clamp():
font-size: 24px;
font-size: min(max(3.5vw, 16px), 40px);
Line one for IE.
Line two for others, means font-size:3.5vw, max-font-size:40px, min-font-size:16px.

Related

How to decease or increase sizes in CSS all togther?

I'm coding for a responsive website using basic CSS and HTML(without bootstrap).
now I wanna change the size of elements(caption font, picture size, etc) to be set up for size of various devices.
for example I have codes like below:
.footer-link{
font-size: 14px;
width: 80%;
padding-bottom: 20px;}
and want to reduce 10% of sizes by a code to have sth like:
.footer-link{
font-size: 12px;
width: 72%;
padding-bottom: 18px;}
I know about media . but with that I still need to rewrite every single code and size in each media! Actually i want to avoid rewriting by having some especial code that reduces all sizes in a media itself alone.
but I don't have any idea of doing this.
any recommendation please?
you can add #media query in css and add the max width in which the inner code will be vaild. for example:
#media (max-width: 600px) {
.footer-link{
font-size: 12px;
width: 72%;
padding-bottom: 18px;}
}
now only when the device have maximum width of 600px this code will be executed.
Also you can change the size to make it em,rem, vw, vh, % instead of normal px preoperty to make it more dynamic.
you can read more about how to make responsive website from here
Here is an example for a small device:
.footer-link{
font-size: 14px;
width: 80%;
padding-bottom: 20px;
}
#media (min-width: 576px) {
.footer-link{
font-size: 12px;
width: 72%;
padding-bottom: 18px;}
}
to do other sizes you just create a new media query and change the size, bootstrap 4's breakpoints look like this:
xs = Extra small <576px.
sm = Small ≥576px.
md = Medium ≥768px.
lg = Large ≥992px.
xl = Extra large ≥1200px.
Three methods:
ONE:
1) Use the rem scaling measurement
Do NOT use px, instead use the rem scaling measurement. rem is Root em and everything works from this :root value, this hiarachy is critical for step 2:
2) Use #media queries to control the root-em size
Once set, you can run a media query simply controlling the root-em (rem) value for each of your #media queries.
Example:
:root {
font-size: 16px; /* this sets 1rem */
}
.footer-link{
font-size: 0.9rem; /* 16 x 0.9 */
width: 5rem;
padding-bottom: calc(100% - 5rem);
}
#media screen and (max-width:500px){
:root {
/* Everything is magically a bit smaller */
font-size: 14px;
}
}
NOTE: Setting font-size: in the html{ ... } can maybe overwrite the browser font-size setting (unconfirmed by me).
TWO:
Using ONE above but also with CSS Variables for ease of adjustment.
Exampe:
:root {
/* percentage */
--widthValue: 80%;
font-size: 16px; /* this is still needed as sets 1rem */
}
.footer-link{
font-size: 1rem;
width: var(--widthValue);
padding-bottom: calc(100% - var(--widthValue));
}
#media screen and (max-width:500px){
:root {
/* Everything is magically a bit smaller */
font-size: 15px;
--widthValue: 76%;
}
}
This allows you to fine tweak adjustments that can not easily be scoped by rem values. Read more here.
THREE:
There was a third method in my mind when I started writing this answer but I think the two above should between them more than easily cover what you're looking for.
I know about media . but I still need to rewrite every single code and size in each media
Yes, you will need to update your basic CSS as written in your question, but that's inevitable as you're replacing static code with varaible driven code.
The solution I present is Dont Repeat Yourself (huh?) -- you only need to change one value in the #media query and all the styles cascade from that one simple change.
The sample code you provided is not a sample of responsive website. To be responsive we have to redesign and reorder elements. Some elements like images and backgrounds may need to be resized but the fonts, widths and paddings etc. should not be smaller when the screen is smaller. For example if you reduce the width of elements when the window is smaller in a small window you have nothing rather than elements with width:1% !
So I think you need a kind of ZOOM which may be appropraite for games and somethings special.
Besides without using CSS media queries and without rewriting css rules, the only way to zoom everything is JS codes. So I write simple sample to show how you can zoom everything according to the window size.
Please try resizing the window to check the effect:
var myDesignWidth=500; //this is the initial width which you design everything
$(window).on("load resize",function(){
var newZoom=$(window).width() / myDesignWidth;
$("body").css({"zoom":newZoom});
})
.footer-link{
font-size: 14px;
width: 80%;
padding-bottom: 20px;
display:inline-block;
background:url('https://d1o2pwfline4gu.cloudfront.net/m/t/13116/13106367/a-0270.jpg');
background-size:cover;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="footer-link">This is a footer link with background</a>

Fluid Typography

I'm trying to use fluid typography and the goal is to scale the text between screen sizes 300px and 1160px.
So at 1160px I want 56px H1 and mobile 30px.
The problem I'm having is the H1 increases in size past the 1160px and keeps increasing.
h1 {
font-size: calc(30px + (56 - 30) * ((100vw - 300px) / (1160 - 300)));
}
<H1>Fluid Typography</H1>
You need to limit fluid calculation of h1 between media queries. Try this:
h1 { font-size: 30px; }
#media (min-width: 300px) {
h1 {
font-size: calc(30px + (56 - 30) * ((100vw - 300px) / (1160 - 300)));
}
}
#media (min-width: 1160px) {
h1 {
font-size: 56px;
}
}
First, the minimum font-size needs to be provided: that's the first line. Then between two breakpoints you introduce fluid calculation which, at 300px gives exactly 30px of font-size, and again at 1160px calculates to exactly 56px. After 1160px you keep it at 56px again using media query. This way you have a graceful transition between static and fluid typography between the set breakpoints.
You can find more examples of this here:
https://www.madebymike.com.au/writing/fluid-type-calc-examples/
or here:
https://www.smashingmagazine.com/2016/05/fluid-typography/
Let me know if you need more examples, I've done a lot of these.
If you are using SCSS you can use the following Mixin:
https://gist.github.com/MColl92/3229098c32e20c1d5593865a7e3ea3da
$min_screen_width: 360px;
$max_screen_width: 1448px;
$min_font_size: 38px;
$max_font_size: 52px;
#mixin fluid-type($min-vw, $max-vw, $min-font-size, $max-font-size) {
$u1: unit($min-vw);
$u2: unit($max-vw);
$u3: unit($min-font-size);
$u4: unit($max-font-size);
#if $u1 == $u2 and $u1 == $u3 and $u1 == $u4 {
& {
font-size: $min-font-size;
#media screen and (min-width: $min-vw) {
font-size: calc(
#{$min-font-size} + #{strip-unit($max-font-size - $min-font-size)}*
((100vw - #{$min-vw}) / #{strip-unit($max-vw - $min-vw)})
);
}
#media screen and (min-width: $max-vw) {
font-size: $max-font-size;
}
}
}
}
#function strip-unit($value) {
#return $value / ($value * 0 + 1);
}
To apply globally:
Define your minimum and maximum screen widths
Define your min and max font size for H1 element in px
Apply fluid-type mixin to root element (html or body selector).
Generate px to rem table from https://nekocalc.com/px-to-rem-converter.
(NOTE: you will need to set the root font size to you max_font_size when generating)
Assign REM values to font-size as required

Changing font-size on root doesn't affect #media queries [duplicate]

This question already has answers here:
Is is possible to overwrite the browser's default font-size in media queries using EMs?
(2 answers)
Closed 5 years ago.
I'm working in a page that has
html {
font-size: 62.5%;
}
That means 1rem = 10px instead of 1rem = 16px So far, so good.
The problem is that it doesn't affect #media queries.
/*
it should change at 600px and not 960px.
the #media ignores the 62.5%;
*/
#media (min-width: 60rem) {
.el {
background: blue;
}
}
Check this codepen to see the issue.
http://codepen.io/sandrina-p/pen/bqGZjE
I tested on a retina monitor, with Chrome and Firefox. On Safari the issue doesn't happen.
Any solution?
I found the issue.
In #media you need to use em and it will always read the default browser size, ignoring your custom font-size. The same doesn't happen with rem.
So in this case, you need to set 37.5em (600/16), and it will change the at 600px in every browser including safari.
https://zellwk.com/blog/media-query-units/
(...) the only unit that performed consistently across all four browsers is em. There aren’t any differences between em and rem with the exception of bugs found on Safari.
(...) Unfortunately, px media queries remained at 400px in the third experiment, which makes it a no-go if you intend to support users who change their browser’s font-size value.
Hence, my conclusion after these experiments is: Use em media queries.
#media screen and (max-width: 37.5em) {
.el {
background: blue;
}
}
No. It doesn't have to do anything with you html font-size or your .el font-size. Because 1rem is 16px. So you have to calculate it as per 16px.
#media (min-width: 37.5rem) {
.el {
background: blue;
}
}
This would be your 600px media queries breaks.
Try this
<div class="el">
hey there
</div>
// =========== basic template =========== //
$safeArea: 1rem;
body {
font-family: sans-serif;
}
// ======== actual codepen code ========= //
html {
font-size: 62.5%;
}
.el {
background: red;
font-size: 1.6rem;
}
/* it should change at 600 px and not 960px.
the #media ignores the 62.5%;
*/
#media screen and (max-width: 60rem) {
.el {
background: blue;
}
}
see this codepen - http://codepen.io/anon/pen/aJbxOQ

Are CSS #media query statements cascading properties specified in em unit?

Assuming there are two CSS #media queries as in the following sample:
#media screen and (min-width:720px) {body{font-size: 2em;}}
#media screen and (max-width:1280px) {body{font-size: 0.5em;}}
what would be expected body font-size if page is viewed in the device with 1280 x 800 screen resolution (namely: 2em, 0.5em or 1em)?
For added clarity: in this context 'cascading' means that the result will be calculated by consequently applying all matching cases, i.e. 2em * 0.5em.
By analogy, having CSS like this:
TEST1<div style="font-size:2em">TEST2<div style="font-size:0.5em">TEST3</div></div>
the font-size of inner TEST3 text will be 1em (2em * 0.5em = 1em, i.e. the same as of original TEST1).
See on jsfiddle: https://jsfiddle.net/bj3xsanq/2/
In your example, font size will end up being 0.5em, because the second font-size definition overrides the first one according to the usual CSS rules.
And if you would change the order of the two media queries, then the resulting font size would be 2em.
Here's a snippet which demonstrates this.
Note that the text will be bold (1st media query), italic (2nd media query) and red (the definition from the 2nd media query "wins" according to the usual CSS rules).
Font-size will be set to 0.5em, because the 2nd definition overwrites the first one (NOT 1em, as it would be if the 2nd definition would be applied cumulatively "on top" of the 1st one).
#media screen and (max-width:10000px) {
p.styled {
color: blue;
font-weight: bold;
font-size: 2em;
}
}
#media screen and (min-width:1px) {
p.styled {
color: red;
font-style: italic;
font-size: 0.5em;
}
}
<p class="styled">Text with styles from both media queries applied.</p>
<p>Text with no styles applied.</p>
It will be 2em until 1179px if you do:
#media screen and (min-width : 280px){
body{font-size: 2em;}
#media screen and (min-width : 1179px){
body{font-size: .5em;}}
It all depends how you declare the break points, sometimes odd things seem to happen, but it is just all in the break points declaration.
I have found this approach the easiest for mobile first.

Pixels in CSS vs pixel density

I am incredibly new to HTML and CSS and it just occurred to me that when deciding something is 5px say, since a pixel's physical size is dependent on the density then surely 5px on a screen of 100 ppi would look bigger than on a screen of 300 ppi.
Is this correct and if so is there any way to mediate this?
Absolutely! Typically on a desktop, 1 css pixel = 1 pixel. Mobile devices (especially with newer high-res displays) have caused us some headaches. Here's my favourite workaround:
(function() {
var meta = document.createElement("meta");
meta.setAttribute('name','viewport');
var content = 'initial-scale=';
content += 1 / window.devicePixelRatio;
content += ',user-scalable=no';
meta.setAttribute('content', content);
document.getElementsByTagName('head')[0].appendChild(meta);
})();
I typically add this as the first child of my body tag, but it should probably be in the head tag. This script modifies a device's scale such based on the pixel density of the display and forces 1 CSS pixel to equal 1 pixel.
Enjoy!
A CSS pixel is not a physical pixel!
96 CSS px ~= 1 physical inch.
refer to https://www.w3.org/TR/css3-values/
You can also use #media queries which allows you to use different css for different sized screens:
You can learn more CSS Tricks
#media all and (max-width: 699px) and (min-width: 520px), (min-width: 1151px) {
body {
background: #ccc;
}
}
Another screen size
#media all and (max-width: 1000px) and (min-width: 700px) {
#sidebar ul li a:before {
content: "Email: ";
font-style: italic;
color: #666;
}
}