Css - 具有分解css iphone 4及更高版本的目标

时间:2017-03-22 15:08:54

标签: ios css iphone css3

我希望将css课程定位到iphone 4,5,6和6 plus 我使用了这个article,但想知道我是否无法将其分解。事实上在我看来,前两个设备目标(最小宽度320 /最大最大宽度480px和568px,我可以使用最大的最大宽度并将它们融合成一个声明。感觉我的代码不够干净而且相当重复的。

这是我目前的代码:

.example {
  @media 
    //iphone 4
    (min-device-width: 320px) 
    and (max-device-width: 480px)
    and (-webkit-min-device-pixel-ratio: 2)
    and (orientation: portrait),
    //iphone 5
    (min-device-width: 320px) 
    and (max-device-width: 568px)
    and (-webkit-min-device-pixel-ratio: 2)
    and (orientation: portrait),
    //iphone 6
    (min-device-width: 375px) 
    and (max-device-width: 667px) 
    and (-webkit-min-device-pixel-ratio: 2)
    and (orientation: portrait),
    //iphone 6+
    (min-device-width: 414px) 
    and (max-device-width: 736px) 
    and (-webkit-min-device-pixel-ratio: 3)
    and (orientation: portrait) {
      color: yellow;
 }
}

我可以将aobve代码转换/分解为以下内容吗?

.example {
  @media 
    //mix iphone 4 and 5 
    (min-device-width: 320px) 
    and (max-device-width: 568pxpx)
    and (-webkit-min-device-pixel-ratio: 2)
    and (orientation: portrait),
    //iphone 6    
    (min-device-width: 375px) 
    and (max-device-width: 667px) 
    and (-webkit-min-device-pixel-ratio: 2)
    and (orientation: portrait),
    //iphone 6+
    (min-device-width: 414px) 
    and (max-device-width: 736px) 
    and (-webkit-min-device-pixel-ratio: 3)
    and (orientation: portrait) {
      color: red
 }
}

这也意味着一些Android设备,例如the Samsung Galaxy 3与iphone 4(320px)具有相同的宽度,还会有我的班级'示例'应用的红色?

2 个答案:

答案 0 :(得分:1)

您的两个代码示例都适用于符合要求的任何手机。

(min-device-width: 320px) and (max-device-width: 568pxpx)
and (-webkit-min-device-pixel-ratio: 2)
and (orientation: portrait),`

我不相信您可以以任何方式执行特定于设备的CSS,但您可以尝试使用javascript获取设备的操作系统。

      navigator.userAgent.match(/iPhone/i)

这篇文章详细介绍了它们的使用article。据我所知,这种方法不是未来的证据,因为稍后可能会为iPhone更改userAgent字段。

答案 1 :(得分:1)

由于单独使用CSS安全地找到目标设备并不容易,head script标记中的此脚本可能有助于检查用户代理和设备特定的测量

如果函数通过,则会向iPhone456标记添加一个类html,您可以在CSS中使用该标记来定位这些iPhone模型上的特定元素。

注意,您可能需要调整正则表达式,但解决方案将为您提供良好的开端



/* rules for iPhone 4,5,6 */
.iPhone456 div.test {
  color: red;
}

<head>
  <script>
    (function(d,s) {
      /* Set html class if iPhone 4,5,6 */
      if (!!navigator.userAgent.match(/iPhone/i)) {
        var w = s.availWidth, h = s.availHeight;
        if (
          (w === 320 && (h === 480 || h === 568)) ||
          (w === 375 && h === 667) ||
          (w === 414 && h === 736)
        ) {
          d.classList.add('iPhone456');
        }
      }
    })(document.documentElement,screen);
  </script>
</head>
<body>

<div class="test">Should be red on iPhone 4,5,6</div>

</body>
&#13;
&#13;
&#13;