Mobile website font sizing and wrapping

2019-09-02 11:41发布

问题:

I have a simple static website with a couple lines of text in it.

It will be accessed only from mobile devices, and I want that the font size for the text will be 1/3rd of the screen's height and lines to word wrap based on the screens width.

can it be done using CSS & HTML only? if so how?

Thanks

回答1:

The simple answer is to programmatically serve a stylesheet based on the mobile device. You can do this in your CSS file with :

@media screen and (max-device-width: 480px) {
  font-size: 160px; /* 1/3 max screen height */
}

Alternately, you could use javascript to calculate the width and height of the viewport then set the style dynamically.

window.onload = function() {
  var viewportwidth;
  var viewportheight;

  if (typeof window.innerWidth != 'undefined') {
      viewportwidth = window.innerWidth,
      viewportheight = window.innerHeight
  } else if (typeof document.documentElement != 'undefined'
    && typeof document.documentElement.clientWidth !=
    'undefined' && document.documentElement.clientWidth != 0) {
      viewportwidth = document.documentElement.clientWidth,
      viewportheight = document.documentElement.clientHeight
  } else {
      viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
      viewportheight = document.getElementsByTagName('body')[0].clientHeight
  }
  document.body.style.fontSize = viewportheight / 3;
}

Set wordwrapping in CSS with white-space: normal and, if desired, word-wrap:break-word