[英]change font size of <pre> tag dynamically based on the parent width and height changing
I have elements like 我有像
<div id="container"> <pre> Hai, This is first line This is second line This is last line </pre> </div>
I want to change the font size of the 我想更改字体大小 dynamically with the correct alignment when i change the height and width of the main div. 当我更改主div的高度和宽度时,以正确的对齐方式动态地动态调整。
I'll go either with Viewport percentage or Media queries : 我将使用视口百分比或媒体查询:
#container1 > pre { font-size: 3vw; } #container2 > pre { font-size: 20px; } @media (max-width: 500px) { #container2 > pre { font-size: 10px; } }
<div id="container1"> <pre>Using vw</pre> </div> <div id="container2"> <pre>Using media queries</pre> </div>
If you are looking for a JavaScript solution, this post may help you : How to detect DIV's dimension changed? 如果您正在寻找JavaScript解决方案,则此文章可能对您有所帮助: 如何检测DIV的尺寸已更改? They explain how to listen properly to element size changes 他们解释了如何正确聆听元素大小的变化
You may try: You can use vw
您可以尝试: 可以使用vw
#container{ font-size: 7vw; }
<div id="container"> <pre> Hai, This is first line This is second line This is last line </pre> </div>
Here is the fiddle: https://jsfiddle.net/e420fkL7/3/ 这是小提琴: https : //jsfiddle.net/e420fkL7/3/
A library ( Repo Here ) is used to detect changes in the element's dimensions. 库( 此处为Repo )用于检测元素尺寸的变化。 Since CSS cannot be used to detect changes on an element's width, JS was necessary. 由于无法使用CSS来检测元素宽度的变化,因此需要JS。
<script src="https://cdn.rawgit.com/legomushroom/resize/master/dist/any-resize-event.min.js"></script>
<div id="container">
<pre id="resizeThis">
Hai,
This is first line
This is second line
This is last line
</pre>
</div>
Here's the JS: 这是JS:
// This example uses an external library for checking resize of the element.
var container = document.getElementById("container");
container.addEventListener("onresize", setFontSize);
function setFontSize(){
var width = container.offsetWidth; // Get the width of the div
var minSize = 11; // Minimum font size
// Here, we make any operation on the width/height and check if it is less that the minimum font size, or any other conditions.
var toSet = (width * 0.03) < minSize ? minSize : (width * 0.03);
document.getElementById("resizeThis").style.fontSize = toSet + "px";
}
setFontSize();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.