根据屏幕大小切换CSS类

Fat*_*ers 25 css

CSS nob在这里......

我正在寻找一个响应式框架,并想象我将如何完成不同的任务.

根据屏幕的大小,它们将类添加到body标签中,例如:

.PhoneVisible,.DesktopVisible等...

他们还有类来链接到按钮:

.btn,小按钮,按钮,大按钮

我很困惑你会如何改变你的CSS.IE之类的东西:

<a href="#" class="MyButtonOptions">XXXX</>

.PhoneVisible .MyButtonOptions { btn small-button }
.TabletVisible  .MyButtonOptions { btn  med-button }
.DesktopVisible .MyButtonOptions { btn large-button }
Run Code Online (Sandbox Code Playgroud)

您是否必须单独设置不同的选项?

ie .PhoneVisible .MyButtonOptions {height:30px; } ???

所有建议赞赏!

Nej*_*ian 47

CSS媒体查询绝对是最佳选择.

您可以根据浏览器大小,像素密度等轻松分离CSS.

以下是CSS-Tricks的示例列表.

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
    /* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
    /* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
    /* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
    /* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
    /* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
    /* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
    /* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
    /* Styles */
}

/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
    /* Styles */
}
Run Code Online (Sandbox Code Playgroud)

  • 这是切换样式的好建议,但不是切换类的建议 (5认同)

Fel*_*sso 12

看看这个https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries.

另一种方法是将resize事件附加一些"切换代码".

像这样:http://jsfiddle.net/s5dvb/

HTML

<div id="body" class="limit400">
    <h1>Hey :D</h1>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

.limit400 h1 { font-size:10px; }
.limit1200 h1 { font-size:50px; }
Run Code Online (Sandbox Code Playgroud)

JS

$(window).on('resize', function() {
    if($(window).height() > 400) {
        $('#body').addClass('limit1200');
        $('#body').removeClass('limit400');
    }else{
        $('#body').addClass('limit400');
        $('#body').removeClass('limit1200');
    }
})
Run Code Online (Sandbox Code Playgroud)

关于框架,请尝试http://purecss.io/http://getbootstrap.com/

希望能帮助到你.