How to avoid scaling of elements inside foreignObjects of svgs? - html

I want to use a svg as container for a div element which should contain several elements. At the moment it looks like this:
<body>
<svg width="100%" height="100%" viewBox="0 0 45 90" version="1.1" xmlns="http://www.w3.org/2000/svg" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:1.41421;">
<path d="M45.02,17.449l0,-5.837l-0.324,0c0,-3.841 0,-6.21 0,-6.344c0,-0.786 0.105,-3.078 -2.657,-3.659c-5.996,-1.263 -19.539,-1.352 -19.539,-1.352c0,0 -13.543,0.089 -19.539,1.352c-2.762,0.58 -2.657,2.873 -2.657,3.659c0,0.192 0,4.987 0,12.133l-0.324,0l0,14.537l0.324,0c0,22.9 0,52.313 0,52.794c0,0.786 -0.105,3.079 2.656,3.66c5.997,1.262 19.54,1.351 19.54,1.351c0,0 13.542,-0.089 19.539,-1.351c2.762,-0.581 2.657,-2.874 2.657,-3.66c0,-0.594 0,-45.159 0,-67.283l0.324,0Zm-22.52,-13.778c0.535,0 0.969,0.434 0.969,0.969c0,0.536 -0.434,0.97 -0.969,0.97c-0.535,0 -0.969,-0.435 -0.969,-0.97c0,-0.536 0.434,-0.969 0.969,-0.969Zm20.262,75.595l-40.525,0l0,-71.234l40.524,0l0,71.234l0.001,0Z" style="fill-rule:nonzero;"></path>
<foreignObject x="2.238" y="8.019" width="40" height="71">
<div id="screen">
I'm a very long text. Why am I so big?
</div>
</foreignObject>
</svg>
</body>
CSS
html, body{
width: 100%;
height: 100%;
}
#screen{
background: green;
overflow: scroll;
width: 100%;
height: 100%;
font-size: 10px;
}
JSFiddle
My problem is that all elements inside the screen-div are way larger than expected. e.g. see the scrollbar or the size of the text.
I assume the content of the foreignObject is scaled by the same factor as the svg. Is there a way to avoid this? Could I normalize the div inside the foreignObject to be not scaled or zoomed?
svg is "Smartphone" by Martin Jordan from the Noun Project

The only solution I can think of is to use JavaScript to dynamically size and counter-scale the foreignObject based on the viewBox dimensions versus the offsetWidth and offsetHeight of the outer <svg>.
For example, in this demo I happen to have hard-coded the size of the SVG to be four times as large as the viewBox dimensions. To counteract this, I made the foreignObject four times as large, but then scaled it down to one-quarter the size:
<foreignObject width="164" height="288" transform="translate(2,8) scale(0.25,0.25)">
https://jsfiddle.net/7ttps7a7/3/
A good generic solution would be to put an extra attribute in a custom namespace on any foreignObject, and then load a JavaScript library that finds such elements and dynamically adjusts them (and keeps them adjusted as the size of the SVG changes).
Note that comparing offsetWidth (and height) vs viewBox width (and height) needs to consider the value of the preserveAspectRatio attribute on the SVG to be precise.
Edit: I've created a small library that does this
Library: http://phrogz.net/SVG/fixed-size-foreignObject.js
Demo: http://phrogz.net/SVG/fixed-size-foreignObject.html
To use it:
Include the library in your HTML or SVG page.
Please download it and host it on your own site; I am not a CDN.
Be sure to use x and y attributes to place your <foreignObject>, and width and height values to size it.
Use one of the following:
fixedSizeForeignObject( someForeignObjectElement );
fixedSizeForeignObjects( arrayOfForeignObjectElements );
How it works:
When a foreignObject is added to the list of elements to keep resized, its original x, y, width, height values are recorded. The SVG element that owns the foreignObject is added to list of SVG elements to watch.
When the window resizes, code is triggered that (a) calculates the scale of each SVG (actual pixels versus viewBox size) and then (b) for each foreignObject registered it adjusts the width/height to be correct, and then scales the element down to fit in the original location.
I'll copy/paste the library here in the (unlikely) case that my site is down:
(function(win){
const svgs, els=[];
win.fixedSizeForeignObjects = function fixedSizeForeignObjects(els) {
els.forEach( fixedSizeForeignObject );
}
win.fixedSizeForeignObject = function fixedSizeForeignObject(el) {
if (!svgs) { svgs = []; win.addEventListener('resize',resizeSVGs,false) }
let svg=el.ownerSVGElement, found=false;
for (let i=svgs.length;i--;) if (svgs[i]===svg) found=true;
if (!found) svgs.push(svg);
let info = {
el:el, svg:svg,
w:el.getAttribute('width')*1, h:el.getAttribute('height')*1,
x:el.getAttribute('x')*1, y:el.getAttribute('y')*1
};
els.push(info);
el.removeAttribute('x');
el.removeAttribute('y');
calculateSVGScale(svg);
fixScale(info);
}
function resizeSVGs(evt) {
svgs.forEach(calculateSVGScale);
els.forEach(fixScale);
}
function calculateSVGScale(svg) {
let w1=svg.viewBox.animVal.width, h1=svg.viewBox.animVal.height;
if (!w1 && !h1) svg.scaleRatios = [1,1]; // No viewBox
else {
let info = win.getComputedStyle(svg);
let w2=parseFloat(info.width), h2=parseFloat(info.height);
let par=svg.preserveAspectRatio.animVal;
if (par.align===SVGPreserveAspectRatio.SVG_PRESERVEASPECTRATIO_NONE) {
svg.scaleRatios = [w2/w1, h2/h1];
} else {
let meet = par.meetOrSlice === SVGPreserveAspectRatio.SVG_MEETORSLICE_MEET;
let ratio = (w1/h1 > w2/h2) != meet ? h2/h1 : w2/w1;
svg.scaleRatios = [ratio, ratio];
}
}
}
function fixScale(info) {
let s = info.svg.scaleRatios;
info.el.setAttribute('width', info.w*s[0]);
info.el.setAttribute('height',info.h*s[1]);
info.el.setAttribute('transform','translate('+info.x+','+info.y+') scale('+1/s[0]+','+1/s[1]+')');
}
})(window);

Related

Dynamic css font-size on a html div [duplicate]

