【问题标题】:How do I get responsive CSS to fit the viewport when switching between portrait and landscape?在纵向和横向之间切换时,如何获得响应式 CSS 以适应视口?
【发布时间】:2014-06-10 00:52:48
【问题描述】:

这是我的目标:我想要纵向模式的移动设备的移动样式,以及横向模式的非移动样式。

这是我所做的:我设置了媒体查询以提供最小宽度为 35em 的移动样式,并添加了一个视口元标记,上面写着“meta name="viewport" content="width=设备宽度,初始比例=1“”。移动/纵向 CSS 为 100% 宽,非移动/横向 CSS 为 980 像素宽。

这是我的问题:当我将移动设备切换到纵向模式时,非移动页面不适合视口,我必须放大才能查看整个页面。我希望非移动设备最初适合视口而不进行缩放。

到目前为止我已经尝试过:尝试了我能想到的视口元标记的所有变体,在 CSS 中添加了“html, body {width: 100%;}”。有什么建议吗?

【问题讨论】:

  • 把你的代码粘贴到这里或者摆弄它对我们来说很容易。

标签: html css responsive-design viewport landscape-portrait


【解决方案1】:

据我了解,您需要纵向和横向的不同视口设置。这是可能的,但请彻底测试,因为有怪癖(对不起,没有引号,这是来自个人经验)。

确保您已设置默认视口元标记,并为其指定一个 id。喜欢:

<meta name="viewport" id="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1">

然后添加一点 Javascript 来检测方向的变化并设置正确的视口模式。比如:

window.addEventListener('orientationchange', doOnOrientationChange);

function doOnOrientationChange()
{
  var bPortrait = document.documentElement.clientWidth < document.documentElement.clientHeight;
  if(bPortrait)
  {      
    document.getElementById("viewport").setAttribute("content","width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1", minimum-scale=1");
  }
  else
  {
    document.getElementById("viewport").setAttribute("content","width=900px, user-scalable=yes, maximum-scale=2, minimum-scale=0.25");
  }
}

请注意,横向的视口宽度设置为 900 像素。请根据您的网站宽度进行调整。您可能还想将此功能添加到您的文档加载事件列表中,以防有人已经将他的设备置于横向模式;-)

为了检测方向变化,我建议你阅读这篇文章: http://davidwalsh.name/orientation-change

然后使用媒体查询添加样式表。 由于我猜这两者非常不同,我建议使用两个文件(也许第三个用于常规设置):

<link rel='stylesheet' media='screen and (orientation:portrait)' href='portrait.css' />
<link rel='stylesheet' media='screen and (orientation:landscape)' href=landscape.css' />

但@APAD1 的建议当然也有效。

【讨论】:

    【解决方案2】:

    您可以像这样根据设备方向设置媒体查询:

    /* Portrait */
    @media screen and (orientation:portrait) {
        /* Portrait styles */
    }
    /* Landscape */
    @media screen and (orientation:landscape) {
        /* Landscape styles */
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多