css – 我应该使用max-device-width还是max-width?

前端之家收集整理的这篇文章主要介绍了css – 我应该使用max-device-width还是max-width?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > What is the difference between max-device-width and max-width for mobile web?8个答案使用CSS媒体查询,您可以使用max-device-width定位设备宽度(如iPhone或Android设备)和/或以页面宽度为目标的最大宽度。

如果您使用max-device-width,当您更改桌面上浏览器窗口的大小时,CSS将不会更改,因为您的桌面不会更改大小。

如果您使用max-width,当您更改桌面上浏览器窗口的大小时,您可能会看到面向移动的样式,例如触摸友好的元素和菜单以及类似的东西。

定位特定的浏览器(和设备?)现在已被弃用,您应该对您的定位有点不了解。这是否也适用于媒体查询

你为什么要针对另一个?哪一个是推荐的?

这是我在生产网站上使用的媒体查询的示例:

@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (min-device-height: 480px) and (max-device-height: 640px) {  
    /* Change a menu to fit the screen better,etc... */
}

我倾向于同时使用max-device-width和max-width。

解决方法

TL; DR

如果您要制作自适应网站,则可能需要使用min-width / max-width而不是min-device-width / max-device-width,以便定位更广泛的屏幕尺寸。

请记住在< head>中指定一个viewport meta tag。部分:

<Meta name="viewport" content="width=device-width,initial-scale=1">

说明

由于需要考虑几个因素(缩放,像素密度,屏幕分辨率和大小,设备方向,宽高比等),给定设备可能具有的所有不同的可能的屏幕分辨率和像素密度。在这种情况下,像素实际上被称为“optical reference unit”而不是物理硬件像素。

幸运的是,您可以在< head>部分,以便控制浏览器视口的宽度和缩放比例。如果此标记内容值为width = device-width,则屏幕的宽度将为match the device independent pixels,并确保所有不同的设备都能缩放和一致运行。

<Meta name="viewport" content="width=device-width,initial-scale=1">

在媒体查询方面,您可能希望使用max-width而不是max-device-width,因为max-width将定位到视口(当前浏览器窗口),而max-device-width将定位设备的实际全屏尺寸/分辨率。

换句话说,如果您使用的是最大设备宽度,则在调整桌面浏览器大小时将不会看到不同的媒体查询,因为与最大宽度不同,仅考虑设备的实际全屏尺寸;而不是浏览器窗口的当前大小。

如果你想创建一个自适应布局,这会产生巨大的不同,因为网站在调整浏览器大小时不会响应。此外,如果您使用的是最大设备宽度,即使调整浏览器窗口大小以符合所述较小屏幕尺寸,您使用的媒体查询也不会应用于桌面设备。

这个article on Google Developers高度阻止max-device-width的使用:

07006

It is also possible to create queries based on *-device-width; though this practice is strongly discouraged.

The difference is subtle but very important: min-width is based on the size of the browser window,whereas min-device-width is based on the size of the screen. Unfortunately some browsers,including the legacy Android browser may not report the device width properly and instead report the screen size in device pixels instead of the expected viewport width.

In addition,using *-device-width can prevent content from adapting on desktops or other devices that allow windows to be resized because the query is based on the actual device size,not the size of the browser window.

进一步阅读:

> Quirksmode.org – A pixel is not a pixel is not a pixel
> W3.org CSS3 Media Queries Documentation
> Google Developers – Web Fundamentals – Viewport
> Google Developers – Web Fundamentals – Responsive CSS media queries
> MDN – Using the viewport meta tag to control layout on mobile browsers

原文链接:https://www.f2er.com/css/222769.html

猜你在找的CSS相关文章