更改<pre> tag dynamically based on the parent width and height changing

时间:2017-10-12 09:36:28

标签: javascript html css3

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.

3 个答案:

答案 0 :(得分:0)

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? They explain how to listen properly to element size changes

答案 1 :(得分:0)

You may try: You can use vw

#container{
  font-size: 7vw;
}
<div id="container">
  <pre>
    Hai,
    This is first line
    This is second line
    This is last line
  </pre>
</div>

答案 2 :(得分:0)

Here is the fiddle: https://jsfiddle.net/e420fkL7/3/

A library (Repo Here) is used to detect changes in the element's dimensions. Since CSS cannot be used to detect changes on an element's width, JS was necessary.

<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:

// 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();