Reputation: 531
I currently have the following code:
<p style="font-size: 20em; max-width: 100vw;">Hellooo!</p>
As you can see, the font-size is too large for the screen. I want the text to stay at its set size until it overflows the screen (My attempt is the max-width
, but that is not working). Is there a way to fix this with CSS and HTML only?
Since I want the text size to be 20em
unless it overflows the screen, I do not want to set the width
to any value other than 20em
.
Thanks!
Upvotes: 7
Views: 10300
Reputation: 1567
You can use the following npm library:
https://www.npmjs.com/package/@gmwallet/app-common
Import the dependency:
import { fontSizer } from "@gmwallet/app-common";
Five an id to your component:
<p style="font-size: 20em; max-width: 100vw; id="myid">Hellooo!</p>
Use it:
const result = fontSizer("fname");
This is for automatically responsive DOM element, so it could be more useful with dynamic data. For example if your text is not static, but let's say that it is contained in a variable called "helloVar", you could put it in a watch statement:
watch: {
helloVar: {
handler(newValue) {
const result = fontSizer('myid');
if (result === 0) {
console.log("Font size adapted to input width.");
}
},
immediate: true, // To trigger the handler on component mount
},
},
Upvotes: 0
Reputation: 1239
With a known font, you can also use a good fallback.
p {
font-size: min(20em, 28vw);
/* Next rules are only be have a clearer preview */
line-height: 1;
text-align: center;
padding: 0;
margin: 0;
}
<p>Hellooo!</p>
Upvotes: 3
Reputation: 2445
A combination of media-queries
and variable units(vw
) will solve!
.mytext{
}
@media screen and (min-width: 1200px) {/*adjust*/
.mytext {
font-size: 20em;
}
}
@media screen and (max-width: 1200px) {/*adjust*/
.mytext {
font-size: 20vw;
}
}
<p style="" class="mytext">Hellooo!</p>
Upvotes: 0
Reputation: 499
You can use the CSS calc function and change the font size based on the vw value.
<p style="font-size:calc(25vw)">Hellooo!</p>
Upvotes: 1
Reputation: 4078
If you know the length of text, you can use the CSS min() function with your em sizing and the maximum size dependent on the viewport. Otherwise you are going to need a polyfill.
<p style="font-size: min(20em, 12vw); max-width: 100vw;">Hellooo!</p>
Upvotes: 1