优化小屏幕需要CSS媒体查询?

时间:2013-01-13 04:25:39

标签: css media-queries

我没有接触过很多CSS媒体查询;我基本上是通过实验学习的。我正在尝试优化我的网站,以便在所有设备上都很好看。我希望它使用特定的CSS文件,如果浏览器宽度很大(桌面设备,包括Retina显示),一个不同的CSS文件,如果它是一个平板电脑(iPad或其他,包括Retina),和一个不同的CSS文件的小屏幕(iPhone或其他,包括Retina)。我目前的设置包括在下面,并且是他们的结果。

<link rel="stylesheet" type="text/css" href="stylesheets/prevhome.css" /> <!--Desktop -->
<link rel="stylesheet" type="text/css" media="screen and (max-device-width : 1024px), screen and (-webkit-min-device-pixel-ratio: 2)" href="stylesheets/tablet.css" /> <!-- Tablet -->
<link rel="stylesheet" type="text/css" media="screen and (max-device-width: 640px), screen and (-webkit-min-device-pixel-ratio: 2)" href="stylesheets/phone.css" /> <!-- Phone -->

这适用于台式电脑,但Retina显示器MacBook Pro使用的是Phone CSS文件而不是桌面文件。 iPad显示平板电脑优化版本很棒,但Retina显示屏iPad使用Phone优化的CSS文件。 iPhone使用Phone CSS文件显示页面很棒,而Retina显示器iPhone也显示它很棒。我不知道我的网站在其他设备上的外观,因为我只能使用Apple设备进行测试。

所以,我的CSS链接显然设置不正确。我怎样才能正确设置它?除Retina显示器外,我不想瞄准任何特定设备。 Windows平板电脑应该使用平板电脑CSS文件,而不仅仅是iPad。这可以通过3个CSS链接和3个文件完成,一个用于桌面(大于1024像素?),一个用于平板电脑(小于1024像素),一个用于手机(小于640像素)?或者我必须做这些链接,然后另外为每个Retina设备,rMBP,iPad和iPhone创建一个链接?甚至创建3个以上的CSS文件?

2 个答案:

答案 0 :(得分:0)

您无需检测Retina显示,只需检测device-width

<link rel="stylesheet" type="text/css" href="stylesheets/prevhome.css" /> <!--Desktop -->
<link rel="stylesheet" type="text/css" media="screen and (device-width : 1024px)" href="stylesheets/tablet.css" /> <!-- Tablet -->
<link rel="stylesheet" type="text/css" media="screen and (device-width: 640px)" href="stylesheets/phone.css" /> <!-- Phone -->

出于网络性能原因,所有这一切都可以使用单个CSS文件完成,其中包含@media (...) { selector1 { property: value; } }个媒体规则块,而不是条件加载1到3个文件。

答案 1 :(得分:0)

你的原始CSS链接的问题是你有两个条件(用逗号表示交替)但你没有在第二个提供任何宽度条件 -

<link rel="stylesheet" type="text/css" href="stylesheets/prevhome.css" /> <!--Desktop -->
<link rel="stylesheet" type="text/css" media="screen and (max-device-width : 1024px), screen and (max-device-width : 1024px) and (-webkit-min-device-pixel-ratio: 2)" href="stylesheets/tablet.css" /> <!-- Tablet -->
<link rel="stylesheet" type="text/css" media="screen and (max-device-width: 640px), screen and (max-device-width: 640px) and (-webkit-min-device-pixel-ratio: 2)" href="stylesheets/phone.css" /> <!-- Phone -->

psuedo代码中的原始链接可以写成 -

“屏幕最大宽度为1024px 屏幕,最小设备像素比率为2”

这就是为什么视网膜MacBook正在加载手机和平板电脑的风格。

当然,由于您没有为较高像素密度的情况加载特定/不同的样式表,因此原始链接可以写成 -

<link rel="stylesheet" type="text/css" href="stylesheets/prevhome.css" /> <!--Desktop -->
<link rel="stylesheet" type="text/css" media="screen and (max-device-width : 1024px)" href="stylesheets/tablet.css" /> <!-- Tablet -->
<link rel="stylesheet" type="text/css" media="screen and (max-device-width: 640px)" href="stylesheets/phone.css" /> <!-- Phone -->

这在功能上是等效的。

相关问题