限制第一个孩子的元素宽度

时间:2014-10-02 09:42:04

标签: html css css3 flexbox

我有一个非常棘手的情况,我只想用CSS解决。

基本上,这个想法非常简单,我有一个.item div,其中包含imgp。 图片不能高于320px,因此我添加了max-height: 320px,为了保持宽高比,它还有width: auto

到目前为止一直很好......

棘手的部分是:.item div,必须与img

具有相同的宽度

但是因为p包含的文字比图片更宽,所以它不起作用。

我在这里创建了一个JS Bin:http://jsbin.com/liyeratuzadu/1/edit 在这个JS Bin中,在CSS选项卡中查找以下代码:

.item p {
  /*width: 100px;*/
}

取消注释该行以查看所需结果。

提示:我不想在p上有固定的宽度,因为我认为这不是很敏感。

1 个答案:

答案 0 :(得分:2)

解决方案#1 - 显示:表方法

1)在项目

上设置display:table

2)给它一个非常小的宽度说width: 1px

.item {
  display: table;
  width: 1px;
  background: tomato;
}

<强> Updated JsBin

&#13;
&#13;
body {
  text-align: center;
}
.item {
  display: table;
  width: 1px;
  background: tomato;
}
.item img {
  display: block;
  /* removes spacing from inline-block (default) */
  width: auto;
  max-height: 320px;
  margin: 0 auto 0;
}
&#13;
<div class="item">
  <img src="http://dummyimage.com/500x700/">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea impedit labore atque illo autem inventore totam, voluptatem tempore repudiandae.</p>
</div>
&#13;
&#13;
&#13;

解决方案#2 - 利用内在大小(不兼容IE)

.item {
  width: -moz-min-content; 
  width: -webkit-min-content; 
  width: min-content;
  background: tomato;
}

&#13;
&#13;
.item {
  width: -moz-min-content;
  width: -webkit-min-content;
  width: min-content;
  background: tomato;
}
.item img {
  display: block;
  /* removes spacing from inline-block (default) */
  width: auto;
  max-height: 320px;
  margin: 0 auto 0;
}
&#13;
<div class="item">
  <img src="http://dummyimage.com/500x700/">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea impedit labore atque illo autem inventore totam, voluptatem tempore repudiandae.</p>
</div>
&#13;
&#13;
&#13;

1)Browser support is quite good(IE除外)

2)Here's an article解释min-content属性

相关问题