I'm having a hard time getting my head around font scaling.
I currently have a website with a body font-size of 100%. 100% of what though? This seems to compute out at 16 pixels.
I was under the impression that 100% would somehow refer to the size of the browser window, but apparently not because it's always 16 pixels whether the window is resized down to a mobile width or full-blown widescreen desktop.
How can I make the text on my site scale in relation to its container? I tried using em, but this doesn't scale either.
My reasoning is that things like my menu become squished when you resize, so I need to reduce the px font-size of .menuItem among other elements in relation to the width of the container. (For example, in the menu on a large desktop, 22px works perfectly. Move down to tablet width and 16px is more appropriate.)
I'm aware I can add breakpoints, but I really want the text to scale as well as having extra breakpoints, otherwise, I'll end up with hundreds of breakpoints for every 100pixels decrease in width to control the text.
If the container is not the body, CSS Tricks covers all of your options in Fitting Text to a Container.
If the container is the body, what you are looking for is Viewport-percentage lengths:
The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly. However, when the value of overflow on the root element is auto, any scroll bars are assumed not to exist.
The values are:
vw (% of the viewport width)
vh (% of the viewport height)
vi (1% of the viewport size in the direction of the root element's inline axis)
vb (1% of the viewport size in the direction of the root element's block axis)
vmin (the smaller of vw or vh)
vmax (the larger or vw or vh)
1 v* is equal to 1% of the initial containing block.
Using it looks like this:
p {
font-size: 4vw;
}
As you can see, when the viewport width increases, so do the font-size, without needing to use media queries.
These values are a sizing unit, just like px or em, so they can be used to size other elements as well, such as width, margin, or padding.
Browser support is pretty good, but you'll likely need a fallback, such as:
p {
font-size: 16px;
font-size: 4vw;
}
Check out the support statistics: http://caniuse.com/#feat=viewport-units.
Also, check out CSS-Tricks for a broader look: Viewport Sized Typography
Here's a nice article about setting minimum/maximum sizes and exercising a bit more control over the sizes: Precise control over responsive typography
And here's an article about setting your size using calc() so that the text fills the viewport: http://codepen.io/CrocoDillon/pen/fBJxu
Also, please view this article, which uses a technique dubbed 'molten leading' to adjust the line-height as well. Molten Leading in CSS
But what if the container is not the viewport (body)?
This question is asked in a comment by Alex under 2507rkt3's answer.
That fact does not mean vw cannot be used to some extent to size for that container. Now to see any variation at all one has to be assuming that the container in some way is flexible in size. Whether through a direct percentage width or through being 100% minus margins. The point becomes "moot" if the container is always set to, let's say, 200px wide--then just set a font-size that works for that width.
Example 1
With a flexible width container, however, it must be realized that in some way the container is still being sized off the viewport. As such, it is a matter of adjusting a vw setting based off that percentage size difference to the viewport, which means taking into account the sizing of parent wrappers. Take this example:
div {
width: 50%;
border: 1px solid black;
margin: 20px;
font-size: 16px;
/* 100 = viewport width, as 1vw = 1/100th of that
So if the container is 50% of viewport (as here)
then factor that into how you want it to size.
Let's say you like 5vw if it were the whole width,
then for this container, size it at 2.5vw (5 * .5 [i.e. 50%])
*/
font-size: 2.5vw;
}
Assuming here the div is a child of the body, it is 50% of that 100% width, which is the viewport size in this basic case. Basically, you want to set a vw that is going to look good to you. As you can see in my comment in the above CSS content, you can "think" through that mathematically with respect to the full viewport size, but you don't need to do that. The text is going to "flex" with the container because the container is flexing with the viewport resizing. Here's an example of two differently sized containers.
Example 2
You can help ensure viewport sizing by forcing the calculation based off that. Consider this example:
html {width: 100%;} /* Force 'html' to be viewport width */
body {width: 150%; } /* Overflow the body */
div {
width: 50%;
border: 1px solid black;
margin: 20px;
font-size: 16px;
/* 100 = viewport width, as 1vw = 1/100th of that
Here, the body is 150% of viewport, but the container is 50%
of viewport, so both parents factor into how you want it to size.
Let's say you like 5vw if it were the whole width,
then for this container, size it at 3.75vw
(5 * 1.5 [i.e. 150%]) * .5 [i.e. 50%]
*/
font-size: 3.75vw;
}
The sizing is still based off viewport, but is in essence set up based off the container size itself.
Should the Size of the Container Change Dynamically...
If the sizing of the container element ended up changing dynamically its percentage relationship either via #media breakpoints or via JavaScript, then whatever the base "target" was would need recalculation to maintain the same "relationship" for text sizing.
Take example #1 above. If the div was switched to 25% width by either #media or JavaScript, then at the same time, the font-size would need to adjust in either the media query or by JavaScript to the new calculation of 5vw * .25 = 1.25. This would put the text size at the same size it would have been had the "width" of the original 50% container been reduced by half from viewport sizing, but has now been reduced due to a change in its own percentage calculation.
A Challenge
With the CSS calc() function in use, it would become difficult to adjust dynamically, as that function does not work for font-size purposes at this time. So you could not do a pure CSS adjustment if your width is changing on calc(). Of course, a minor adjustment of width for margins may not be enough to warrant any change in font-size, so it may not matter.
Solution with SVG:
.resizeme {
resize: both;
margin: 0;
padding: 0;
height: 75px;
width: 500px;
background-color: lightblue;
overflow: hidden;
}
<div class="resizeme">
<svg
width="100%"
height="100%"
viewBox="0 0 500 75"
preserveAspectRatio="xMinYMid meet"
style="background-color:green"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
>
<text
x="0"
y="75"
font-size="75"
fill="black"
>█Resize This█</text>
</svg>
</div>
Solution with SVG and text-wrapping using foreignObject:
.resizeme {
resize: both;
margin: 0;
padding: 0;
height: 200px;
width: 500px;
background-color: lightblue;
overflow: hidden;
}
<div class="resizeme">
<svg
width="100%"
height="100%"
viewBox="0 0 500 200"
preserveAspectRatio="xMinYMin meet"
>
<foreignObject width="100%" height="100%" xmlns="http://www.w3.org/1999/xhtml">
<div xmlns="http://www.w3.org/1999/xhtml" style="background-color:lightgreen;">
<h1>heading</h1>
<p>Resize the blue box.</p>
</div>
</foreignObject>
</svg>
</div>
In one of my projects I use a "mixture" between vw and vh to adjust the font size to my needs, for example:
font-size: calc(3vw + 3vh);
I know this doesn't answer the OP's question, but maybe it can be a solution to anyone else.
Pure-CSS solution with calc(), CSS units and math
This is precisely not what OP asks, but may make someone's day. This answer is not spoon-feedingly easy and needs some researching on the developer end.
I came finally to get a pure-CSS solution for this using calc() with different units. You will need some basic mathematical understanding of formulas to work out your expression for calc().
When I worked this out, I had to get a full-page-width responsive header with some padding few parents up in DOM. I'll use my values here, replace them with your own.
To mathematics
You will need:
Nicely adjusted ratio in some viewport. I used 320 pixels, thus I got 24 pixels high and 224 pixels wide, so the ratio is 9.333... or 28 / 3
The container width, I had padding: 3em and full width so this got to 100wv - 2 * 3em
X is the width of container, so replace it with your own expression or adjust the value to get full-page text. R is the ratio you will have. You can get it by adjusting the values in some viewport, inspecting element width and height and replacing them with your own values. Also, it is width / heigth ;)
x = 100vw - 2 * 3em = 100vw - 6em
r = 224px/24px = 9.333... = 28 / 3
y = x / r
= (100vw - 6em) / (28 / 3)
= (100vw - 6em) * 3 / 28
= (300vw - 18em) / 28
= (75vw - 4.5rem) / 7
And bang! It worked! I wrote
font-size: calc((75vw - 4.5rem) / 7)
to my header and it adjusted nicely in every viewport.
But how does it work?
We need some constants up here. 100vw means the full width of viewport, and my goal was to establish full-width header with some padding.
The ratio. Getting a width and height in one viewport got me a ratio to play with, and with ratio I know what the height should be in other viewport width. Calculating them with hand would take plenty of time and at least take lots of bandwidth, so it's not a good answer.
Conclusion
I wonder why no-one has figured this out and some people are even telling that this would be impossible to tinker with CSS. I don't like to use JavaScript in adjusting elements, so I don't accept JavaScript (and forget about jQuery) answers without digging more. All in all, it's good that this got figured out and this is one step to pure-CSS implementations in website design.
I apologize of any unusual convention in my text, I'm not native speaker in English and am also quite new to writing Stack Overflow answers.
It should also be noted that we have evil scrollbars in some browsers. For example, when using Firefox I noticed that 100vw means the full width of viewport, extending under scrollbar (where content cannot expand!), so the fullwidth text has to be margined carefully and preferably get tested with many browsers and devices.
There is a big philosophy for this issue.
The easiest thing to do would be to give a certain font-size to body (I recommend 10), and then all the other element would have their font in em or rem.
I'll give you an example to understand those units.
Em is always relative to its parent:
body{font-size: 10px;}
.menu{font-size: 2em;} /* That means 2*10 pixels = 20 pixels */
.menu li{font-size: 1.5em;} /* That means 1.5*20 pixels = 30 pixels */
Rem is always relative to body:
body{font-size: 10px;}
.menu{font-size: 2rem;} /* That means 2*10 pixels = 20 pixels */
.menu li{font-size: 1.5rem;} /* that means 1.5*10 pixels = 15 pixels */
And then you could create a script that would modify font-size relative to your container width.
But this isn't what I would recommend. Because in a 900 pixels width container for example you would have a p element with a 12 pixels font-size let's say. And on your idea that would become an 300 pixels wide container at 4 pixels font-size. There has to be a lower limit.
Other solutions would be with media queries, so that you could set font for different widths.
But the solutions that I would recommend is to use a JavaScript library that helps you with that. And fittext.js that I found so far.
Here is the function:
document.body.setScaledFont = function(f) {
var s = this.offsetWidth, fs = s * f;
this.style.fontSize = fs + '%';
return this
};
Then convert all your documents child element font sizes to em's or %.
Then add something like this to your code to set the base font size.
document.body.setScaledFont(0.35);
window.onresize = function() {
document.body.setScaledFont(0.35);
}
http://jsfiddle.net/0tpvccjt/
There is a way to do this without JavaScript!
You can use an inline SVG image. You can use CSS on an SVG if it is inline. You have to remember that using this method means your SVG image will respond to its container size.
Try using the following solution...
HTML
<div>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 360.96 358.98" >
<text>SAVE $500</text>
</svg>
</div>
CSS
div {
width: 50%; /* Set your container width */
height: 50%; /* Set your container height */
}
svg {
width: 100%;
height: auto;
}
text {
transform: translate(40px, 202px);
font-size: 62px;
fill: #000;
}
Example:
https://jsfiddle.net/k8L4xLLa/32/
Want something more flashy?
SVG images also allow you to do cool stuff with shapes and junk. Check out this great use case for scalable text...
https://jsfiddle.net/k8L4xLLa/14/
CSS Container Queries
A late-2022 addition to the CSS feature set makes scaling font size with containers straightforward.
Container queries come with a new set of CSS units cqw/cqh (container query width/height). To use them you need to set the container-type property on the parent element whose size you want to use. Minimal example:
<div>
<p>Lorem ipsum dolor sit amet</p>
</div>
<style>
div {
container-type: inline-size;
}
p {
font-size: 5cqw;
}
</style>
The font size will increase smoothly as the container grows. At 1000px container width, the p font size will be 1000px / 100 * 5 = 50px.
container-type can be size or inline-size. size tracks both height and width of the container which allows you to use both cqw and cqh.
Most of the time on the web, heights are calculated based on content and you only specify the width. To save the browser some work, you'll generally want to set container-type: inline-size; so the browser only tracks the inline dimension which is usually width (unless you set writing-mode to vertical).
Browser support for container queries has grown rapidly in the 2nd half of 2022 and currently stands at 75% (2023-01-01).
This may not be super practical, but if you want a font to be a direct function of the parent, without having any JavaScript that listens/loops (interval) to read the size of the div/page, there is a way to do it. Iframes.
Anything within the iframe will consider the size of the iframe as the size of the viewport. So the trick is to just make an iframe whose width is the maximum width you want your text to be, and whose height is equal to the maximum height * the particular text's aspect ratio.
Setting aside the limitation that viewport units can't also come along side parent units for text (as in, having the % size behave like everyone else), viewport units do provide a very powerful tool: being able to get the minimum/maximum dimension. You can't do that anywhere else - you can't say...make the height of this div be the width of the parent * something.
That being said, the trick is to use vmin, and to set the iframe size so that [fraction] * total height is a good font size when the height is the limiting dimension, and [fraction] * total width when the width is the limiting dimension. This is why the height has to be a product of the width and the aspect ratio.
For my particular example, you have
.main iframe{
position: absolute;
top: 50%;
left: 50%;
width: 100%;
height: calc(3.5 * 100%);
background: rgba(0, 0, 0, 0);
border-style: none;
transform: translate3d(-50%, -50%, 0);
}
The small annoyance with this method is that you have to manually set the CSS of the iframe. If you attach the whole CSS file, that would take up a lot of bandwidth for many text areas. So, what I do is attach the rule that I want directly from my CSS.
var rule = document.styleSheets[1].rules[4];
var iDoc = document.querySelector('iframe').contentDocument;
iDoc.styleSheets[0].insertRule(rule.cssText);
You can write small function that gets the CSS rule / all CSS rules that would affect the text area.
I cannot think of another way to do it without having some cycling/listening JavaScript. The real solution would be for browsers to provide a way to scale text as a function of the parent container and to also provide the same vmin/vmax type functionality.
JSFiddle:
https://jsfiddle.net/0jr7rrgm/3/
(click once to lock the red square to the mouse, and click again to release)
Most of the JavaScript in the fiddle is just my custom click-drag function.
Using vw, em & co. works for sure, but IMO it always needs a human's touch for fine-tuning.
Here's a script I just wrote based on #tnt-rox' answer that tries to automatize that human's touch:
$('#controller').click(function(){
$('h2').each(function(){
var
$el = $(this),
max = $el.get(0),
el = null
;
max =
max
? max.offsetWidth
: 320
;
$el.css({
'font-size': '1em',
'display': 'inline',
});
el = $el.get(0);
el.get_float = function(){
var
fs = 0
;
if (this.style && this.style.fontSize) {
fs = parseFloat(this.style.fontSize.replace(/([\d\.]+)em/g, '$1'));
}
return fs;
};
el.bigger = function(){
this.style.fontSize = (this.get_float() + 0.1) + 'em';
};
while (el.offsetWidth < max) {
el.bigger();
}
// Finishing touch.
$el.css({
'font-size': ((el.get_float() -0.1) +'em'),
'line-height': 'normal',
'display': '',
});
}); // end of (each)
}); // end of (font scaling test)
div {
width: 50%;
background-color: tomato;
font-family: 'Arial';
}
h2 {
white-space: nowrap;
}
h2:nth-child(2) {
font-style: italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="button" id="controller" value="Apply" />
<div>
<h2>Lorem ipsum dolor</h2>
<h2>Test String</h2>
<h2>Sweet Concatenation</h2>
<h2>Font Scaling</h2>
</div>
It basically reduces the font-size to 1em and then starts incrementing by 0.1 until it reaches maximum width.
JSFiddle
Use CSS Variables
No one has mentioned CSS variables yet, and this approach worked best for me, so:
Let's say you've got a column on your page that is 100% of the width of a mobile user's screen, but has a max-width of 800px, so on desktop there's some space on either side of the column. Put this at the top of your page:
<script> document.documentElement.style.setProperty('--column-width', Math.min(window.innerWidth, 800)+'px'); </script>
And now you can use that variable (instead of the built-in vw unit) to set the size of your font. E.g.
p {
font-size: calc( var(--column-width) / 100 );
}
It's not a pure CSS approach, but it's pretty close.
100% is relative to the base font size, which, if you haven't set it, would be the browser's user-agent default.
To get the effect you're after, I would use a piece of JavaScript code to adjust the base font size relative to the window dimensions.
Artistically, if you need to fit two or more lines of text within the same width regardless of their character count then you have nice options.
It's best to find a dynamical solution so whatever text is entered we end up with a nice display.
Let's see how we may approach.
var els = document.querySelectorAll(".divtext"),
refWidth = els[0].clientWidth,
refFontSize = parseFloat(window.getComputedStyle(els[0],null)
.getPropertyValue("font-size"));
els.forEach((el,i) => el.style.fontSize = refFontSize * refWidth / els[i].clientWidth + "px")
#container {
display: inline-block;
background-color: black;
padding: 0.6vw 1.2vw;
}
.divtext {
display: table;
color: white;
font-family: impact;
font-size: 4.5vw;
}
<div id="container">
<div class="divtext">THIS IS JUST AN</div>
<div class="divtext">EXAMPLE</div>
<div class="divtext">TO SHOW YOU WHAT</div>
<div class="divtext">YOU WANT</div>
</div>
All we do is to get the width (els[0].clientWidth) and the font size (parseFloat(window.getComputedStyle(els[0],null).getPropertyValue("font-size"))) of the first line as a reference and then just calculate the subsequent lines font size accordingly.
This web component changes the font size so the inner text width matches the container width. Check the demo.
You can use it like this:
<full-width-text>Lorem Ipsum</full-width-text>
You may be you looking for something like this:
http://jsfiddle.net/sijav/dGsC9/4/
http://fiddle.jshell.net/sijav/dGsC9/4/show/
I have used flowtype, and it's working great (however it's JavaScript and not a pure CSS solution):
$('body').flowtype({
minFont: 10,
maxFont: 40,
minimum: 500,
maximum: 1200,
fontRatio: 70
});
I've prepared a simple scale function using CSS transform instead of font-size. You can use it inside of any container, you don't have to set media queries, etc. :)
Blog post:
Full width CSS & JS scalable header
The code:
function scaleHeader() {
var scalable = document.querySelectorAll('.scale--js');
var margin = 10;
for (var i = 0; i < scalable.length; i++) {
var scalableContainer = scalable[i].parentNode;
scalable[i].style.transform = 'scale(1)';
var scalableContainerWidth = scalableContainer.offsetWidth - margin;
var scalableWidth = scalable[i].offsetWidth;
scalable[i].style.transform = 'scale(' + scalableContainerWidth / scalableWidth + ')';
scalableContainer.style.height = scalable[i].getBoundingClientRect().height + 'px';
}
}
Working demo:
https://codepen.io/maciejkorsan/pen/BWLryj
Inside your CSS, try adding this at the bottom changing the 320 pixels width for wherever your design starts breaking:
#media only screen and (max-width: 320px) {
body { font-size: 1em; }
}
Then give the font-size in "px" or "em" as you wish.
Try http://simplefocus.com/flowtype/. This is what I use for my sites, and it has worked perfectly.
My own solution, jQuery-based, works by gradually increasing the font size until the container gets a big increase in height (meaning it got a line break).
It's pretty simple, but works fairly well, and it is very easy to use. You don't have to know anything about the font being used, everything is taken care of by the browser.
You can play with it on http://jsfiddle.net/tubededentifrice/u5y15d0L/2/
The magic happens here:
var setMaxTextSize=function(jElement) {
// Get and set the font size into data for reuse upon resize
var fontSize=parseInt(jElement.data(quickFitFontSizeData)) || parseInt(jElement.css("font-size"));
jElement.data(quickFitFontSizeData, fontSize);
// Gradually increase font size until the element gets a big increase in height (i.e. line break)
var i = 0;
var previousHeight;
do
{
previousHeight=jElement.height();
jElement.css("font-size", "" + (++fontSize) + "px");
}
while(i++ < 300 && jElement.height()-previousHeight < fontSize/2)
// Finally, go back before the increase in height and set the element as resized by adding quickFitSetClass
fontSize -= 1;
jElement.addClass(quickFitSetClass).css("font-size", "" + fontSize + "px");
return fontSize;
};
My problem was similar, but related to scaling text within a heading. I tried Fit Font, but I needed to toggle the compressor to get any results, since it was solving a slightly different problem, as was Text Flow.
So I wrote my own little plugin that reduced the font size to fit the container, assuming you have overflow: hidden and white-space: nowrap so that even if reducing the font to the minimum doesn't allow showing the full heading, it just cuts off what it can show.
(function($) {
// Reduces the size of text in the element to fit the parent.
$.fn.reduceTextSize = function(options) {
options = $.extend({
minFontSize: 10
}, options);
function checkWidth(em) {
var $em = $(em);
var oldPosition = $em.css('position');
$em.css('position', 'absolute');
var width = $em.width();
$em.css('position', oldPosition);
return width;
}
return this.each(function(){
var $this = $(this);
var $parent = $this.parent();
var prevFontSize;
while (checkWidth($this) > $parent.width()) {
var currentFontSize = parseInt($this.css('font-size').replace('px', ''));
// Stop looping if min font size reached, or font size did not change last iteration.
if (isNaN(currentFontSize) || currentFontSize <= options.minFontSize ||
prevFontSize && prevFontSize == currentFontSize) {
break;
}
prevFontSize = currentFontSize;
$this.css('font-size', (currentFontSize - 1) + 'px');
}
});
};
})(jQuery);
Try to use the fitText plugin, because Viewport sizes isn't the solution of this problem.
Just add the library:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
And change font-size for correct by settings the coefficient of text:
$("#text_div").fitText(0.8);
You can set maximum and minimum values of text:
$("#text_div").fitText(0.8, { minFontSize: '12px', maxFontSize: '36px' });
Here is a pure CSS solution with the understanding that you admit breakpoints are necessary but also want text scaling:
I'm aware I can add breakpoints, but I really want the text to scale
as well as having extra breakpoints, otherwise....
Here is an approach using:
Custom properties
Media queries for breakpoints
clamp() (browser support in Feb 2022 is pretty good at 93%)
calc()
If one common scaling factor can be used to control ALL the text scaling within a container per screen max-width, all you need to do is scale a custom property per max-width, and apply this factor to 1 calculation.
A basic setup starts like this:
:root {
--scaling-factor: 1
}
.parent {
font-size: 30px
}
.largest {
font-size: clamp(60%, calc(var(--scaling-factor) * 100%), 100%);
}
.middle {
font-size: clamp(60%, calc(var(--scaling-factor) * 85%), 100%);
}
.smallest {
font-size: clamp(60%, calc(var(--scaling-factor) * 70%), 100%);
}
Then nest your media queries something like this (or whatever you need for your breakpoints):
#media (max-width: 1200px) {
:root {
--scaling-factor: 0.9
}
#media (max-width: 800px) {
:root {
--scaling-factor: 0.8
}
#media (max-width: 600px) {
:root {
--scaling-factor: 0.5 /* nope, because the font-size is floored at 60% thanks to clamp() */
}
}
}
}
This minimizes your media query markup.
Advantages
One custom property controls ALL scaling ... no need to add multiple declarations per media breakpoint
The use of clamp() sets a lower-limit on what the font-size should be, so you ensure your text is never too small (here the floor is 60% of the parent's font-size)
Please see this JSFiddle for a demo. Resize the window until at the smallest widths, the paragraphs are all the same font-size.
Always have your element with this attribute:
JavaScript: element.style.fontSize = "100%";
or
CSS: style = "font-size: 100%;"
When you go fullscreen, you should already have a scale variable calculated (scale > 1 or scale = 1). Then, on fullscreen:
document.body.style.fontSize = (scale * 100) + "%";
It works nicely with little code.
Take look at my code. It makes the font size smaller to fit whatever there.
But I think this doesn't lead to a good user experience
var containerWidth = $("#ui-id-2").width();
var items = $(".quickSearchAutocomplete .ui-menu-item");
var fontSize = 16;
items.each(function(){
// Displaying a value depends sometimes on your case. You may make it block or inline-table instead of inline-block or whatever value that make the div take overflow width.
$(this).css({"whiteSpace": "nowrap", "display": "inline-block"});
while ($(this).width() > containerWidth){
console.log("$(this).width()" + $(this).width() + "containerWidth" + containerWidth)
$(this).css("font-size", fontSize -= 0.5);
}
});
For dynamic text, this plugin is quite useful:
http://freqdec.github.io/slabText/
Simply add CSS:
.slabtexted .slabtext
{
display: -moz-inline-box;
display: inline-block;
white-space: nowrap;
}
.slabtextinactive .slabtext
{
display: inline;
white-space: normal;
font-size: 1em !important;
letter-spacing: inherit !important;
word-spacing: inherit !important;
*letter-spacing: normal !important;
*word-spacing: normal !important;
}
.slabtextdone .slabtext
{
display: block;
}
And the script:
$('#mydiv').slabText();
This worked for me:
I try to approximate font-size based on a width/height got from setting `font-size: 10px`. Basically, the idea is "if I have 20 pixels width and 11 pixels height with `font-size: 10px`, so what would it be the maximum font-size to math a container of 50 pixels width and 30 pixels height?"
The answer is a double proportion system:
{ 20:10=50:X, 11:10=30:Y } = { X= (10*50)/20, Y= (10*30)/11 }
Now X is a font-size that will match width, and Y is a font-size that will match height; take the smallest value
function getMaxFontSizeApprox(el){
var fontSize = 10;
var p = el.parentNode;
var parent_h = p.offsetHeight ? p.offsetHeight : p.style.pixelHeight;
if(!parent_h)
parent_h = 0;
var parent_w = p.offsetHeight ? p.offsetWidth : p.style.pixelWidth;
if(!parent_w)
parent_w = 0;
el.style.fontSize = fontSize + "px";
var el_h = el.offsetHeight ? el.offsetHeight : el.style.pixelHeight;
if(!el_h)
el_h = 0;
var el_w = el.offsetHeight ? el.offsetWidth : el.style.pixelWidth;
if(!el_w)
el_w = 0;
// 0.5 is the error on the measure that JavaScript does
// if the real measure had been 12.49 px => JavaScript would have said 12px
// so we think about the worst case when could have, we add 0.5 to
// compensate the round error
var fs1 = (fontSize*(parent_w + 0.5))/(el_w + 0.5);
var fs2 = (fontSize*(parent_h) + 0.5)/(el_h + 0.5);
fontSize = Math.floor(Math.min(fs1,fs2));
el.style.fontSize = fontSize + "px";
return fontSize;
}
NB: the argument of the function must be a span element or an element which is smaller than its parent, otherwise if children and parent have both the same width/height function will fail.
let textElement = document.getElementById('text1');
let parentElement = textElement.parentElement;
const parentClientHeight = parentElement.clientHeight;
const parentClientWidth = parentElement.clientWidth;
textElement.style.padding = "unset";
textElement.style.margin = "auto";
let fontSize = parentClientHeight;
let minFS = 3,
maxFS = fontSize;
while (fontSize != minFS) {
textElement.style.fontSize = `${fontSize}px`;
if (
parentElement.scrollHeight <= parentClientHeight &&
parentElement.scrollWidth <= parentClientWidth
) {
minFS = fontSize;
} else {
maxFS = fontSize;
}
fontSize = Math.floor((minFS + maxFS) / 2);
}
textElement.style.fontSize = `${minFS}px`;
<div style="height:200px; width:300px;">
<div id='text1'>
test
</div>
</div>
As a JavaScript fallback (or your sole solution), you can use my jQuery Scalem plugin, which lets you scale relative to the parent element (container) by passing the reference option.
In case it's helpful to anyone, most of the solutions in this thread were wrapping text into multiple lines, form e.
But then I found this, and it worked:
https://github.com/chunksnbits/jquery-quickfit
Example usage:
$('.someText').quickfit({max:50,tolerance:.4})

SVG image not reacting to CSS colour changes [duplicate]

html
<img src="logo.svg" alt="Logo" class="logo-img">
css
.logo-img path {
fill: #000;
}
The above svg loads and is natively fill: #fff but when I use the above css to try change it to black it doesn't change, this is my first time playing with SVG and I am not sure why it's not working.
You could set your SVG as a mask. That way setting a background-color would act as your fill color.
HTML
<div class="logo"></div>
CSS
.logo {
background-color: red;
-webkit-mask: url(logo.svg) no-repeat center;
mask: url(logo.svg) no-repeat center;
}
JSFiddle: https://jsfiddle.net/KuhlTime/2j8exgcb/
MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/mask
Please check whether your browser supports this feature:
https://caniuse.com/#search=mask
If your goal is just to change the color of the logo, and you don't necessarily NEED to use CSS, then don't use javascript or jquery as was suggested by some previous answers.
To precisely answer the original question, just:
Open your logo.svg in a text editor.
look for fill: #fff and replace it with fill: #000
For example, your logo.svg might look like this when opened in a text editor:
<svg fill="#000000" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
<path d="M0 0h24v24H0z" fill="none"/>
<path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z" fill="#fff"/>
</svg>
... just change the fill and save.
Try pure CSS:
.logo-img {
/* to black */
filter: invert(1);
/* or to blue */
filter: invert(0.5) sepia(1) saturate(5) hue-rotate(175deg);
}
more info in this article https://blog.union.io/code/2017/08/10/img-svg-fill/
If you want a dynamic color, do not want to use javascript and do not want an inline SVG, use a CSS variable. Works in Chrome, Firefox and Safari. edit: and Edge
<svg>
<use href="logo.svg" style="--color_fill: #000;"></use>
</svg>
In your SVG, replace any instances of style="fill: #000" with style="fill: var(--color_fill)".
You will first have to inject the SVG into the HTML DOM.
There is an open source library called SVGInject that does this for you. It uses the onload attribute to trigger the injection.
Here is a minimal example using SVGInject:
<html>
<head>
<script src="svg-inject.min.js"></script>
</head>
<body>
<img src="image.svg" onload="SVGInject(this)" />
</body>
</html>
After the image is loaded the onload="SVGInject(this) will trigger the injection and the <img> element will be replaced by the contents of the SVG file provided in the src attribute.
It solves several issues with SVG injection:
SVGs can be hidden until injection has finished. This is important if a style is already applied during load time, which would otherwise cause a brief "unstyled content flash".
The <img> elements inject themselves automatically. If you add SVGs dynamically, you don't have to worry about calling the injection function again.
A random string is added to each ID in the SVG to avoid having the same ID multiple times in the document if an SVG is injected more than once.
SVGInject is plain Javascript and works with all browsers that support SVG.
Disclaimer: I am the co-author of SVGInject
Edit your SVG file, add fill="currentColor" to svg tag and make sure to remove any other fill property from the file.
For example:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 139.435269383854" id="img" fill="currentColor">...
</svg>
Note that currentColor is a keyword (not a fixed color in use).
After that, you can change the color using CSS, by setting the color property of the element or from it's parent.
Example:
.div-with-svg-inside {
color: red;
}
I forgot to say, you must insert the SVG this way:
<svg>
<use xlink:href='/assets/file.svg#img' href="/assets/file.svg#img"></use>
</svg>
if image is coming from some variable then
<svg>
<use [attr.xlink:href]="somevariable + '#img'" [attr.href]="somevariable + '#img'"></use>
</svg>
Note that `#img` is the id of the `svg` tag inside svg file. Also note `xlink:href` has been deprecated instead you should use `href` or use can use both to support older browser versions.
Another way of doing it: [https://css-tricks.com/cascading-svg-fill-color/][1]
[1]: https://css-tricks.com/cascading-svg-fill-color/
I suggest to select your color , and go to this pen
https://codepen.io/sosuke/pen/Pjoqqp
it will convert HEX to css filter eg:#64D7D6
equal
filter: invert(88%) sepia(21%) saturate(935%) hue-rotate(123deg) brightness(85%) contrast(97%);
the final snippet
.filterit{
width:270px;
filter: invert(88%) sepia(21%) saturate(935%) hue-rotate(123deg) brightness(85%) contrast(97%);
}
<img src="https://www.flaticon.com/svg/static/icons/svg/1389/1389029.svg"
class="filterit
/>
This answer is based on answer https://stackoverflow.com/a/24933495/3890888 but with a plain JavaScript version of the script used there.
You need to make the SVG to be an inline SVG. You can make use of this script, by adding a class svg to the image:
/*
* Replace all SVG images with inline SVG
*/
document.querySelectorAll('img.svg').forEach(function(img){
var imgID = img.id;
var imgClass = img.className;
var imgURL = img.src;
fetch(imgURL).then(function(response) {
return response.text();
}).then(function(text){
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(text, "text/xml");
// Get the SVG tag, ignore the rest
var svg = xmlDoc.getElementsByTagName('svg')[0];
// Add replaced image's ID to the new SVG
if(typeof imgID !== 'undefined') {
svg.setAttribute('id', imgID);
}
// Add replaced image's classes to the new SVG
if(typeof imgClass !== 'undefined') {
svg.setAttribute('class', imgClass+' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
svg.removeAttribute('xmlns:a');
// Check if the viewport is set, if the viewport is not set the SVG wont't scale.
if(!svg.getAttribute('viewBox') && svg.getAttribute('height') && svg.getAttribute('width')) {
svg.setAttribute('viewBox', '0 0 ' + svg.getAttribute('height') + ' ' + svg.getAttribute('width'))
}
// Replace image with new SVG
img.parentNode.replaceChild(svg, img);
});
});
And then, now if you do:
.logo-img path {
fill: #000;
}
Or may be:
.logo-img path {
background-color: #000;
}
JSFiddle: http://jsfiddle.net/erxu0dzz/1/
Use filters to transform to any color.
I recently found this solution, and hope somebody might be able to use it.
Since the solution uses filters, it can be used with any type of image. Not just svg.
If you have a single-color image that you just want to change the color of, you can do this with the help of some filters. It works on multicolor images as well of course, but you can't target a specific color. Only the whole image.
The filters came from the script proposed in How to transform black into any given color using only CSS filters
If you want to change white to any color, you can adjust the invert value in each filter.
.startAsBlack{
display: inline-block;
width: 50px;
height: 50px;
background: black;
}
.black-green{
filter: invert(43%) sepia(96%) saturate(1237%) hue-rotate(88deg) brightness(128%) contrast(119%);
}
.black-red{
filter: invert(37%) sepia(93%) saturate(7471%) hue-rotate(356deg) brightness(91%) contrast(135%);
}
.black-blue{
filter: invert(12%) sepia(83%) saturate(5841%) hue-rotate(244deg) brightness(87%) contrast(153%);
}
.black-purple{
filter: invert(18%) sepia(98%) saturate(2657%) hue-rotate(289deg) brightness(121%) contrast(140%);
}
Black to any color: <br/>
<div class="startAsBlack black-green"></div>
<div class="startAsBlack black-red"></div>
<div class="startAsBlack black-blue"></div>
<div class="startAsBlack black-purple"></div>
Why not create a webfont with your svg image or images, import the webfont in the css and then just change the color of the glyph using the css color attribute?
No javascript needed
Simple..
You can use this code:
<svg class="logo">
<use xlink:href="../../static/icons/logo.svg#Capa_1"></use>
</svg>
First specify the path of svg and then write it's ID, In this case "Capa_1". You can get the ID of svg by opening it in any editor.
In css:
.logo {
fill: red;
}
The answer from #Praveen is solid.
I couldn't get it to respond in my work, so I made a jquery hover function for it.
CSS
.svg path {
transition:0.3s all !important;
}
JS / JQuery
// code from above wrapped into a function
replaceSVG();
// hover function
// hover over an element, and find the SVG that you want to change
$('.element').hover(function() {
var el = $(this);
var svg = el.find('svg path');
svg.attr('fill', '#CCC');
}, function() {
var el = $(this);
var svg = el.find('svg path');
svg.attr('fill', '#3A3A3A');
});
If you are just switching the image between the real color and the black-and-white, you can set one selector as:
{filter:none;}
and another as:
{filter:grayscale(100%);}
To expand on #gringo answer, the Javascript method described in other answers works, but requires the user to download unnecessary image files, and IMO, it bloats your code.
I think a better approach would be to to migrate all 1-color vector graphics to a webfont file. I've used Fort Awesome in the past, and it works great to combine your custom icons/images in SVG format, along with any 3rd party icons you may be using (Font Awesome, Bootstrap icons, etc.) into a single webfont file the user has to download. You can also customize it, so you only include the 3rd party icons you're using. This reduces the number of requests the page has to make, and you're overall page weight, especially if you're already including any 3rd party icons libraries.
If you prefer a more dev oriented option, you could Google "npm svg webfont", and use one of the node modules that's most appropriate for your environment.
Once, you've done either of those two options, then you could easily change the color via CSS, and most likely, you've sped up your site in the process.
Since SVG is basically code, you need just contents. I used PHP to obtain content, but you can use whatever you want.
<?php
$content = file_get_contents($pathToSVG);
?>
Then, I've printed content "as is" inside a div container
<div class="fill-class"><?php echo $content;?></div>
To finnaly set rule to container's SVG childs on CSS
.fill-class > svg {
fill: orange;
}
I got this results with a material icon SVG:
Mozilla Firefox 59.0.2 (64-bit) Linux
Google Chrome66.0.3359.181 (Build oficial) (64 bits) Linux
Opera 53.0.2907.37 Linux
The main problem in your case is that you are importing the svg from an <img> tag which will hide the SVG structure.
You need to use the <svg> tag in conjunction with the <use> to get the desired effect. To make it work, you need to give an id to the path you want to use in the SVG file <path id='myName'...> to then be able to retrieve them from the <use xlink:href="#myName"/> tag.
Try the snipped below.
.icon {
display: inline-block;
width: 2em;
height: 2em;
transition: .5s;
fill: currentColor;
stroke-width: 5;
}
.icon:hover {
fill: rgba(255,255,255,0);
stroke: black;
stroke-width: 2;
}
.red {
color: red;
}
.blue {
color: blue;
}
<svg width="0" height="0">
<defs>
<path id="home" d="M100 59.375l-18.75-18.75v-28.125h-12.5v15.625l-18.75-18.75-50 50v3.125h12.5v31.25h31.25v-18.75h12.5v18.75h31.25v-31.25h12.5z"/>
</svg>
<span class="icon red">
<svg viewbox="0 0 100 100">
<use xlink:href="#home"/>
</svg>
</span>
<span class="icon blue">
<svg viewbox="0 0 100 100">
<use xlink:href="#home"/>
</svg>
</span>
Note that you can put any URL before the fragment # if you want to load the SVG from an external source (and not embed it into your HTML). Also, usually you do not specify the fill into the CSS. It's better to consider using fill:"currentColor" within the SVG itself. The corresponding element's CSS color value will then be used in place.
This might be helpful for people using PHP in combination with .svg images that they want to manipulate with CSS.
You can't overwrite properties inside a img tag with CSS. But when the svg source code is embedded in the HTML you surely can. I like to resolve this issue with a require_once function where I include a .svg.php file. It's like importing an image but you can still overwrite styles with CSS!
First include the svg file:
<?php require_once( '/assets/images/my-icon.svg.php' ); ?>
And it includes this icon for example:
<svg xmlns="http://www.w3.org/2000/svg" width="20.666" height="59.084" viewBox="0 0 20.666 59.084"><g transform="translate(-639.749 -3139)"><path d="M648.536,3173.876c0-2.875-1.725-3.8-3.471-3.8-1.683,0-3.49.9-3.49,3.8,0,3,1.786,3.8,3.49,3.8C646.811,3177.676,648.536,3176.769,648.536,3173.876Zm-3.471,2.341c-.883,0-1.437-.513-1.437-2.341,0-1.971.615-2.381,1.437-2.381.862,0,1.438.349,1.438,2.381,0,1.907-.616,2.339-1.438,2.339Z" fill="#142312"/><path d="M653.471,3170.076a1.565,1.565,0,0,0-1.416.9l-6.558,13.888h1.2a1.565,1.565,0,0,0,1.416-.9l6.559-13.887Z" fill="#142312"/><path d="M655.107,3177.263c-1.684,0-3.471.9-3.471,3.8,0,3,1.766,3.8,3.471,3.8,1.745,0,3.49-.9,3.49-3.8C658.6,3178.186,656.851,3177.263,655.107,3177.263Zm0,6.139c-.884,0-1.438-.514-1.438-2.34,0-1.972.617-2.381,1.438-2.381.862,0,1.437.349,1.437,2.381,0,1.909-.616,2.34-1.437,2.34Z" fill="#142312"/><path d="M656.263,3159.023l-1.49-14.063a1.35,1.35,0,0,0,.329-.293,1.319,1.319,0,0,0,.268-1.123l-.753-3.49a1.328,1.328,0,0,0-1.306-1.054h-6.448a1.336,1.336,0,0,0-1.311,1.068l-.71,3.493a1.344,1.344,0,0,0,.276,1.112,1.532,1.532,0,0,0,.283.262l-1.489,14.087c-1.7,1.727-4.153,4.871-4.153,8.638v28.924a1.339,1.339,0,0,0,1.168,1.49,1.357,1.357,0,0,0,.17.01h17.981a1.366,1.366,0,0,0,1.337-1.366v-29.059C660.414,3163.893,657.963,3160.749,656.263,3159.023Zm-8.307-17.349h4.274l.176.815H647.79Zm9.785,43.634v10.1H642.434v-17.253a4.728,4.728,0,0,1-2.028-4.284,4.661,4.661,0,0,1,2.028-4.215v-2c0-3.162,2.581-5.986,3.687-7.059a1.356,1.356,0,0,0,.4-.819l1.542-14.614H652.1l1.545,14.618a1.362,1.362,0,0,0,.4.819c1.109,1.072,3.688,3.9,3.688,7.059v9.153a5.457,5.457,0,0,1,0,8.5Z" fill="#142312"/></g></svg>
Now we can easily change the fill color like this with CSS:
svg path {
fill: blue;
}
I first tried to solve this problem with file_get_contents() but the solution above is much faster.
open the svg icon in your code editor and add a class after the path tag:
<path class'colorToChange' ...
You can add class to svg and change the color like this:
codepen
Know this is an old question but recently we came across the same issue, and we solved it from the server side. This is a php specific answer but I am positive that other envs have something similar.
instead of using the img tag you render the svg as svg from the get-go.
public static function print_svg($file){
$iconfile = new \DOMDocument();
$iconfile->load($file);
$tag = $iconfile->saveHTML($iconfile->getElementsByTagName('svg')[0]);
return $tag;
}
now when you render the file you will get complete inline svg
For me, my svgs looked different when having them as img and svg. So my solution converts the img to csv, changes styles internally and back to img (although it requires a bit more work), I believe "blob" also has better compatibility than the upvoted answer using "mask".
let img = yourimgs[0];
if (img.src.includes(".svg")) {
var ajax = new XMLHttpRequest();
ajax.open("GET", img.src, true);
ajax.send();
ajax.onload = function (e) {
svg = e.target.responseText;
svgText = "";
//change your svg-string as youd like, for example
// replacing the hex color between "{fill:" and ";"
idx = svg.indexOf("{fill:");
substr = svg.substr(idx + 6);
str1 = svg.substr(0, idx + 6);
str2 = substr.substr(substr.indexOf(";"));
svgText = str1 + "#ff0000" + str2;
let blob = new Blob([svgText], { type: "image/svg+xml" });
let url = URL.createObjectURL(blob);
let image = document.createElement("img");
image.src = url;
image.addEventListener("load", () => URL.revokeObjectURL(url), {
once: true,
});
img.replaceWith(image);
};
}
Simple JS
Use following short function ImgToSvg which swap img to svg (including class list)
<img src="logo.svg" onload="ImgToSvg(this)" class="logo-img"/>
const ImgToSvg= async (img) => {
const s = document.createElement('div');
s.innerHTML = await (await fetch(img.src)).text();
s.firstChild.classList = img.classList;
img.replaceWith(s.firstChild)
}
.logo-img {
fill: yellow;
}
<img onload="ImgToSvg(this)" class="logo-img" src="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB4PSIyIiB5PSIyIiB3aWR0aD0iMjk2IiBoZWlnaHQ9IjI5NiIgc3R5bGU9InN0cm9rZTojNTU1NTU1O3N0cm9rZS13aWR0aDoyIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtc2l6ZT0iMTgiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGFsaWdubWVudC1iYXNlbGluZT0ibWlkZGxlIiBmb250LWZhbWlseT0ibW9ub3NwYWNlLCBzYW5zLXNlcmlmIiBmaWxsPSIjNTU1NTU1Ij4zMDAmIzIxNTszMDA8L3RleHQ+PC9zdmc+" />
<!-- in this snippet I use dataURI in img src to avoid CORS problems witch reading svg data from external source by js -->
This is improvement of Waruyama answer by providing short js function
I wanted to change specific paths and/or colors only and even colorize paths differently. Also, in my case some CSS was applied to the IMG-tag directly, hence I wanted to let it be original IMG-element to not mess around with positioning and alignment.
Thanks to inspiration from this answer: https://stackoverflow.com/a/43015413/1444589, this is what worked for me:
let img = document.querySelector('img[class^="YourClassName"]');
let imgURL = img.src;
fetch(imgURL)
.then(response => response.text())
.then(text => {
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(text, 'text/xml');
let svg = xmlDoc.getElementsByTagName('svg')[0];
let paths = xmlDoc.getElementsByTagName('path');
// access individual path elements directly
let leftShape = paths[0];
leftShape.setAttribute('fill', '#4F4F4F');
// or find specific color
const pathsArr = Array.from(paths);
let skirtShape = pathsArr.find(path => path.getAttribute('fill') === '#F038A5');
skirtShape.setAttribute('fill', '#0078D6');
// Replace old SVG with colorized SVG
// positioning and alignment is left untouched
let base64Str = btoa(new XMLSerializer().serializeToString(svg));
img.src = 'data:image/svg+xml;base64, ' + base64Str;
});
Why not just using CSS's filter property to manipulate the color on :hover or whatever other state? I found it works over SVG images into img tags. At least, it's almost fully supported in 2020. It seams to me the simpliest solution. The only caveat is having to tweak the filter properties in order to find the target color. But you have also this very useful tool.
for that matters you have to use your SVG as an inline HTML.
say here's your logo.svg code (when you open it on textEditor):
Logo.SVG
<svg width="139" height="100" xmlns="http://www.w3.org/2000/svg">
<!-- Note that I've Added Class Attribute 'logo-img' Here -->
<g transform="translate(-22 -45)" fill="none" fill-rule="evenodd">
<path
d="M158.023 48.118a7.625 7.625 0 01-.266 10.78l-88.11 83.875a7.625 7.625 0 01-10.995-.5l-33.89-38.712a7.625 7.625 0 0111.475-10.045l28.653 32.73 82.353-78.394a7.625 7.625 0 0110.78.266z"
fill="#00000" />
</g>
</svg>
add your desired Class/ID to it (i've added 'logo-img'):
Edited Svg
<svg class="logo-img" width="139" height="100" xmlns="http://www.w3.org/2000/svg">
<!-- Note that I've Added Class Attribute 'logo-img' Here -->
...
</svg>
Now apply Your Css Rules:
CSS
.logo-img path {
fill: #000;
}
Pro
With this way you can animate on user's actions (hover, selected,...)
Con
Your HTML File would be a mess.
Heres a Stack Snippet
<style>
body {
display: flex;
justify-content: center;
}
.logo-img path {
transition: .5s all linear;
}
.logo-img path {
fill: coral;
}
.logo-img:hover path{
fill: darkblue;
}
</style>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<svg class="logo-img" width="139" height="100" xmlns="http://www.w3.org/2000/svg">
<!-- Note that I've Added Class Attribute 'logo-img' Here -->
<g transform="translate(-22 -45)" fill="none" fill-rule="evenodd">
<path
d="M158.023 48.118a7.625 7.625 0 01-.266 10.78l-88.11 83.875a7.625 7.625 0 01-10.995-.5l-33.89-38.712a7.625 7.625 0 0111.475-10.045l28.653 32.73 82.353-78.394a7.625 7.625 0 0110.78.266z"
fill="#00000" />
</g>
</svg>
</body>
</html>
If your shape(s) are always one solid color and you have more than a couple, you can use Fontello and make a custom icon font with a whole series of your own custom SVG shapes. Then you can set/animate the size and color of all of them with CSS alone.
For all the possible use cases for this question, this is an essential paradigm to consider. I've used it in many projects. In any case, if you haven't heard of Fontello, you need to find out about it. If you know of a similar solution that is better, I would love to know.
Possible downfalls:
Icon/shape fonts are known to mess with screen readers, so that may take some handling.
Fontello can be finicky with importing shapes, and it may take some trial and error with authoring and exporting them.
Avoid any and all grouping, and use only single non-nested compound shapes.
Directly to svg fill css will not work you can use as below
<style>
svg path {
fill: red;
}
</style>
<svg xmlns="http://www.w3.org/2000/svg" width="20.666" height="59.084" viewBox="0 0 20.666 59.084"><g transform="translate(-639.749 -3139)"><path d="M648.536,3173.876c0-2.875-1.725-3.8-3.471-3.8-1.683,0-3.49.9-3.49,3.8,0,3,1.786,3.8,3.49,3.8C646.811,3177.676,648.536,3176.769,648.536,3173.876Zm-3.471,2.341c-.883,0-1.437-.513-1.437-2.341,0-1.971.615-2.381,1.437-2.381.862,0,1.438.349,1.438,2.381,0,1.907-.616,2.339-1.438,2.339Z" fill="#142312"/><path d="M653.471,3170.076a1.565,1.565,0,0,0-1.416.9l-6.558,13.888h1.2a1.565,1.565,0,0,0,1.416-.9l6.559-13.887Z" fill="#142312"/><path d="M655.107,3177.263c-1.684,0-3.471.9-3.471,3.8,0,3,1.766,3.8,3.471,3.8,1.745,0,3.49-.9,3.49-3.8C658.6,3178.186,656.851,3177.263,655.107,3177.263Zm0,6.139c-.884,0-1.438-.514-1.438-2.34,0-1.972.617-2.381,1.438-2.381.862,0,1.437.349,1.437,2.381,0,1.909-.616,2.34-1.437,2.34Z" fill="#142312"/><path d="M656.263,3159.023l-1.49-14.063a1.35,1.35,0,0,0,.329-.293,1.319,1.319,0,0,0,.268-1.123l-.753-3.49a1.328,1.328,0,0,0-1.306-1.054h-6.448a1.336,1.336,0,0,0-1.311,1.068l-.71,3.493a1.344,1.344,0,0,0,.276,1.112,1.532,1.532,0,0,0,.283.262l-1.489,14.087c-1.7,1.727-4.153,4.871-4.153,8.638v28.924a1.339,1.339,0,0,0,1.168,1.49,1.357,1.357,0,0,0,.17.01h17.981a1.366,1.366,0,0,0,1.337-1.366v-29.059C660.414,3163.893,657.963,3160.749,656.263,3159.023Zm-8.307-17.349h4.274l.176.815H647.79Zm9.785,43.634v10.1H642.434v-17.253a4.728,4.728,0,0,1-2.028-4.284,4.661,4.661,0,0,1,2.028-4.215v-2c0-3.162,2.581-5.986,3.687-7.059a1.356,1.356,0,0,0,.4-.819l1.542-14.614H652.1l1.545,14.618a1.362,1.362,0,0,0,.4.819c1.109,1.072,3.688,3.9,3.688,7.059v9.153a5.457,5.457,0,0,1,0,8.5Z" fill="#142312"/></g></svg>
This worked for me

Dynamically adjust font-size with height and width of the container [duplicate]

I'm having a hard time getting my head around font scaling.
I currently have a website with a body font-size of 100%. 100% of what though? This seems to compute out at 16 pixels.
I was under the impression that 100% would somehow refer to the size of the browser window, but apparently not because it's always 16 pixels whether the window is resized down to a mobile width or full-blown widescreen desktop.
How can I make the text on my site scale in relation to its container? I tried using em, but this doesn't scale either.
My reasoning is that things like my menu become squished when you resize, so I need to reduce the px font-size of .menuItem among other elements in relation to the width of the container. (For example, in the menu on a large desktop, 22px works perfectly. Move down to tablet width and 16px is more appropriate.)
I'm aware I can add breakpoints, but I really want the text to scale as well as having extra breakpoints, otherwise, I'll end up with hundreds of breakpoints for every 100pixels decrease in width to control the text.
If the container is not the body, CSS Tricks covers all of your options in Fitting Text to a Container.
If the container is the body, what you are looking for is Viewport-percentage lengths:
The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly. However, when the value of overflow on the root element is auto, any scroll bars are assumed not to exist.
The values are:
vw (% of the viewport width)
vh (% of the viewport height)
vi (1% of the viewport size in the direction of the root element's inline axis)
vb (1% of the viewport size in the direction of the root element's block axis)
vmin (the smaller of vw or vh)
vmax (the larger or vw or vh)
1 v* is equal to 1% of the initial containing block.
Using it looks like this:
p {
font-size: 4vw;
}
As you can see, when the viewport width increases, so do the font-size, without needing to use media queries.
These values are a sizing unit, just like px or em, so they can be used to size other elements as well, such as width, margin, or padding.
Browser support is pretty good, but you'll likely need a fallback, such as:
p {
font-size: 16px;
font-size: 4vw;
}
Check out the support statistics: http://caniuse.com/#feat=viewport-units.
Also, check out CSS-Tricks for a broader look: Viewport Sized Typography
Here's a nice article about setting minimum/maximum sizes and exercising a bit more control over the sizes: Precise control over responsive typography
And here's an article about setting your size using calc() so that the text fills the viewport: http://codepen.io/CrocoDillon/pen/fBJxu
Also, please view this article, which uses a technique dubbed 'molten leading' to adjust the line-height as well. Molten Leading in CSS
But what if the container is not the viewport (body)?
This question is asked in a comment by Alex under 2507rkt3's answer.
That fact does not mean vw cannot be used to some extent to size for that container. Now to see any variation at all one has to be assuming that the container in some way is flexible in size. Whether through a direct percentage width or through being 100% minus margins. The point becomes "moot" if the container is always set to, let's say, 200px wide--then just set a font-size that works for that width.
Example 1
With a flexible width container, however, it must be realized that in some way the container is still being sized off the viewport. As such, it is a matter of adjusting a vw setting based off that percentage size difference to the viewport, which means taking into account the sizing of parent wrappers. Take this example:
div {
width: 50%;
border: 1px solid black;
margin: 20px;
font-size: 16px;
/* 100 = viewport width, as 1vw = 1/100th of that
So if the container is 50% of viewport (as here)
then factor that into how you want it to size.
Let's say you like 5vw if it were the whole width,
then for this container, size it at 2.5vw (5 * .5 [i.e. 50%])
*/
font-size: 2.5vw;
}
Assuming here the div is a child of the body, it is 50% of that 100% width, which is the viewport size in this basic case. Basically, you want to set a vw that is going to look good to you. As you can see in my comment in the above CSS content, you can "think" through that mathematically with respect to the full viewport size, but you don't need to do that. The text is going to "flex" with the container because the container is flexing with the viewport resizing. Here's an example of two differently sized containers.
Example 2
You can help ensure viewport sizing by forcing the calculation based off that. Consider this example:
html {width: 100%;} /* Force 'html' to be viewport width */
body {width: 150%; } /* Overflow the body */
div {
width: 50%;
border: 1px solid black;
margin: 20px;
font-size: 16px;
/* 100 = viewport width, as 1vw = 1/100th of that
Here, the body is 150% of viewport, but the container is 50%
of viewport, so both parents factor into how you want it to size.
Let's say you like 5vw if it were the whole width,
then for this container, size it at 3.75vw
(5 * 1.5 [i.e. 150%]) * .5 [i.e. 50%]
*/
font-size: 3.75vw;
}
The sizing is still based off viewport, but is in essence set up based off the container size itself.
Should the Size of the Container Change Dynamically...
If the sizing of the container element ended up changing dynamically its percentage relationship either via #media breakpoints or via JavaScript, then whatever the base "target" was would need recalculation to maintain the same "relationship" for text sizing.
Take example #1 above. If the div was switched to 25% width by either #media or JavaScript, then at the same time, the font-size would need to adjust in either the media query or by JavaScript to the new calculation of 5vw * .25 = 1.25. This would put the text size at the same size it would have been had the "width" of the original 50% container been reduced by half from viewport sizing, but has now been reduced due to a change in its own percentage calculation.
A Challenge
With the CSS calc() function in use, it would become difficult to adjust dynamically, as that function does not work for font-size purposes at this time. So you could not do a pure CSS adjustment if your width is changing on calc(). Of course, a minor adjustment of width for margins may not be enough to warrant any change in font-size, so it may not matter.
Solution with SVG:
.resizeme {
resize: both;
margin: 0;
padding: 0;
height: 75px;
width: 500px;
background-color: lightblue;
overflow: hidden;
}
<div class="resizeme">
<svg
width="100%"
height="100%"
viewBox="0 0 500 75"
preserveAspectRatio="xMinYMid meet"
style="background-color:green"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
>
<text
x="0"
y="75"
font-size="75"
fill="black"
>█Resize This█</text>
</svg>
</div>
Solution with SVG and text-wrapping using foreignObject:
.resizeme {
resize: both;
margin: 0;
padding: 0;
height: 200px;
width: 500px;
background-color: lightblue;
overflow: hidden;
}
<div class="resizeme">
<svg
width="100%"
height="100%"
viewBox="0 0 500 200"
preserveAspectRatio="xMinYMin meet"
>
<foreignObject width="100%" height="100%" xmlns="http://www.w3.org/1999/xhtml">
<div xmlns="http://www.w3.org/1999/xhtml" style="background-color:lightgreen;">
<h1>heading</h1>
<p>Resize the blue box.</p>
</div>
</foreignObject>
</svg>
</div>
In one of my projects I use a "mixture" between vw and vh to adjust the font size to my needs, for example:
font-size: calc(3vw + 3vh);
I know this doesn't answer the OP's question, but maybe it can be a solution to anyone else.
Pure-CSS solution with calc(), CSS units and math
This is precisely not what OP asks, but may make someone's day. This answer is not spoon-feedingly easy and needs some researching on the developer end.
I came finally to get a pure-CSS solution for this using calc() with different units. You will need some basic mathematical understanding of formulas to work out your expression for calc().
When I worked this out, I had to get a full-page-width responsive header with some padding few parents up in DOM. I'll use my values here, replace them with your own.
To mathematics
You will need:
Nicely adjusted ratio in some viewport. I used 320 pixels, thus I got 24 pixels high and 224 pixels wide, so the ratio is 9.333... or 28 / 3
The container width, I had padding: 3em and full width so this got to 100wv - 2 * 3em
X is the width of container, so replace it with your own expression or adjust the value to get full-page text. R is the ratio you will have. You can get it by adjusting the values in some viewport, inspecting element width and height and replacing them with your own values. Also, it is width / heigth ;)
x = 100vw - 2 * 3em = 100vw - 6em
r = 224px/24px = 9.333... = 28 / 3
y = x / r
= (100vw - 6em) / (28 / 3)
= (100vw - 6em) * 3 / 28
= (300vw - 18em) / 28
= (75vw - 4.5rem) / 7
And bang! It worked! I wrote
font-size: calc((75vw - 4.5rem) / 7)
to my header and it adjusted nicely in every viewport.
But how does it work?
We need some constants up here. 100vw means the full width of viewport, and my goal was to establish full-width header with some padding.
The ratio. Getting a width and height in one viewport got me a ratio to play with, and with ratio I know what the height should be in other viewport width. Calculating them with hand would take plenty of time and at least take lots of bandwidth, so it's not a good answer.
Conclusion
I wonder why no-one has figured this out and some people are even telling that this would be impossible to tinker with CSS. I don't like to use JavaScript in adjusting elements, so I don't accept JavaScript (and forget about jQuery) answers without digging more. All in all, it's good that this got figured out and this is one step to pure-CSS implementations in website design.
I apologize of any unusual convention in my text, I'm not native speaker in English and am also quite new to writing Stack Overflow answers.
It should also be noted that we have evil scrollbars in some browsers. For example, when using Firefox I noticed that 100vw means the full width of viewport, extending under scrollbar (where content cannot expand!), so the fullwidth text has to be margined carefully and preferably get tested with many browsers and devices.
There is a big philosophy for this issue.
The easiest thing to do would be to give a certain font-size to body (I recommend 10), and then all the other element would have their font in em or rem.
I'll give you an example to understand those units.
Em is always relative to its parent:
body{font-size: 10px;}
.menu{font-size: 2em;} /* That means 2*10 pixels = 20 pixels */
.menu li{font-size: 1.5em;} /* That means 1.5*20 pixels = 30 pixels */
Rem is always relative to body:
body{font-size: 10px;}
.menu{font-size: 2rem;} /* That means 2*10 pixels = 20 pixels */
.menu li{font-size: 1.5rem;} /* that means 1.5*10 pixels = 15 pixels */
And then you could create a script that would modify font-size relative to your container width.
But this isn't what I would recommend. Because in a 900 pixels width container for example you would have a p element with a 12 pixels font-size let's say. And on your idea that would become an 300 pixels wide container at 4 pixels font-size. There has to be a lower limit.
Other solutions would be with media queries, so that you could set font for different widths.
But the solutions that I would recommend is to use a JavaScript library that helps you with that. And fittext.js that I found so far.
Here is the function:
document.body.setScaledFont = function(f) {
var s = this.offsetWidth, fs = s * f;
this.style.fontSize = fs + '%';
return this
};
Then convert all your documents child element font sizes to em's or %.
Then add something like this to your code to set the base font size.
document.body.setScaledFont(0.35);
window.onresize = function() {
document.body.setScaledFont(0.35);
}
http://jsfiddle.net/0tpvccjt/
There is a way to do this without JavaScript!
You can use an inline SVG image. You can use CSS on an SVG if it is inline. You have to remember that using this method means your SVG image will respond to its container size.
Try using the following solution...
HTML
<div>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 360.96 358.98" >
<text>SAVE $500</text>
</svg>
</div>
CSS
div {
width: 50%; /* Set your container width */
height: 50%; /* Set your container height */
}
svg {
width: 100%;
height: auto;
}
text {
transform: translate(40px, 202px);
font-size: 62px;
fill: #000;
}
Example:
https://jsfiddle.net/k8L4xLLa/32/
Want something more flashy?
SVG images also allow you to do cool stuff with shapes and junk. Check out this great use case for scalable text...
https://jsfiddle.net/k8L4xLLa/14/
CSS Container Queries
A late-2022 addition to the CSS feature set makes scaling font size with containers straightforward.
Container queries come with a new set of CSS units cqw/cqh (container query width/height). To use them you need to set the container-type property on the parent element whose size you want to use. Minimal example:
<div>
<p>Lorem ipsum dolor sit amet</p>
</div>
<style>
div {
container-type: inline-size;
}
p {
font-size: 5cqw;
}
</style>
The font size will increase smoothly as the container grows. At 1000px container width, the p font size will be 1000px / 100 * 5 = 50px.
container-type can be size or inline-size. size tracks both height and width of the container which allows you to use both cqw and cqh.
Most of the time on the web, heights are calculated based on content and you only specify the width. To save the browser some work, you'll generally want to set container-type: inline-size; so the browser only tracks the inline dimension which is usually width (unless you set writing-mode to vertical).
Browser support for container queries has grown rapidly in the 2nd half of 2022 and currently stands at 75% (2023-01-01).
This may not be super practical, but if you want a font to be a direct function of the parent, without having any JavaScript that listens/loops (interval) to read the size of the div/page, there is a way to do it. Iframes.
Anything within the iframe will consider the size of the iframe as the size of the viewport. So the trick is to just make an iframe whose width is the maximum width you want your text to be, and whose height is equal to the maximum height * the particular text's aspect ratio.
Setting aside the limitation that viewport units can't also come along side parent units for text (as in, having the % size behave like everyone else), viewport units do provide a very powerful tool: being able to get the minimum/maximum dimension. You can't do that anywhere else - you can't say...make the height of this div be the width of the parent * something.
That being said, the trick is to use vmin, and to set the iframe size so that [fraction] * total height is a good font size when the height is the limiting dimension, and [fraction] * total width when the width is the limiting dimension. This is why the height has to be a product of the width and the aspect ratio.
For my particular example, you have
.main iframe{
position: absolute;
top: 50%;
left: 50%;
width: 100%;
height: calc(3.5 * 100%);
background: rgba(0, 0, 0, 0);
border-style: none;
transform: translate3d(-50%, -50%, 0);
}
The small annoyance with this method is that you have to manually set the CSS of the iframe. If you attach the whole CSS file, that would take up a lot of bandwidth for many text areas. So, what I do is attach the rule that I want directly from my CSS.
var rule = document.styleSheets[1].rules[4];
var iDoc = document.querySelector('iframe').contentDocument;
iDoc.styleSheets[0].insertRule(rule.cssText);
You can write small function that gets the CSS rule / all CSS rules that would affect the text area.
I cannot think of another way to do it without having some cycling/listening JavaScript. The real solution would be for browsers to provide a way to scale text as a function of the parent container and to also provide the same vmin/vmax type functionality.
JSFiddle:
https://jsfiddle.net/0jr7rrgm/3/
(click once to lock the red square to the mouse, and click again to release)
Most of the JavaScript in the fiddle is just my custom click-drag function.
Using vw, em & co. works for sure, but IMO it always needs a human's touch for fine-tuning.
Here's a script I just wrote based on #tnt-rox' answer that tries to automatize that human's touch:
$('#controller').click(function(){
$('h2').each(function(){
var
$el = $(this),
max = $el.get(0),
el = null
;
max =
max
? max.offsetWidth
: 320
;
$el.css({
'font-size': '1em',
'display': 'inline',
});
el = $el.get(0);
el.get_float = function(){
var
fs = 0
;
if (this.style && this.style.fontSize) {
fs = parseFloat(this.style.fontSize.replace(/([\d\.]+)em/g, '$1'));
}
return fs;
};
el.bigger = function(){
this.style.fontSize = (this.get_float() + 0.1) + 'em';
};
while (el.offsetWidth < max) {
el.bigger();
}
// Finishing touch.
$el.css({
'font-size': ((el.get_float() -0.1) +'em'),
'line-height': 'normal',
'display': '',
});
}); // end of (each)
}); // end of (font scaling test)
div {
width: 50%;
background-color: tomato;
font-family: 'Arial';
}
h2 {
white-space: nowrap;
}
h2:nth-child(2) {
font-style: italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="button" id="controller" value="Apply" />
<div>
<h2>Lorem ipsum dolor</h2>
<h2>Test String</h2>
<h2>Sweet Concatenation</h2>
<h2>Font Scaling</h2>
</div>
It basically reduces the font-size to 1em and then starts incrementing by 0.1 until it reaches maximum width.
JSFiddle
Use CSS Variables
No one has mentioned CSS variables yet, and this approach worked best for me, so:
Let's say you've got a column on your page that is 100% of the width of a mobile user's screen, but has a max-width of 800px, so on desktop there's some space on either side of the column. Put this at the top of your page:
<script> document.documentElement.style.setProperty('--column-width', Math.min(window.innerWidth, 800)+'px'); </script>
And now you can use that variable (instead of the built-in vw unit) to set the size of your font. E.g.
p {
font-size: calc( var(--column-width) / 100 );
}
It's not a pure CSS approach, but it's pretty close.
100% is relative to the base font size, which, if you haven't set it, would be the browser's user-agent default.
To get the effect you're after, I would use a piece of JavaScript code to adjust the base font size relative to the window dimensions.
Artistically, if you need to fit two or more lines of text within the same width regardless of their character count then you have nice options.
It's best to find a dynamical solution so whatever text is entered we end up with a nice display.
Let's see how we may approach.
var els = document.querySelectorAll(".divtext"),
refWidth = els[0].clientWidth,
refFontSize = parseFloat(window.getComputedStyle(els[0],null)
.getPropertyValue("font-size"));
els.forEach((el,i) => el.style.fontSize = refFontSize * refWidth / els[i].clientWidth + "px")
#container {
display: inline-block;
background-color: black;
padding: 0.6vw 1.2vw;
}
.divtext {
display: table;
color: white;
font-family: impact;
font-size: 4.5vw;
}
<div id="container">
<div class="divtext">THIS IS JUST AN</div>
<div class="divtext">EXAMPLE</div>
<div class="divtext">TO SHOW YOU WHAT</div>
<div class="divtext">YOU WANT</div>
</div>
All we do is to get the width (els[0].clientWidth) and the font size (parseFloat(window.getComputedStyle(els[0],null).getPropertyValue("font-size"))) of the first line as a reference and then just calculate the subsequent lines font size accordingly.
This web component changes the font size so the inner text width matches the container width. Check the demo.
You can use it like this:
<full-width-text>Lorem Ipsum</full-width-text>
You may be you looking for something like this:
http://jsfiddle.net/sijav/dGsC9/4/
http://fiddle.jshell.net/sijav/dGsC9/4/show/
I have used flowtype, and it's working great (however it's JavaScript and not a pure CSS solution):
$('body').flowtype({
minFont: 10,
maxFont: 40,
minimum: 500,
maximum: 1200,
fontRatio: 70
});
I've prepared a simple scale function using CSS transform instead of font-size. You can use it inside of any container, you don't have to set media queries, etc. :)
Blog post:
Full width CSS & JS scalable header
The code:
function scaleHeader() {
var scalable = document.querySelectorAll('.scale--js');
var margin = 10;
for (var i = 0; i < scalable.length; i++) {
var scalableContainer = scalable[i].parentNode;
scalable[i].style.transform = 'scale(1)';
var scalableContainerWidth = scalableContainer.offsetWidth - margin;
var scalableWidth = scalable[i].offsetWidth;
scalable[i].style.transform = 'scale(' + scalableContainerWidth / scalableWidth + ')';
scalableContainer.style.height = scalable[i].getBoundingClientRect().height + 'px';
}
}
Working demo:
https://codepen.io/maciejkorsan/pen/BWLryj
Inside your CSS, try adding this at the bottom changing the 320 pixels width for wherever your design starts breaking:
#media only screen and (max-width: 320px) {
body { font-size: 1em; }
}
Then give the font-size in "px" or "em" as you wish.
Try http://simplefocus.com/flowtype/. This is what I use for my sites, and it has worked perfectly.
My own solution, jQuery-based, works by gradually increasing the font size until the container gets a big increase in height (meaning it got a line break).
It's pretty simple, but works fairly well, and it is very easy to use. You don't have to know anything about the font being used, everything is taken care of by the browser.
You can play with it on http://jsfiddle.net/tubededentifrice/u5y15d0L/2/
The magic happens here:
var setMaxTextSize=function(jElement) {
// Get and set the font size into data for reuse upon resize
var fontSize=parseInt(jElement.data(quickFitFontSizeData)) || parseInt(jElement.css("font-size"));
jElement.data(quickFitFontSizeData, fontSize);
// Gradually increase font size until the element gets a big increase in height (i.e. line break)
var i = 0;
var previousHeight;
do
{
previousHeight=jElement.height();
jElement.css("font-size", "" + (++fontSize) + "px");
}
while(i++ < 300 && jElement.height()-previousHeight < fontSize/2)
// Finally, go back before the increase in height and set the element as resized by adding quickFitSetClass
fontSize -= 1;
jElement.addClass(quickFitSetClass).css("font-size", "" + fontSize + "px");
return fontSize;
};
My problem was similar, but related to scaling text within a heading. I tried Fit Font, but I needed to toggle the compressor to get any results, since it was solving a slightly different problem, as was Text Flow.
So I wrote my own little plugin that reduced the font size to fit the container, assuming you have overflow: hidden and white-space: nowrap so that even if reducing the font to the minimum doesn't allow showing the full heading, it just cuts off what it can show.
(function($) {
// Reduces the size of text in the element to fit the parent.
$.fn.reduceTextSize = function(options) {
options = $.extend({
minFontSize: 10
}, options);
function checkWidth(em) {
var $em = $(em);
var oldPosition = $em.css('position');
$em.css('position', 'absolute');
var width = $em.width();
$em.css('position', oldPosition);
return width;
}
return this.each(function(){
var $this = $(this);
var $parent = $this.parent();
var prevFontSize;
while (checkWidth($this) > $parent.width()) {
var currentFontSize = parseInt($this.css('font-size').replace('px', ''));
// Stop looping if min font size reached, or font size did not change last iteration.
if (isNaN(currentFontSize) || currentFontSize <= options.minFontSize ||
prevFontSize && prevFontSize == currentFontSize) {
break;
}
prevFontSize = currentFontSize;
$this.css('font-size', (currentFontSize - 1) + 'px');
}
});
};
})(jQuery);
Try to use the fitText plugin, because Viewport sizes isn't the solution of this problem.
Just add the library:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
And change font-size for correct by settings the coefficient of text:
$("#text_div").fitText(0.8);
You can set maximum and minimum values of text:
$("#text_div").fitText(0.8, { minFontSize: '12px', maxFontSize: '36px' });
Here is a pure CSS solution with the understanding that you admit breakpoints are necessary but also want text scaling:
I'm aware I can add breakpoints, but I really want the text to scale
as well as having extra breakpoints, otherwise....
Here is an approach using:
Custom properties
Media queries for breakpoints
clamp() (browser support in Feb 2022 is pretty good at 93%)
calc()
If one common scaling factor can be used to control ALL the text scaling within a container per screen max-width, all you need to do is scale a custom property per max-width, and apply this factor to 1 calculation.
A basic setup starts like this:
:root {
--scaling-factor: 1
}
.parent {
font-size: 30px
}
.largest {
font-size: clamp(60%, calc(var(--scaling-factor) * 100%), 100%);
}
.middle {
font-size: clamp(60%, calc(var(--scaling-factor) * 85%), 100%);
}
.smallest {
font-size: clamp(60%, calc(var(--scaling-factor) * 70%), 100%);
}
Then nest your media queries something like this (or whatever you need for your breakpoints):
#media (max-width: 1200px) {
:root {
--scaling-factor: 0.9
}
#media (max-width: 800px) {
:root {
--scaling-factor: 0.8
}
#media (max-width: 600px) {
:root {
--scaling-factor: 0.5 /* nope, because the font-size is floored at 60% thanks to clamp() */
}
}
}
}
This minimizes your media query markup.
Advantages
One custom property controls ALL scaling ... no need to add multiple declarations per media breakpoint
The use of clamp() sets a lower-limit on what the font-size should be, so you ensure your text is never too small (here the floor is 60% of the parent's font-size)
Please see this JSFiddle for a demo. Resize the window until at the smallest widths, the paragraphs are all the same font-size.
Always have your element with this attribute:
JavaScript: element.style.fontSize = "100%";
or
CSS: style = "font-size: 100%;"
When you go fullscreen, you should already have a scale variable calculated (scale > 1 or scale = 1). Then, on fullscreen:
document.body.style.fontSize = (scale * 100) + "%";
It works nicely with little code.
Take look at my code. It makes the font size smaller to fit whatever there.
But I think this doesn't lead to a good user experience
var containerWidth = $("#ui-id-2").width();
var items = $(".quickSearchAutocomplete .ui-menu-item");
var fontSize = 16;
items.each(function(){
// Displaying a value depends sometimes on your case. You may make it block or inline-table instead of inline-block or whatever value that make the div take overflow width.
$(this).css({"whiteSpace": "nowrap", "display": "inline-block"});
while ($(this).width() > containerWidth){
console.log("$(this).width()" + $(this).width() + "containerWidth" + containerWidth)
$(this).css("font-size", fontSize -= 0.5);
}
});
For dynamic text, this plugin is quite useful:
http://freqdec.github.io/slabText/
Simply add CSS:
.slabtexted .slabtext
{
display: -moz-inline-box;
display: inline-block;
white-space: nowrap;
}
.slabtextinactive .slabtext
{
display: inline;
white-space: normal;
font-size: 1em !important;
letter-spacing: inherit !important;
word-spacing: inherit !important;
*letter-spacing: normal !important;
*word-spacing: normal !important;
}
.slabtextdone .slabtext
{
display: block;
}
And the script:
$('#mydiv').slabText();
This worked for me:
I try to approximate font-size based on a width/height got from setting `font-size: 10px`. Basically, the idea is "if I have 20 pixels width and 11 pixels height with `font-size: 10px`, so what would it be the maximum font-size to math a container of 50 pixels width and 30 pixels height?"
The answer is a double proportion system:
{ 20:10=50:X, 11:10=30:Y } = { X= (10*50)/20, Y= (10*30)/11 }
Now X is a font-size that will match width, and Y is a font-size that will match height; take the smallest value
function getMaxFontSizeApprox(el){
var fontSize = 10;
var p = el.parentNode;
var parent_h = p.offsetHeight ? p.offsetHeight : p.style.pixelHeight;
if(!parent_h)
parent_h = 0;
var parent_w = p.offsetHeight ? p.offsetWidth : p.style.pixelWidth;
if(!parent_w)
parent_w = 0;
el.style.fontSize = fontSize + "px";
var el_h = el.offsetHeight ? el.offsetHeight : el.style.pixelHeight;
if(!el_h)
el_h = 0;
var el_w = el.offsetHeight ? el.offsetWidth : el.style.pixelWidth;
if(!el_w)
el_w = 0;
// 0.5 is the error on the measure that JavaScript does
// if the real measure had been 12.49 px => JavaScript would have said 12px
// so we think about the worst case when could have, we add 0.5 to
// compensate the round error
var fs1 = (fontSize*(parent_w + 0.5))/(el_w + 0.5);
var fs2 = (fontSize*(parent_h) + 0.5)/(el_h + 0.5);
fontSize = Math.floor(Math.min(fs1,fs2));
el.style.fontSize = fontSize + "px";
return fontSize;
}
NB: the argument of the function must be a span element or an element which is smaller than its parent, otherwise if children and parent have both the same width/height function will fail.
let textElement = document.getElementById('text1');
let parentElement = textElement.parentElement;
const parentClientHeight = parentElement.clientHeight;
const parentClientWidth = parentElement.clientWidth;
textElement.style.padding = "unset";
textElement.style.margin = "auto";
let fontSize = parentClientHeight;
let minFS = 3,
maxFS = fontSize;
while (fontSize != minFS) {
textElement.style.fontSize = `${fontSize}px`;
if (
parentElement.scrollHeight <= parentClientHeight &&
parentElement.scrollWidth <= parentClientWidth
) {
minFS = fontSize;
} else {
maxFS = fontSize;
}
fontSize = Math.floor((minFS + maxFS) / 2);
}
textElement.style.fontSize = `${minFS}px`;
<div style="height:200px; width:300px;">
<div id='text1'>
test
</div>
</div>
As a JavaScript fallback (or your sole solution), you can use my jQuery Scalem plugin, which lets you scale relative to the parent element (container) by passing the reference option.
In case it's helpful to anyone, most of the solutions in this thread were wrapping text into multiple lines, form e.
But then I found this, and it worked:
https://github.com/chunksnbits/jquery-quickfit
Example usage:
$('.someText').quickfit({max:50,tolerance:.4})

Change font-size to fit text width to parent element [duplicate]

I'm having a hard time getting my head around font scaling.
I currently have a website with a body font-size of 100%. 100% of what though? This seems to compute out at 16 pixels.
I was under the impression that 100% would somehow refer to the size of the browser window, but apparently not because it's always 16 pixels whether the window is resized down to a mobile width or full-blown widescreen desktop.
How can I make the text on my site scale in relation to its container? I tried using em, but this doesn't scale either.
My reasoning is that things like my menu become squished when you resize, so I need to reduce the px font-size of .menuItem among other elements in relation to the width of the container. (For example, in the menu on a large desktop, 22px works perfectly. Move down to tablet width and 16px is more appropriate.)
I'm aware I can add breakpoints, but I really want the text to scale as well as having extra breakpoints, otherwise, I'll end up with hundreds of breakpoints for every 100pixels decrease in width to control the text.
If the container is not the body, CSS Tricks covers all of your options in Fitting Text to a Container.
If the container is the body, what you are looking for is Viewport-percentage lengths:
The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly. However, when the value of overflow on the root element is auto, any scroll bars are assumed not to exist.
The values are:
vw (% of the viewport width)
vh (% of the viewport height)
vi (1% of the viewport size in the direction of the root element's inline axis)
vb (1% of the viewport size in the direction of the root element's block axis)
vmin (the smaller of vw or vh)
vmax (the larger or vw or vh)
1 v* is equal to 1% of the initial containing block.
Using it looks like this:
p {
font-size: 4vw;
}
As you can see, when the viewport width increases, so do the font-size, without needing to use media queries.
These values are a sizing unit, just like px or em, so they can be used to size other elements as well, such as width, margin, or padding.
Browser support is pretty good, but you'll likely need a fallback, such as:
p {
font-size: 16px;
font-size: 4vw;
}
Check out the support statistics: http://caniuse.com/#feat=viewport-units.
Also, check out CSS-Tricks for a broader look: Viewport Sized Typography
Here's a nice article about setting minimum/maximum sizes and exercising a bit more control over the sizes: Precise control over responsive typography
And here's an article about setting your size using calc() so that the text fills the viewport: http://codepen.io/CrocoDillon/pen/fBJxu
Also, please view this article, which uses a technique dubbed 'molten leading' to adjust the line-height as well. Molten Leading in CSS
But what if the container is not the viewport (body)?
This question is asked in a comment by Alex under 2507rkt3's answer.
That fact does not mean vw cannot be used to some extent to size for that container. Now to see any variation at all one has to be assuming that the container in some way is flexible in size. Whether through a direct percentage width or through being 100% minus margins. The point becomes "moot" if the container is always set to, let's say, 200px wide--then just set a font-size that works for that width.
Example 1
With a flexible width container, however, it must be realized that in some way the container is still being sized off the viewport. As such, it is a matter of adjusting a vw setting based off that percentage size difference to the viewport, which means taking into account the sizing of parent wrappers. Take this example:
div {
width: 50%;
border: 1px solid black;
margin: 20px;
font-size: 16px;
/* 100 = viewport width, as 1vw = 1/100th of that
So if the container is 50% of viewport (as here)
then factor that into how you want it to size.
Let's say you like 5vw if it were the whole width,
then for this container, size it at 2.5vw (5 * .5 [i.e. 50%])
*/
font-size: 2.5vw;
}
Assuming here the div is a child of the body, it is 50% of that 100% width, which is the viewport size in this basic case. Basically, you want to set a vw that is going to look good to you. As you can see in my comment in the above CSS content, you can "think" through that mathematically with respect to the full viewport size, but you don't need to do that. The text is going to "flex" with the container because the container is flexing with the viewport resizing. Here's an example of two differently sized containers.
Example 2
You can help ensure viewport sizing by forcing the calculation based off that. Consider this example:
html {width: 100%;} /* Force 'html' to be viewport width */
body {width: 150%; } /* Overflow the body */
div {
width: 50%;
border: 1px solid black;
margin: 20px;
font-size: 16px;
/* 100 = viewport width, as 1vw = 1/100th of that
Here, the body is 150% of viewport, but the container is 50%
of viewport, so both parents factor into how you want it to size.
Let's say you like 5vw if it were the whole width,
then for this container, size it at 3.75vw
(5 * 1.5 [i.e. 150%]) * .5 [i.e. 50%]
*/
font-size: 3.75vw;
}
The sizing is still based off viewport, but is in essence set up based off the container size itself.
Should the Size of the Container Change Dynamically...
If the sizing of the container element ended up changing dynamically its percentage relationship either via #media breakpoints or via JavaScript, then whatever the base "target" was would need recalculation to maintain the same "relationship" for text sizing.
Take example #1 above. If the div was switched to 25% width by either #media or JavaScript, then at the same time, the font-size would need to adjust in either the media query or by JavaScript to the new calculation of 5vw * .25 = 1.25. This would put the text size at the same size it would have been had the "width" of the original 50% container been reduced by half from viewport sizing, but has now been reduced due to a change in its own percentage calculation.
A Challenge
With the CSS calc() function in use, it would become difficult to adjust dynamically, as that function does not work for font-size purposes at this time. So you could not do a pure CSS adjustment if your width is changing on calc(). Of course, a minor adjustment of width for margins may not be enough to warrant any change in font-size, so it may not matter.
Solution with SVG:
.resizeme {
resize: both;
margin: 0;
padding: 0;
height: 75px;
width: 500px;
background-color: lightblue;
overflow: hidden;
}
<div class="resizeme">
<svg
width="100%"
height="100%"
viewBox="0 0 500 75"
preserveAspectRatio="xMinYMid meet"
style="background-color:green"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
>
<text
x="0"
y="75"
font-size="75"
fill="black"
>█Resize This█</text>
</svg>
</div>
Solution with SVG and text-wrapping using foreignObject:
.resizeme {
resize: both;
margin: 0;
padding: 0;
height: 200px;
width: 500px;
background-color: lightblue;
overflow: hidden;
}
<div class="resizeme">
<svg
width="100%"
height="100%"
viewBox="0 0 500 200"
preserveAspectRatio="xMinYMin meet"
>
<foreignObject width="100%" height="100%" xmlns="http://www.w3.org/1999/xhtml">
<div xmlns="http://www.w3.org/1999/xhtml" style="background-color:lightgreen;">
<h1>heading</h1>
<p>Resize the blue box.</p>
</div>
</foreignObject>
</svg>
</div>
In one of my projects I use a "mixture" between vw and vh to adjust the font size to my needs, for example:
font-size: calc(3vw + 3vh);
I know this doesn't answer the OP's question, but maybe it can be a solution to anyone else.
Pure-CSS solution with calc(), CSS units and math
This is precisely not what OP asks, but may make someone's day. This answer is not spoon-feedingly easy and needs some researching on the developer end.
I came finally to get a pure-CSS solution for this using calc() with different units. You will need some basic mathematical understanding of formulas to work out your expression for calc().
When I worked this out, I had to get a full-page-width responsive header with some padding few parents up in DOM. I'll use my values here, replace them with your own.
To mathematics
You will need:
Nicely adjusted ratio in some viewport. I used 320 pixels, thus I got 24 pixels high and 224 pixels wide, so the ratio is 9.333... or 28 / 3
The container width, I had padding: 3em and full width so this got to 100wv - 2 * 3em
X is the width of container, so replace it with your own expression or adjust the value to get full-page text. R is the ratio you will have. You can get it by adjusting the values in some viewport, inspecting element width and height and replacing them with your own values. Also, it is width / heigth ;)
x = 100vw - 2 * 3em = 100vw - 6em
r = 224px/24px = 9.333... = 28 / 3
y = x / r
= (100vw - 6em) / (28 / 3)
= (100vw - 6em) * 3 / 28
= (300vw - 18em) / 28
= (75vw - 4.5rem) / 7
And bang! It worked! I wrote
font-size: calc((75vw - 4.5rem) / 7)
to my header and it adjusted nicely in every viewport.
But how does it work?
We need some constants up here. 100vw means the full width of viewport, and my goal was to establish full-width header with some padding.
The ratio. Getting a width and height in one viewport got me a ratio to play with, and with ratio I know what the height should be in other viewport width. Calculating them with hand would take plenty of time and at least take lots of bandwidth, so it's not a good answer.
Conclusion
I wonder why no-one has figured this out and some people are even telling that this would be impossible to tinker with CSS. I don't like to use JavaScript in adjusting elements, so I don't accept JavaScript (and forget about jQuery) answers without digging more. All in all, it's good that this got figured out and this is one step to pure-CSS implementations in website design.
I apologize of any unusual convention in my text, I'm not native speaker in English and am also quite new to writing Stack Overflow answers.
It should also be noted that we have evil scrollbars in some browsers. For example, when using Firefox I noticed that 100vw means the full width of viewport, extending under scrollbar (where content cannot expand!), so the fullwidth text has to be margined carefully and preferably get tested with many browsers and devices.
There is a big philosophy for this issue.
The easiest thing to do would be to give a certain font-size to body (I recommend 10), and then all the other element would have their font in em or rem.
I'll give you an example to understand those units.
Em is always relative to its parent:
body{font-size: 10px;}
.menu{font-size: 2em;} /* That means 2*10 pixels = 20 pixels */
.menu li{font-size: 1.5em;} /* That means 1.5*20 pixels = 30 pixels */
Rem is always relative to body:
body{font-size: 10px;}
.menu{font-size: 2rem;} /* That means 2*10 pixels = 20 pixels */
.menu li{font-size: 1.5rem;} /* that means 1.5*10 pixels = 15 pixels */
And then you could create a script that would modify font-size relative to your container width.
But this isn't what I would recommend. Because in a 900 pixels width container for example you would have a p element with a 12 pixels font-size let's say. And on your idea that would become an 300 pixels wide container at 4 pixels font-size. There has to be a lower limit.
Other solutions would be with media queries, so that you could set font for different widths.
But the solutions that I would recommend is to use a JavaScript library that helps you with that. And fittext.js that I found so far.
Here is the function:
document.body.setScaledFont = function(f) {
var s = this.offsetWidth, fs = s * f;
this.style.fontSize = fs + '%';
return this
};
Then convert all your documents child element font sizes to em's or %.
Then add something like this to your code to set the base font size.
document.body.setScaledFont(0.35);
window.onresize = function() {
document.body.setScaledFont(0.35);
}
http://jsfiddle.net/0tpvccjt/
There is a way to do this without JavaScript!
You can use an inline SVG image. You can use CSS on an SVG if it is inline. You have to remember that using this method means your SVG image will respond to its container size.
Try using the following solution...
HTML
<div>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 360.96 358.98" >
<text>SAVE $500</text>
</svg>
</div>
CSS
div {
width: 50%; /* Set your container width */
height: 50%; /* Set your container height */
}
svg {
width: 100%;
height: auto;
}
text {
transform: translate(40px, 202px);
font-size: 62px;
fill: #000;
}
Example:
https://jsfiddle.net/k8L4xLLa/32/
Want something more flashy?
SVG images also allow you to do cool stuff with shapes and junk. Check out this great use case for scalable text...
https://jsfiddle.net/k8L4xLLa/14/
CSS Container Queries
A late-2022 addition to the CSS feature set makes scaling font size with containers straightforward.
Container queries come with a new set of CSS units cqw/cqh (container query width/height). To use them you need to set the container-type property on the parent element whose size you want to use. Minimal example:
<div>
<p>Lorem ipsum dolor sit amet</p>
</div>
<style>
div {
container-type: inline-size;
}
p {
font-size: 5cqw;
}
</style>
The font size will increase smoothly as the container grows. At 1000px container width, the p font size will be 1000px / 100 * 5 = 50px.
container-type can be size or inline-size. size tracks both height and width of the container which allows you to use both cqw and cqh.
Most of the time on the web, heights are calculated based on content and you only specify the width. To save the browser some work, you'll generally want to set container-type: inline-size; so the browser only tracks the inline dimension which is usually width (unless you set writing-mode to vertical).
Browser support for container queries has grown rapidly in the 2nd half of 2022 and currently stands at 75% (2023-01-01).
This may not be super practical, but if you want a font to be a direct function of the parent, without having any JavaScript that listens/loops (interval) to read the size of the div/page, there is a way to do it. Iframes.
Anything within the iframe will consider the size of the iframe as the size of the viewport. So the trick is to just make an iframe whose width is the maximum width you want your text to be, and whose height is equal to the maximum height * the particular text's aspect ratio.
Setting aside the limitation that viewport units can't also come along side parent units for text (as in, having the % size behave like everyone else), viewport units do provide a very powerful tool: being able to get the minimum/maximum dimension. You can't do that anywhere else - you can't say...make the height of this div be the width of the parent * something.
That being said, the trick is to use vmin, and to set the iframe size so that [fraction] * total height is a good font size when the height is the limiting dimension, and [fraction] * total width when the width is the limiting dimension. This is why the height has to be a product of the width and the aspect ratio.
For my particular example, you have
.main iframe{
position: absolute;
top: 50%;
left: 50%;
width: 100%;
height: calc(3.5 * 100%);
background: rgba(0, 0, 0, 0);
border-style: none;
transform: translate3d(-50%, -50%, 0);
}
The small annoyance with this method is that you have to manually set the CSS of the iframe. If you attach the whole CSS file, that would take up a lot of bandwidth for many text areas. So, what I do is attach the rule that I want directly from my CSS.
var rule = document.styleSheets[1].rules[4];
var iDoc = document.querySelector('iframe').contentDocument;
iDoc.styleSheets[0].insertRule(rule.cssText);
You can write small function that gets the CSS rule / all CSS rules that would affect the text area.
I cannot think of another way to do it without having some cycling/listening JavaScript. The real solution would be for browsers to provide a way to scale text as a function of the parent container and to also provide the same vmin/vmax type functionality.
JSFiddle:
https://jsfiddle.net/0jr7rrgm/3/
(click once to lock the red square to the mouse, and click again to release)
Most of the JavaScript in the fiddle is just my custom click-drag function.
Use CSS Variables
No one has mentioned CSS variables yet, and this approach worked best for me, so:
Let's say you've got a column on your page that is 100% of the width of a mobile user's screen, but has a max-width of 800px, so on desktop there's some space on either side of the column. Put this at the top of your page:
<script> document.documentElement.style.setProperty('--column-width', Math.min(window.innerWidth, 800)+'px'); </script>
And now you can use that variable (instead of the built-in vw unit) to set the size of your font. E.g.
p {
font-size: calc( var(--column-width) / 100 );
}
It's not a pure CSS approach, but it's pretty close.
Using vw, em & co. works for sure, but IMO it always needs a human's touch for fine-tuning.
Here's a script I just wrote based on #tnt-rox' answer that tries to automatize that human's touch:
$('#controller').click(function(){
$('h2').each(function(){
var
$el = $(this),
max = $el.get(0),
el = null
;
max =
max
? max.offsetWidth
: 320
;
$el.css({
'font-size': '1em',
'display': 'inline',
});
el = $el.get(0);
el.get_float = function(){
var
fs = 0
;
if (this.style && this.style.fontSize) {
fs = parseFloat(this.style.fontSize.replace(/([\d\.]+)em/g, '$1'));
}
return fs;
};
el.bigger = function(){
this.style.fontSize = (this.get_float() + 0.1) + 'em';
};
while (el.offsetWidth < max) {
el.bigger();
}
// Finishing touch.
$el.css({
'font-size': ((el.get_float() -0.1) +'em'),
'line-height': 'normal',
'display': '',
});
}); // end of (each)
}); // end of (font scaling test)
div {
width: 50%;
background-color: tomato;
font-family: 'Arial';
}
h2 {
white-space: nowrap;
}
h2:nth-child(2) {
font-style: italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="button" id="controller" value="Apply" />
<div>
<h2>Lorem ipsum dolor</h2>
<h2>Test String</h2>
<h2>Sweet Concatenation</h2>
<h2>Font Scaling</h2>
</div>
It basically reduces the font-size to 1em and then starts incrementing by 0.1 until it reaches maximum width.
JSFiddle
100% is relative to the base font size, which, if you haven't set it, would be the browser's user-agent default.
To get the effect you're after, I would use a piece of JavaScript code to adjust the base font size relative to the window dimensions.
Artistically, if you need to fit two or more lines of text within the same width regardless of their character count then you have nice options.
It's best to find a dynamical solution so whatever text is entered we end up with a nice display.
Let's see how we may approach.
var els = document.querySelectorAll(".divtext"),
refWidth = els[0].clientWidth,
refFontSize = parseFloat(window.getComputedStyle(els[0],null)
.getPropertyValue("font-size"));
els.forEach((el,i) => el.style.fontSize = refFontSize * refWidth / els[i].clientWidth + "px")
#container {
display: inline-block;
background-color: black;
padding: 0.6vw 1.2vw;
}
.divtext {
display: table;
color: white;
font-family: impact;
font-size: 4.5vw;
}
<div id="container">
<div class="divtext">THIS IS JUST AN</div>
<div class="divtext">EXAMPLE</div>
<div class="divtext">TO SHOW YOU WHAT</div>
<div class="divtext">YOU WANT</div>
</div>
All we do is to get the width (els[0].clientWidth) and the font size (parseFloat(window.getComputedStyle(els[0],null).getPropertyValue("font-size"))) of the first line as a reference and then just calculate the subsequent lines font size accordingly.
This web component changes the font size so the inner text width matches the container width. Check the demo.
You can use it like this:
<full-width-text>Lorem Ipsum</full-width-text>
You may be you looking for something like this:
http://jsfiddle.net/sijav/dGsC9/4/
http://fiddle.jshell.net/sijav/dGsC9/4/show/
I have used flowtype, and it's working great (however it's JavaScript and not a pure CSS solution):
$('body').flowtype({
minFont: 10,
maxFont: 40,
minimum: 500,
maximum: 1200,
fontRatio: 70
});
I've prepared a simple scale function using CSS transform instead of font-size. You can use it inside of any container, you don't have to set media queries, etc. :)
Blog post:
Full width CSS & JS scalable header
The code:
function scaleHeader() {
var scalable = document.querySelectorAll('.scale--js');
var margin = 10;
for (var i = 0; i < scalable.length; i++) {
var scalableContainer = scalable[i].parentNode;
scalable[i].style.transform = 'scale(1)';
var scalableContainerWidth = scalableContainer.offsetWidth - margin;
var scalableWidth = scalable[i].offsetWidth;
scalable[i].style.transform = 'scale(' + scalableContainerWidth / scalableWidth + ')';
scalableContainer.style.height = scalable[i].getBoundingClientRect().height + 'px';
}
}
Working demo:
https://codepen.io/maciejkorsan/pen/BWLryj
Inside your CSS, try adding this at the bottom changing the 320 pixels width for wherever your design starts breaking:
#media only screen and (max-width: 320px) {
body { font-size: 1em; }
}
Then give the font-size in "px" or "em" as you wish.
Try http://simplefocus.com/flowtype/. This is what I use for my sites, and it has worked perfectly.
My own solution, jQuery-based, works by gradually increasing the font size until the container gets a big increase in height (meaning it got a line break).
It's pretty simple, but works fairly well, and it is very easy to use. You don't have to know anything about the font being used, everything is taken care of by the browser.
You can play with it on http://jsfiddle.net/tubededentifrice/u5y15d0L/2/
The magic happens here:
var setMaxTextSize=function(jElement) {
// Get and set the font size into data for reuse upon resize
var fontSize=parseInt(jElement.data(quickFitFontSizeData)) || parseInt(jElement.css("font-size"));
jElement.data(quickFitFontSizeData, fontSize);
// Gradually increase font size until the element gets a big increase in height (i.e. line break)
var i = 0;
var previousHeight;
do
{
previousHeight=jElement.height();
jElement.css("font-size", "" + (++fontSize) + "px");
}
while(i++ < 300 && jElement.height()-previousHeight < fontSize/2)
// Finally, go back before the increase in height and set the element as resized by adding quickFitSetClass
fontSize -= 1;
jElement.addClass(quickFitSetClass).css("font-size", "" + fontSize + "px");
return fontSize;
};
My problem was similar, but related to scaling text within a heading. I tried Fit Font, but I needed to toggle the compressor to get any results, since it was solving a slightly different problem, as was Text Flow.
So I wrote my own little plugin that reduced the font size to fit the container, assuming you have overflow: hidden and white-space: nowrap so that even if reducing the font to the minimum doesn't allow showing the full heading, it just cuts off what it can show.
(function($) {
// Reduces the size of text in the element to fit the parent.
$.fn.reduceTextSize = function(options) {
options = $.extend({
minFontSize: 10
}, options);
function checkWidth(em) {
var $em = $(em);
var oldPosition = $em.css('position');
$em.css('position', 'absolute');
var width = $em.width();
$em.css('position', oldPosition);
return width;
}
return this.each(function(){
var $this = $(this);
var $parent = $this.parent();
var prevFontSize;
while (checkWidth($this) > $parent.width()) {
var currentFontSize = parseInt($this.css('font-size').replace('px', ''));
// Stop looping if min font size reached, or font size did not change last iteration.
if (isNaN(currentFontSize) || currentFontSize <= options.minFontSize ||
prevFontSize && prevFontSize == currentFontSize) {
break;
}
prevFontSize = currentFontSize;
$this.css('font-size', (currentFontSize - 1) + 'px');
}
});
};
})(jQuery);
Try to use the fitText plugin, because Viewport sizes isn't the solution of this problem.
Just add the library:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
And change font-size for correct by settings the coefficient of text:
$("#text_div").fitText(0.8);
You can set maximum and minimum values of text:
$("#text_div").fitText(0.8, { minFontSize: '12px', maxFontSize: '36px' });
Here is a pure CSS solution with the understanding that you admit breakpoints are necessary but also want text scaling:
I'm aware I can add breakpoints, but I really want the text to scale
as well as having extra breakpoints, otherwise....
Here is an approach using:
Custom properties
Media queries for breakpoints
clamp() (browser support in Feb 2022 is pretty good at 93%)
calc()
If one common scaling factor can be used to control ALL the text scaling within a container per screen max-width, all you need to do is scale a custom property per max-width, and apply this factor to 1 calculation.
A basic setup starts like this:
:root {
--scaling-factor: 1
}
.parent {
font-size: 30px
}
.largest {
font-size: clamp(60%, calc(var(--scaling-factor) * 100%), 100%);
}
.middle {
font-size: clamp(60%, calc(var(--scaling-factor) * 85%), 100%);
}
.smallest {
font-size: clamp(60%, calc(var(--scaling-factor) * 70%), 100%);
}
Then nest your media queries something like this (or whatever you need for your breakpoints):
#media (max-width: 1200px) {
:root {
--scaling-factor: 0.9
}
#media (max-width: 800px) {
:root {
--scaling-factor: 0.8
}
#media (max-width: 600px) {
:root {
--scaling-factor: 0.5 /* nope, because the font-size is floored at 60% thanks to clamp() */
}
}
}
}
This minimizes your media query markup.
Advantages
One custom property controls ALL scaling ... no need to add multiple declarations per media breakpoint
The use of clamp() sets a lower-limit on what the font-size should be, so you ensure your text is never too small (here the floor is 60% of the parent's font-size)
Please see this JSFiddle for a demo. Resize the window until at the smallest widths, the paragraphs are all the same font-size.
Always have your element with this attribute:
JavaScript: element.style.fontSize = "100%";
or
CSS: style = "font-size: 100%;"
When you go fullscreen, you should already have a scale variable calculated (scale > 1 or scale = 1). Then, on fullscreen:
document.body.style.fontSize = (scale * 100) + "%";
It works nicely with little code.
Take look at my code. It makes the font size smaller to fit whatever there.
But I think this doesn't lead to a good user experience
var containerWidth = $("#ui-id-2").width();
var items = $(".quickSearchAutocomplete .ui-menu-item");
var fontSize = 16;
items.each(function(){
// Displaying a value depends sometimes on your case. You may make it block or inline-table instead of inline-block or whatever value that make the div take overflow width.
$(this).css({"whiteSpace": "nowrap", "display": "inline-block"});
while ($(this).width() > containerWidth){
console.log("$(this).width()" + $(this).width() + "containerWidth" + containerWidth)
$(this).css("font-size", fontSize -= 0.5);
}
});
For dynamic text, this plugin is quite useful:
http://freqdec.github.io/slabText/
Simply add CSS:
.slabtexted .slabtext
{
display: -moz-inline-box;
display: inline-block;
white-space: nowrap;
}
.slabtextinactive .slabtext
{
display: inline;
white-space: normal;
font-size: 1em !important;
letter-spacing: inherit !important;
word-spacing: inherit !important;
*letter-spacing: normal !important;
*word-spacing: normal !important;
}
.slabtextdone .slabtext
{
display: block;
}
And the script:
$('#mydiv').slabText();
This worked for me:
I try to approximate font-size based on a width/height got from setting `font-size: 10px`. Basically, the idea is "if I have 20 pixels width and 11 pixels height with `font-size: 10px`, so what would it be the maximum font-size to math a container of 50 pixels width and 30 pixels height?"
The answer is a double proportion system:
{ 20:10=50:X, 11:10=30:Y } = { X= (10*50)/20, Y= (10*30)/11 }
Now X is a font-size that will match width, and Y is a font-size that will match height; take the smallest value
function getMaxFontSizeApprox(el){
var fontSize = 10;
var p = el.parentNode;
var parent_h = p.offsetHeight ? p.offsetHeight : p.style.pixelHeight;
if(!parent_h)
parent_h = 0;
var parent_w = p.offsetHeight ? p.offsetWidth : p.style.pixelWidth;
if(!parent_w)
parent_w = 0;
el.style.fontSize = fontSize + "px";
var el_h = el.offsetHeight ? el.offsetHeight : el.style.pixelHeight;
if(!el_h)
el_h = 0;
var el_w = el.offsetHeight ? el.offsetWidth : el.style.pixelWidth;
if(!el_w)
el_w = 0;
// 0.5 is the error on the measure that JavaScript does
// if the real measure had been 12.49 px => JavaScript would have said 12px
// so we think about the worst case when could have, we add 0.5 to
// compensate the round error
var fs1 = (fontSize*(parent_w + 0.5))/(el_w + 0.5);
var fs2 = (fontSize*(parent_h) + 0.5)/(el_h + 0.5);
fontSize = Math.floor(Math.min(fs1,fs2));
el.style.fontSize = fontSize + "px";
return fontSize;
}
NB: the argument of the function must be a span element or an element which is smaller than its parent, otherwise if children and parent have both the same width/height function will fail.
let textElement = document.getElementById('text1');
let parentElement = textElement.parentElement;
const parentClientHeight = parentElement.clientHeight;
const parentClientWidth = parentElement.clientWidth;
textElement.style.padding = "unset";
textElement.style.margin = "auto";
let fontSize = parentClientHeight;
let minFS = 3,
maxFS = fontSize;
while (fontSize != minFS) {
textElement.style.fontSize = `${fontSize}px`;
if (
parentElement.scrollHeight <= parentClientHeight &&
parentElement.scrollWidth <= parentClientWidth
) {
minFS = fontSize;
} else {
maxFS = fontSize;
}
fontSize = Math.floor((minFS + maxFS) / 2);
}
textElement.style.fontSize = `${minFS}px`;
<div style="height:200px; width:300px;">
<div id='text1'>
test
</div>
</div>
As a JavaScript fallback (or your sole solution), you can use my jQuery Scalem plugin, which lets you scale relative to the parent element (container) by passing the reference option.
In case it's helpful to anyone, most of the solutions in this thread were wrapping text into multiple lines, form e.
But then I found this, and it worked:
https://github.com/chunksnbits/jquery-quickfit
Example usage:
$('.someText').quickfit({max:50,tolerance:.4})

Is it possible to define font-size in terms of the width or height of the containing div? [duplicate]

I'm having a hard time getting my head around font scaling.
I currently have a website with a body font-size of 100%. 100% of what though? This seems to compute out at 16 pixels.
I was under the impression that 100% would somehow refer to the size of the browser window, but apparently not because it's always 16 pixels whether the window is resized down to a mobile width or full-blown widescreen desktop.
How can I make the text on my site scale in relation to its container? I tried using em, but this doesn't scale either.
My reasoning is that things like my menu become squished when you resize, so I need to reduce the px font-size of .menuItem among other elements in relation to the width of the container. (For example, in the menu on a large desktop, 22px works perfectly. Move down to tablet width and 16px is more appropriate.)
I'm aware I can add breakpoints, but I really want the text to scale as well as having extra breakpoints, otherwise, I'll end up with hundreds of breakpoints for every 100pixels decrease in width to control the text.
If the container is not the body, CSS Tricks covers all of your options in Fitting Text to a Container.
If the container is the body, what you are looking for is Viewport-percentage lengths:
The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly. However, when the value of overflow on the root element is auto, any scroll bars are assumed not to exist.
The values are:
vw (% of the viewport width)
vh (% of the viewport height)
vi (1% of the viewport size in the direction of the root element's inline axis)
vb (1% of the viewport size in the direction of the root element's block axis)
vmin (the smaller of vw or vh)
vmax (the larger or vw or vh)
1 v* is equal to 1% of the initial containing block.
Using it looks like this:
p {
font-size: 4vw;
}
As you can see, when the viewport width increases, so do the font-size, without needing to use media queries.
These values are a sizing unit, just like px or em, so they can be used to size other elements as well, such as width, margin, or padding.
Browser support is pretty good, but you'll likely need a fallback, such as:
p {
font-size: 16px;
font-size: 4vw;
}
Check out the support statistics: http://caniuse.com/#feat=viewport-units.
Also, check out CSS-Tricks for a broader look: Viewport Sized Typography
Here's a nice article about setting minimum/maximum sizes and exercising a bit more control over the sizes: Precise control over responsive typography
And here's an article about setting your size using calc() so that the text fills the viewport: http://codepen.io/CrocoDillon/pen/fBJxu
Also, please view this article, which uses a technique dubbed 'molten leading' to adjust the line-height as well. Molten Leading in CSS
But what if the container is not the viewport (body)?
This question is asked in a comment by Alex under 2507rkt3's answer.
That fact does not mean vw cannot be used to some extent to size for that container. Now to see any variation at all one has to be assuming that the container in some way is flexible in size. Whether through a direct percentage width or through being 100% minus margins. The point becomes "moot" if the container is always set to, let's say, 200px wide--then just set a font-size that works for that width.
Example 1
With a flexible width container, however, it must be realized that in some way the container is still being sized off the viewport. As such, it is a matter of adjusting a vw setting based off that percentage size difference to the viewport, which means taking into account the sizing of parent wrappers. Take this example:
div {
width: 50%;
border: 1px solid black;
margin: 20px;
font-size: 16px;
/* 100 = viewport width, as 1vw = 1/100th of that
So if the container is 50% of viewport (as here)
then factor that into how you want it to size.
Let's say you like 5vw if it were the whole width,
then for this container, size it at 2.5vw (5 * .5 [i.e. 50%])
*/
font-size: 2.5vw;
}
Assuming here the div is a child of the body, it is 50% of that 100% width, which is the viewport size in this basic case. Basically, you want to set a vw that is going to look good to you. As you can see in my comment in the above CSS content, you can "think" through that mathematically with respect to the full viewport size, but you don't need to do that. The text is going to "flex" with the container because the container is flexing with the viewport resizing. Here's an example of two differently sized containers.
Example 2
You can help ensure viewport sizing by forcing the calculation based off that. Consider this example:
html {width: 100%;} /* Force 'html' to be viewport width */
body {width: 150%; } /* Overflow the body */
div {
width: 50%;
border: 1px solid black;
margin: 20px;
font-size: 16px;
/* 100 = viewport width, as 1vw = 1/100th of that
Here, the body is 150% of viewport, but the container is 50%
of viewport, so both parents factor into how you want it to size.
Let's say you like 5vw if it were the whole width,
then for this container, size it at 3.75vw
(5 * 1.5 [i.e. 150%]) * .5 [i.e. 50%]
*/
font-size: 3.75vw;
}
The sizing is still based off viewport, but is in essence set up based off the container size itself.
Should the Size of the Container Change Dynamically...
If the sizing of the container element ended up changing dynamically its percentage relationship either via #media breakpoints or via JavaScript, then whatever the base "target" was would need recalculation to maintain the same "relationship" for text sizing.
Take example #1 above. If the div was switched to 25% width by either #media or JavaScript, then at the same time, the font-size would need to adjust in either the media query or by JavaScript to the new calculation of 5vw * .25 = 1.25. This would put the text size at the same size it would have been had the "width" of the original 50% container been reduced by half from viewport sizing, but has now been reduced due to a change in its own percentage calculation.
A Challenge
With the CSS calc() function in use, it would become difficult to adjust dynamically, as that function does not work for font-size purposes at this time. So you could not do a pure CSS adjustment if your width is changing on calc(). Of course, a minor adjustment of width for margins may not be enough to warrant any change in font-size, so it may not matter.
Solution with SVG:
.resizeme {
resize: both;
margin: 0;
padding: 0;
height: 75px;
width: 500px;
background-color: lightblue;
overflow: hidden;
}
<div class="resizeme">
<svg
width="100%"
height="100%"
viewBox="0 0 500 75"
preserveAspectRatio="xMinYMid meet"
style="background-color:green"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
>
<text
x="0"
y="75"
font-size="75"
fill="black"
>█Resize This█</text>
</svg>
</div>
Solution with SVG and text-wrapping using foreignObject:
.resizeme {
resize: both;
margin: 0;
padding: 0;
height: 200px;
width: 500px;
background-color: lightblue;
overflow: hidden;
}
<div class="resizeme">
<svg
width="100%"
height="100%"
viewBox="0 0 500 200"
preserveAspectRatio="xMinYMin meet"
>
<foreignObject width="100%" height="100%" xmlns="http://www.w3.org/1999/xhtml">
<div xmlns="http://www.w3.org/1999/xhtml" style="background-color:lightgreen;">
<h1>heading</h1>
<p>Resize the blue box.</p>
</div>
</foreignObject>
</svg>
</div>
In one of my projects I use a "mixture" between vw and vh to adjust the font size to my needs, for example:
font-size: calc(3vw + 3vh);
I know this doesn't answer the OP's question, but maybe it can be a solution to anyone else.
Pure-CSS solution with calc(), CSS units and math
This is precisely not what OP asks, but may make someone's day. This answer is not spoon-feedingly easy and needs some researching on the developer end.
I came finally to get a pure-CSS solution for this using calc() with different units. You will need some basic mathematical understanding of formulas to work out your expression for calc().
When I worked this out, I had to get a full-page-width responsive header with some padding few parents up in DOM. I'll use my values here, replace them with your own.
To mathematics
You will need:
Nicely adjusted ratio in some viewport. I used 320 pixels, thus I got 24 pixels high and 224 pixels wide, so the ratio is 9.333... or 28 / 3
The container width, I had padding: 3em and full width so this got to 100wv - 2 * 3em
X is the width of container, so replace it with your own expression or adjust the value to get full-page text. R is the ratio you will have. You can get it by adjusting the values in some viewport, inspecting element width and height and replacing them with your own values. Also, it is width / heigth ;)
x = 100vw - 2 * 3em = 100vw - 6em
r = 224px/24px = 9.333... = 28 / 3
y = x / r
= (100vw - 6em) / (28 / 3)
= (100vw - 6em) * 3 / 28
= (300vw - 18em) / 28
= (75vw - 4.5rem) / 7
And bang! It worked! I wrote
font-size: calc((75vw - 4.5rem) / 7)
to my header and it adjusted nicely in every viewport.
But how does it work?
We need some constants up here. 100vw means the full width of viewport, and my goal was to establish full-width header with some padding.
The ratio. Getting a width and height in one viewport got me a ratio to play with, and with ratio I know what the height should be in other viewport width. Calculating them with hand would take plenty of time and at least take lots of bandwidth, so it's not a good answer.
Conclusion
I wonder why no-one has figured this out and some people are even telling that this would be impossible to tinker with CSS. I don't like to use JavaScript in adjusting elements, so I don't accept JavaScript (and forget about jQuery) answers without digging more. All in all, it's good that this got figured out and this is one step to pure-CSS implementations in website design.
I apologize of any unusual convention in my text, I'm not native speaker in English and am also quite new to writing Stack Overflow answers.
It should also be noted that we have evil scrollbars in some browsers. For example, when using Firefox I noticed that 100vw means the full width of viewport, extending under scrollbar (where content cannot expand!), so the fullwidth text has to be margined carefully and preferably get tested with many browsers and devices.
There is a big philosophy for this issue.
The easiest thing to do would be to give a certain font-size to body (I recommend 10), and then all the other element would have their font in em or rem.
I'll give you an example to understand those units.
Em is always relative to its parent:
body{font-size: 10px;}
.menu{font-size: 2em;} /* That means 2*10 pixels = 20 pixels */
.menu li{font-size: 1.5em;} /* That means 1.5*20 pixels = 30 pixels */
Rem is always relative to body:
body{font-size: 10px;}
.menu{font-size: 2rem;} /* That means 2*10 pixels = 20 pixels */
.menu li{font-size: 1.5rem;} /* that means 1.5*10 pixels = 15 pixels */
And then you could create a script that would modify font-size relative to your container width.
But this isn't what I would recommend. Because in a 900 pixels width container for example you would have a p element with a 12 pixels font-size let's say. And on your idea that would become an 300 pixels wide container at 4 pixels font-size. There has to be a lower limit.
Other solutions would be with media queries, so that you could set font for different widths.
But the solutions that I would recommend is to use a JavaScript library that helps you with that. And fittext.js that I found so far.
Here is the function:
document.body.setScaledFont = function(f) {
var s = this.offsetWidth, fs = s * f;
this.style.fontSize = fs + '%';
return this
};
Then convert all your documents child element font sizes to em's or %.
Then add something like this to your code to set the base font size.
document.body.setScaledFont(0.35);
window.onresize = function() {
document.body.setScaledFont(0.35);
}
http://jsfiddle.net/0tpvccjt/
There is a way to do this without JavaScript!
You can use an inline SVG image. You can use CSS on an SVG if it is inline. You have to remember that using this method means your SVG image will respond to its container size.
Try using the following solution...
HTML
<div>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 360.96 358.98" >
<text>SAVE $500</text>
</svg>
</div>
CSS
div {
width: 50%; /* Set your container width */
height: 50%; /* Set your container height */
}
svg {
width: 100%;
height: auto;
}
text {
transform: translate(40px, 202px);
font-size: 62px;
fill: #000;
}
Example:
https://jsfiddle.net/k8L4xLLa/32/
Want something more flashy?
SVG images also allow you to do cool stuff with shapes and junk. Check out this great use case for scalable text...
https://jsfiddle.net/k8L4xLLa/14/
CSS Container Queries
A late-2022 addition to the CSS feature set makes scaling font size with containers straightforward.
Container queries come with a new set of CSS units cqw/cqh (container query width/height). To use them you need to set the container-type property on the parent element whose size you want to use. Minimal example:
<div>
<p>Lorem ipsum dolor sit amet</p>
</div>
<style>
div {
container-type: inline-size;
}
p {
font-size: 5cqw;
}
</style>
The font size will increase smoothly as the container grows. At 1000px container width, the p font size will be 1000px / 100 * 5 = 50px.
container-type can be size or inline-size. size tracks both height and width of the container which allows you to use both cqw and cqh.
Most of the time on the web, heights are calculated based on content and you only specify the width. To save the browser some work, you'll generally want to set container-type: inline-size; so the browser only tracks the inline dimension which is usually width (unless you set writing-mode to vertical).
Browser support for container queries has grown rapidly in the 2nd half of 2022 and currently stands at 75% (2023-01-01).
This may not be super practical, but if you want a font to be a direct function of the parent, without having any JavaScript that listens/loops (interval) to read the size of the div/page, there is a way to do it. Iframes.
Anything within the iframe will consider the size of the iframe as the size of the viewport. So the trick is to just make an iframe whose width is the maximum width you want your text to be, and whose height is equal to the maximum height * the particular text's aspect ratio.
Setting aside the limitation that viewport units can't also come along side parent units for text (as in, having the % size behave like everyone else), viewport units do provide a very powerful tool: being able to get the minimum/maximum dimension. You can't do that anywhere else - you can't say...make the height of this div be the width of the parent * something.
That being said, the trick is to use vmin, and to set the iframe size so that [fraction] * total height is a good font size when the height is the limiting dimension, and [fraction] * total width when the width is the limiting dimension. This is why the height has to be a product of the width and the aspect ratio.
For my particular example, you have
.main iframe{
position: absolute;
top: 50%;
left: 50%;
width: 100%;
height: calc(3.5 * 100%);
background: rgba(0, 0, 0, 0);
border-style: none;
transform: translate3d(-50%, -50%, 0);
}
The small annoyance with this method is that you have to manually set the CSS of the iframe. If you attach the whole CSS file, that would take up a lot of bandwidth for many text areas. So, what I do is attach the rule that I want directly from my CSS.
var rule = document.styleSheets[1].rules[4];
var iDoc = document.querySelector('iframe').contentDocument;
iDoc.styleSheets[0].insertRule(rule.cssText);
You can write small function that gets the CSS rule / all CSS rules that would affect the text area.
I cannot think of another way to do it without having some cycling/listening JavaScript. The real solution would be for browsers to provide a way to scale text as a function of the parent container and to also provide the same vmin/vmax type functionality.
JSFiddle:
https://jsfiddle.net/0jr7rrgm/3/
(click once to lock the red square to the mouse, and click again to release)
Most of the JavaScript in the fiddle is just my custom click-drag function.
Using vw, em & co. works for sure, but IMO it always needs a human's touch for fine-tuning.
Here's a script I just wrote based on #tnt-rox' answer that tries to automatize that human's touch:
$('#controller').click(function(){
$('h2').each(function(){
var
$el = $(this),
max = $el.get(0),
el = null
;
max =
max
? max.offsetWidth
: 320
;
$el.css({
'font-size': '1em',
'display': 'inline',
});
el = $el.get(0);
el.get_float = function(){
var
fs = 0
;
if (this.style && this.style.fontSize) {
fs = parseFloat(this.style.fontSize.replace(/([\d\.]+)em/g, '$1'));
}
return fs;
};
el.bigger = function(){
this.style.fontSize = (this.get_float() + 0.1) + 'em';
};
while (el.offsetWidth < max) {
el.bigger();
}
// Finishing touch.
$el.css({
'font-size': ((el.get_float() -0.1) +'em'),
'line-height': 'normal',
'display': '',
});
}); // end of (each)
}); // end of (font scaling test)
div {
width: 50%;
background-color: tomato;
font-family: 'Arial';
}
h2 {
white-space: nowrap;
}
h2:nth-child(2) {
font-style: italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="button" id="controller" value="Apply" />
<div>
<h2>Lorem ipsum dolor</h2>
<h2>Test String</h2>
<h2>Sweet Concatenation</h2>
<h2>Font Scaling</h2>
</div>
It basically reduces the font-size to 1em and then starts incrementing by 0.1 until it reaches maximum width.
JSFiddle
Use CSS Variables
No one has mentioned CSS variables yet, and this approach worked best for me, so:
Let's say you've got a column on your page that is 100% of the width of a mobile user's screen, but has a max-width of 800px, so on desktop there's some space on either side of the column. Put this at the top of your page:
<script> document.documentElement.style.setProperty('--column-width', Math.min(window.innerWidth, 800)+'px'); </script>
And now you can use that variable (instead of the built-in vw unit) to set the size of your font. E.g.
p {
font-size: calc( var(--column-width) / 100 );
}
It's not a pure CSS approach, but it's pretty close.
100% is relative to the base font size, which, if you haven't set it, would be the browser's user-agent default.
To get the effect you're after, I would use a piece of JavaScript code to adjust the base font size relative to the window dimensions.
Artistically, if you need to fit two or more lines of text within the same width regardless of their character count then you have nice options.
It's best to find a dynamical solution so whatever text is entered we end up with a nice display.
Let's see how we may approach.
var els = document.querySelectorAll(".divtext"),
refWidth = els[0].clientWidth,
refFontSize = parseFloat(window.getComputedStyle(els[0],null)
.getPropertyValue("font-size"));
els.forEach((el,i) => el.style.fontSize = refFontSize * refWidth / els[i].clientWidth + "px")
#container {
display: inline-block;
background-color: black;
padding: 0.6vw 1.2vw;
}
.divtext {
display: table;
color: white;
font-family: impact;
font-size: 4.5vw;
}
<div id="container">
<div class="divtext">THIS IS JUST AN</div>
<div class="divtext">EXAMPLE</div>
<div class="divtext">TO SHOW YOU WHAT</div>
<div class="divtext">YOU WANT</div>
</div>
All we do is to get the width (els[0].clientWidth) and the font size (parseFloat(window.getComputedStyle(els[0],null).getPropertyValue("font-size"))) of the first line as a reference and then just calculate the subsequent lines font size accordingly.
This web component changes the font size so the inner text width matches the container width. Check the demo.
You can use it like this:
<full-width-text>Lorem Ipsum</full-width-text>
You may be you looking for something like this:
http://jsfiddle.net/sijav/dGsC9/4/
http://fiddle.jshell.net/sijav/dGsC9/4/show/
I have used flowtype, and it's working great (however it's JavaScript and not a pure CSS solution):
$('body').flowtype({
minFont: 10,
maxFont: 40,
minimum: 500,
maximum: 1200,
fontRatio: 70
});
I've prepared a simple scale function using CSS transform instead of font-size. You can use it inside of any container, you don't have to set media queries, etc. :)
Blog post:
Full width CSS & JS scalable header
The code:
function scaleHeader() {
var scalable = document.querySelectorAll('.scale--js');
var margin = 10;
for (var i = 0; i < scalable.length; i++) {
var scalableContainer = scalable[i].parentNode;
scalable[i].style.transform = 'scale(1)';
var scalableContainerWidth = scalableContainer.offsetWidth - margin;
var scalableWidth = scalable[i].offsetWidth;
scalable[i].style.transform = 'scale(' + scalableContainerWidth / scalableWidth + ')';
scalableContainer.style.height = scalable[i].getBoundingClientRect().height + 'px';
}
}
Working demo:
https://codepen.io/maciejkorsan/pen/BWLryj
Inside your CSS, try adding this at the bottom changing the 320 pixels width for wherever your design starts breaking:
#media only screen and (max-width: 320px) {
body { font-size: 1em; }
}
Then give the font-size in "px" or "em" as you wish.
Try http://simplefocus.com/flowtype/. This is what I use for my sites, and it has worked perfectly.
My own solution, jQuery-based, works by gradually increasing the font size until the container gets a big increase in height (meaning it got a line break).
It's pretty simple, but works fairly well, and it is very easy to use. You don't have to know anything about the font being used, everything is taken care of by the browser.
You can play with it on http://jsfiddle.net/tubededentifrice/u5y15d0L/2/
The magic happens here:
var setMaxTextSize=function(jElement) {
// Get and set the font size into data for reuse upon resize
var fontSize=parseInt(jElement.data(quickFitFontSizeData)) || parseInt(jElement.css("font-size"));
jElement.data(quickFitFontSizeData, fontSize);
// Gradually increase font size until the element gets a big increase in height (i.e. line break)
var i = 0;
var previousHeight;
do
{
previousHeight=jElement.height();
jElement.css("font-size", "" + (++fontSize) + "px");
}
while(i++ < 300 && jElement.height()-previousHeight < fontSize/2)
// Finally, go back before the increase in height and set the element as resized by adding quickFitSetClass
fontSize -= 1;
jElement.addClass(quickFitSetClass).css("font-size", "" + fontSize + "px");
return fontSize;
};
My problem was similar, but related to scaling text within a heading. I tried Fit Font, but I needed to toggle the compressor to get any results, since it was solving a slightly different problem, as was Text Flow.
So I wrote my own little plugin that reduced the font size to fit the container, assuming you have overflow: hidden and white-space: nowrap so that even if reducing the font to the minimum doesn't allow showing the full heading, it just cuts off what it can show.
(function($) {
// Reduces the size of text in the element to fit the parent.
$.fn.reduceTextSize = function(options) {
options = $.extend({
minFontSize: 10
}, options);
function checkWidth(em) {
var $em = $(em);
var oldPosition = $em.css('position');
$em.css('position', 'absolute');
var width = $em.width();
$em.css('position', oldPosition);
return width;
}
return this.each(function(){
var $this = $(this);
var $parent = $this.parent();
var prevFontSize;
while (checkWidth($this) > $parent.width()) {
var currentFontSize = parseInt($this.css('font-size').replace('px', ''));
// Stop looping if min font size reached, or font size did not change last iteration.
if (isNaN(currentFontSize) || currentFontSize <= options.minFontSize ||
prevFontSize && prevFontSize == currentFontSize) {
break;
}
prevFontSize = currentFontSize;
$this.css('font-size', (currentFontSize - 1) + 'px');
}
});
};
})(jQuery);
Try to use the fitText plugin, because Viewport sizes isn't the solution of this problem.
Just add the library:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
And change font-size for correct by settings the coefficient of text:
$("#text_div").fitText(0.8);
You can set maximum and minimum values of text:
$("#text_div").fitText(0.8, { minFontSize: '12px', maxFontSize: '36px' });
Here is a pure CSS solution with the understanding that you admit breakpoints are necessary but also want text scaling:
I'm aware I can add breakpoints, but I really want the text to scale
as well as having extra breakpoints, otherwise....
Here is an approach using:
Custom properties
Media queries for breakpoints
clamp() (browser support in Feb 2022 is pretty good at 93%)
calc()
If one common scaling factor can be used to control ALL the text scaling within a container per screen max-width, all you need to do is scale a custom property per max-width, and apply this factor to 1 calculation.
A basic setup starts like this:
:root {
--scaling-factor: 1
}
.parent {
font-size: 30px
}
.largest {
font-size: clamp(60%, calc(var(--scaling-factor) * 100%), 100%);
}
.middle {
font-size: clamp(60%, calc(var(--scaling-factor) * 85%), 100%);
}
.smallest {
font-size: clamp(60%, calc(var(--scaling-factor) * 70%), 100%);
}
Then nest your media queries something like this (or whatever you need for your breakpoints):
#media (max-width: 1200px) {
:root {
--scaling-factor: 0.9
}
#media (max-width: 800px) {
:root {
--scaling-factor: 0.8
}
#media (max-width: 600px) {
:root {
--scaling-factor: 0.5 /* nope, because the font-size is floored at 60% thanks to clamp() */
}
}
}
}
This minimizes your media query markup.
Advantages
One custom property controls ALL scaling ... no need to add multiple declarations per media breakpoint
The use of clamp() sets a lower-limit on what the font-size should be, so you ensure your text is never too small (here the floor is 60% of the parent's font-size)
Please see this JSFiddle for a demo. Resize the window until at the smallest widths, the paragraphs are all the same font-size.
Always have your element with this attribute:
JavaScript: element.style.fontSize = "100%";
or
CSS: style = "font-size: 100%;"
When you go fullscreen, you should already have a scale variable calculated (scale > 1 or scale = 1). Then, on fullscreen:
document.body.style.fontSize = (scale * 100) + "%";
It works nicely with little code.
Take look at my code. It makes the font size smaller to fit whatever there.
But I think this doesn't lead to a good user experience
var containerWidth = $("#ui-id-2").width();
var items = $(".quickSearchAutocomplete .ui-menu-item");
var fontSize = 16;
items.each(function(){
// Displaying a value depends sometimes on your case. You may make it block or inline-table instead of inline-block or whatever value that make the div take overflow width.
$(this).css({"whiteSpace": "nowrap", "display": "inline-block"});
while ($(this).width() > containerWidth){
console.log("$(this).width()" + $(this).width() + "containerWidth" + containerWidth)
$(this).css("font-size", fontSize -= 0.5);
}
});
For dynamic text, this plugin is quite useful:
http://freqdec.github.io/slabText/
Simply add CSS:
.slabtexted .slabtext
{
display: -moz-inline-box;
display: inline-block;
white-space: nowrap;
}
.slabtextinactive .slabtext
{
display: inline;
white-space: normal;
font-size: 1em !important;
letter-spacing: inherit !important;
word-spacing: inherit !important;
*letter-spacing: normal !important;
*word-spacing: normal !important;
}
.slabtextdone .slabtext
{
display: block;
}
And the script:
$('#mydiv').slabText();
This worked for me:
I try to approximate font-size based on a width/height got from setting `font-size: 10px`. Basically, the idea is "if I have 20 pixels width and 11 pixels height with `font-size: 10px`, so what would it be the maximum font-size to math a container of 50 pixels width and 30 pixels height?"
The answer is a double proportion system:
{ 20:10=50:X, 11:10=30:Y } = { X= (10*50)/20, Y= (10*30)/11 }
Now X is a font-size that will match width, and Y is a font-size that will match height; take the smallest value
function getMaxFontSizeApprox(el){
var fontSize = 10;
var p = el.parentNode;
var parent_h = p.offsetHeight ? p.offsetHeight : p.style.pixelHeight;
if(!parent_h)
parent_h = 0;
var parent_w = p.offsetHeight ? p.offsetWidth : p.style.pixelWidth;
if(!parent_w)
parent_w = 0;
el.style.fontSize = fontSize + "px";
var el_h = el.offsetHeight ? el.offsetHeight : el.style.pixelHeight;
if(!el_h)
el_h = 0;
var el_w = el.offsetHeight ? el.offsetWidth : el.style.pixelWidth;
if(!el_w)
el_w = 0;
// 0.5 is the error on the measure that JavaScript does
// if the real measure had been 12.49 px => JavaScript would have said 12px
// so we think about the worst case when could have, we add 0.5 to
// compensate the round error
var fs1 = (fontSize*(parent_w + 0.5))/(el_w + 0.5);
var fs2 = (fontSize*(parent_h) + 0.5)/(el_h + 0.5);
fontSize = Math.floor(Math.min(fs1,fs2));
el.style.fontSize = fontSize + "px";
return fontSize;
}
NB: the argument of the function must be a span element or an element which is smaller than its parent, otherwise if children and parent have both the same width/height function will fail.
let textElement = document.getElementById('text1');
let parentElement = textElement.parentElement;
const parentClientHeight = parentElement.clientHeight;
const parentClientWidth = parentElement.clientWidth;
textElement.style.padding = "unset";
textElement.style.margin = "auto";
let fontSize = parentClientHeight;
let minFS = 3,
maxFS = fontSize;
while (fontSize != minFS) {
textElement.style.fontSize = `${fontSize}px`;
if (
parentElement.scrollHeight <= parentClientHeight &&
parentElement.scrollWidth <= parentClientWidth
) {
minFS = fontSize;
} else {
maxFS = fontSize;
}
fontSize = Math.floor((minFS + maxFS) / 2);
}
textElement.style.fontSize = `${minFS}px`;
<div style="height:200px; width:300px;">
<div id='text1'>
test
</div>
</div>
As a JavaScript fallback (or your sole solution), you can use my jQuery Scalem plugin, which lets you scale relative to the parent element (container) by passing the reference option.
In case it's helpful to anyone, most of the solutions in this thread were wrapping text into multiple lines, form e.
But then I found this, and it worked:
https://github.com/chunksnbits/jquery-quickfit
Example usage:
$('.someText').quickfit({max:50,tolerance:.4})