如何根据移动设备更改CSS?

4th*_*ace 9 css mobile responsive-design

在以下示例中,我只想显示一个div,具体取决于设备.

我熟悉如何使用@media覆盖CSS类但不熟悉如何执行条件.

<style type="text/css">
   @media (max-width : 770px) {
     ...
   }

  @media (max-width : 320px) {
   ...
  }
  //do I need another for the desktop?
</style>

//if desktop
<div style="width: 400px; float: left;">
    this is desktop
    <a href="somepage.html"><img src="aLargeImage.png"/></a>
</div>

//if mobile
<div style="width: 200px; float: left;">
    this is mobile
    <a href="somepage.html">just text</a>
</div>
Run Code Online (Sandbox Code Playgroud)

有什么建议?

4th*_*ace 15

这是一个如何在没有javascript的情况下有条件地完成的示例:

//CSS
.visibledevice {display:none;}
.visibledesktop {display:display;}

@media (max-width : 320px) {
    .visibledevice {display:block;}
    .visibledesktop {display:none;}
}

//in the page
<div class="visibledesktop">this displays for desktop and tablet</div>

<div class="visibledevice">this displays for mobile</div>
Run Code Online (Sandbox Code Playgroud)


小智 7

嗯,我认为更容易创建2个或更多的CSS文件,并通过基于设备的JavaScript加载它们.在onload函数中有类似的东西:

var cssPath = "standard.css";
if (navigator.platform == "iPad")
    cssPath = "iPad.css";

var fileref = document.createElement("link");

fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", cssPath);

document.getElementsByTagName("head")[0].appendChild(fileref);
Run Code Online (Sandbox Code Playgroud)

更短,更易读的css文件易于交换.

  • 我想避免使用 JavaScript。 (2认同)

Phi*_*vid 6

如何进行条件 css 媒体查询:

@media only screen and (width : 1024px) and (orientation : landscape) {    
    .selector1 { width:960px; }
}
Run Code Online (Sandbox Code Playgroud)