如何在CSS中写媒体查询? [英] How to write a media query in CSS?

查看:201
本文介绍了如何在CSS中写媒体查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在以下情况下编写不同的样式



设备宽度大于设备高度

  / * Landscape * / 
@media屏幕和(orientation:landscape){
.bg img {
height:auto;
width:100%;
}
}

设备高度大于设备宽度

  / * Portrait * / 
@media屏幕和(orientation:portrait){
。 bg img {
height:100%;
width:auto;
}
}

方向在调整浏览器大小的某些阶段完美工作。



如何编写正确的CSS?



是否可以使用CSS?



编辑:



我在附加图片调整浏览器大小时的效果

解决方案

您可以访问浏览器< a href =http://en.wikipedia.org/wiki/Aspect_ratio_%28image%29 =nofollow>纵横比与这些媒体查询功能: aspect-ratio | min-aspect-ratio | max-aspect-ratio 。有关详情,请查看MDN上的 CSS媒体查询



Portrait的纵横比大于 1:1 ,横向较小。要验证,我从 JSFiddle 更改了颜色,当您从横向切换到

  / *景观即宽视口)* / 
@media屏幕和(最小宽高比:1/1){
.bg img {
height:auto;
width:100%;
}
}

/ *肖像(即窄视口)* /
@media屏幕和(最大宽高比:1/1){
.bg img {
height:100%;
width:auto;
}
}

更新:是文档流的一部分,并且不会填充视口,除非正文也用 body {height:100%;} 填充视口,如< a href =http://jsfiddle.net/ansonhoyt/JPpzb/1/ =nofollow> JSFiddle 。



尝试 img {position:absolute;} 将图像拉出流程,因此它的尺寸不受身体尺寸的限制。请参见 JSFiddle


I need to write different styles in following cases

Device width greater than device height

/* Landscape */
@media screen and (orientation:landscape) {
    .bg img {
        height: auto;
        width: 100%;
    }
}

Device height greater than device width

/* Portrait */
@media screen and (orientation:portrait) {
    .bg img {
        height: 100%;
        width: auto;
    }
}

Orientation doesn't work perfectly in some stages on resizing the browser.

How to write correct CSS?

Is it possible to do so with CSS?

EDIT :

I am attaching image how it looks on resizing the browser

解决方案

You have access to the browser's aspect ratio with these media query features: aspect-ratio | min-aspect-ratio | max-aspect-ratio. For more info, check out CSS media queries on MDN.

Portrait has an aspect ratio greater than 1:1 and landscape is less. To verify, I made a JSFiddle that changes color when you switch from "landscape" to "portrait".

Try this:

/* Landscape (i.e. wide viewport) */
@media screen and (min-aspect-ratio: 1/1) {
    .bg img {
        height: auto;
        width: 100%;
    }
}

/* Portrait (i.e. narrow viewport) */
@media screen and (max-aspect-ratio: 1/1) {
    .bg img {
        height: 100%;
        width: auto;
    }
}

Update: The image is part of the flow of the document, and won't fill the viewport unless the body also fills the viewport with body {height: 100%;}, as in this JSFiddle.

Try img {position: absolute;} to pull the image out of the flow, so it's dimensions aren't constrained by the body's size. See JSFiddle.

这篇关于如何在CSS中写媒体查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