2013-03-13 74 views
1

我已经习惯于使用媒体查询来动态更改DOM元素ad-hoc。不过,据我所知,这些只能检测窗口/设备宽度/高度,而不是单个DOM元素。我希望能够制作一个CSS,它将根据该元素的大小重新排列和调整元素内容的大小。例如:我可以根据自己的尺寸动态调整元素的内容大小吗?

╒══════════════════════════════╕ 
│Browser Window    │ 
├──────────────────────────────┤ 
│ ┌──────────────────────────┐ │ 
│ │.resizingParent   │ │ 
│ │┌──────┐ Some caption text│ │ 
│ ││ IMG │ directly relating│ │ 
│ ││  │ to the image. │ │ 
│ │└──────┘     │ │ 
│ └──────────────────────────┘ │ 
│        │ 
└──────────────────────────────┘ 
╒══════════════════════════════╕ 
│Browser Window    │ 
├──────────────────────────────┤ 
│ ┌───────────────┐   │ 
│ │.resizingParent│   │ 
│ │┌─────────────┐│   │ 
│ ││    ││   │ 
│ ││ I M G ││   │ 
│ ││    ││   │ 
│ ││    ││   │ 
│ │└─────────────┘│   │ 
│ │Some caption │   │ 
│ │directly  │   │ 
│ │relating to the│   │ 
│ │image.   │   │ 
│ └───────────────┘   │ 
│        │ 
└──────────────────────────────┘ 

我希望的解决方案是为使用媒体查询,如下面的(无效)代码一样简单:

<STYLE> 
.resizingParent>IMG { 
    display: inline-block; 
    width: 25%; 
} 

.resizingParent(max-width:10em)>IMG { 
    display: block; 
    width: 100%; 
} 
</STYLE> 

<DIV CLASS=".resizingParent"> 
    .resizingParent 
    <IMG SRC="IMG.png" ALT="IMG"/> 
    Some caption text directly relating to the image 
</DIV> 

回答

1

不幸的是,媒体查询不工作那样。 CSS中有许多可自然响应的选项(即,视图更改大小时,它们不需要重新格式化媒体查询),具体取决于您需要完成的工作类型。对于您的特定问题,Flexbox是最合适的。

http://codepen.io/cimmanon/pen/Azone

figure { 
    display: -webkit-flexbox; 
    display: -ms-flexbox; 
    display: -webkit-flex; 
    -webkit-flex-wrap: wrap; 
    -ms-flex-wrap: wrap; 
    flex-wrap: wrap; 
    border: 1px solid; 
} 
@supports (flex-wrap: wrap) { 
    figure { 
    display: flex; 
    } 
} 

figure div { 
    -webkit-flex: 1 1; 
    -ms-flex: 1 1; 
    flex: 1 1; 
    margin: 1em; 
    text-align: center; 
} 

figure figcaption { 
    margin: 1em; 
    -webkit-flex: 10 1 20em; 
    -ms-flex: 10 1 20em; 
    flex: 10 1 20em; 
} 

的HTML:

<figure> 
    <div><!-- this div is mostly here to prevent our image from getting distorted --> 
    <img src="http://placehold.it/200x200" /> 
    </div> 

    <figcaption>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus porta elit vel ante hendrerit facilisis. Curabitur aliquam sollicitudin diam, id posuere elit consectetur nec. Vestibulum quam dolor, feugiat in posuere a, posuere imperdiet tellus. Mauris sed ligula vitae urna consequat aliquet. Curabitur pellentesque consectetur ornare. Pellentesque vel euismod odio. Nulla tempus pharetra nulla. In justo dolor, sollicitudin nec commodo sit amet, adipiscing eget lectus. Phasellus velit enim, tempus et lobortis eget, rhoncus nec dolor.</figcaption> 
</figure> 

因为我们要求的柔性物品包裹,浏览器支持目前仅限于Chrome浏览器,Opera和IE10。 http://caniuse.com/#feat=flexbox

+0

我一直在收集*自然响应的各种演示*在这里:http://codepen.io/collection/LfoGq – cimmanon 2013-03-13 19:59:52

+0

最大的问题是图像不能以我需要的方式更改大小.. 。 不管怎么说,还是要谢谢你。 – Supuhstar 2013-03-13 23:46:48

+0

我已经更新了演示以删除div,以便图像调整大小。 – cimmanon 2013-03-13 23:58:00

相关问题