我可以根据自己的大小动态调整元素的内容吗?

时间:2013-03-13 18:49:27

标签: html css media-queries

我已经非常熟练地使用媒体查询动态更改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 个答案:

答案 0 :(得分: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