让img元素决定容器的宽度

时间:2017-07-20 00:26:22

标签: css

我正在尝试使图像分辨率宽度决定容器的宽度。诀窍是当p元素比图像宽时,整个容器会伸展。我想要它做的是p元素尊重图像的宽度,并且永远不会拉伸容器宽度比图像更宽。我不想设置固定的宽度。这是一个演示:

#outer, #inner{
  border-width: 1px;
  border-style: solid;
  box-sizing: border-box;
  padding: 5px;
  text-align: center;
}
#outer {
  border-color red;
}
#inner { border-color: red; display:inline-block; }
img{max-width:100%;}
.fixed {
  width:300px; /*This is what i'm trying to avoid*/
}
<!DOCTYPE html>
<html>
  <head>
    <title>containers, img, p test</title>
  </head>

  <body>
    <div id="outer">
      <div id="inner">
        <img src="http://i67.tinypic.com/24yy8hv.jpg" />
        <p>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc felis dui, varius in ligula id, ultricies rutrum lorem. Mauris felis mauris, pretium in leo ut, convallis tincidunt libero. Proin vel ultrices diam, nec rutrum purus.
        </p>
      </div>
    </div>
    <div id="outer">
      <div id="inner" class="fixed">
        <img src="http://i67.tinypic.com/24yy8hv.jpg" />
        <p>
          This is how the first one is supposed to look. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc felis dui, varius in ligula id, ultricies rutrum lorem. Mauris felis mauris, pretium in leo ut, convallis tincidunt libero. Proin vel ultrices diam, nec rutrum purus.
        </p>
      </div>
    </div>
  </body>

</html>

1 个答案:

答案 0 :(得分:1)

将CSS更改为内联块意味着元素会随着图像的大小而增加。

我为id img添加了inline-block,告诉你它是如何工作的。

#outer, #inner, #img {
  border-width: 1px;
  border-style: solid;
  box-sizing: border-box;
  padding: 5px;
  text-align: center;
}
#outer {
  border-color red;
}
#inner { border-color: red; display:inline-block; }
#img { border-color: blue;display:inline-block;}
img{max-width:100%;}
.fixed {
  width:300px; /*This is what i'm trying to avoid*/
}
<!DOCTYPE html>
<html>
  <head>
    <title>containers, img, p test</title>
  </head>

  <body>
    <div id="outer">
      <div id="inner">
        <div id="img">
          <img src="http://i67.tinypic.com/24yy8hv.jpg" />
        </div>
        <p>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc felis dui, varius in ligula id, ultricies rutrum lorem. Mauris felis mauris, pretium in leo ut, convallis tincidunt libero. Proin vel ultrices diam, nec rutrum purus.
        </p>
      </div>
    </div>
    <div id="outer">
      <div id="inner" class="fixed">
        <div id="img">
          <img src="http://i67.tinypic.com/24yy8hv.jpg" />
        </div>
        <p>
          This is how the fist one is supposed to look. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc felis dui, varius in ligula id, ultricies rutrum lorem. Mauris felis mauris, pretium in leo ut, convallis tincidunt libero. Proin vel ultrices diam, nec rutrum purus.
        </p>
      </div>
    </div>
  </body>

</html>

希望这就是你所追求的。