>我有这样的元素
<div id="container">
<pre>
Hai,
This is first line
This is second line
This is last line
</pre>
</div>
我想在更改主div的高度和宽度时以正确的对齐方式动态更改字体大小。
你可以
试试: 你可以使用vw
#container{
font-size: 7vw;
}
<div id="container">
<pre>
Hai,
This is first line
This is second line
This is last line
</pre>
</div>
我将使用视口百分比或媒体查询:
#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>
如果您正在寻找JavaScript解决方案,这篇文章可能会对您有所帮助:如何检测DIV的维度变化?它们解释了如何正确聆听元素大小的变化
这是小提琴: https://jsfiddle.net/e420fkL7/3/
库(此处为存储库)用于检测元素尺寸的变化。由于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>
这是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();