将div设置为内容宽度,最大宽度为

时间:2016-03-24 03:06:37

标签: html css

我有一个包含浮动左图像然后是文本的div。它执行以下操作。



.outer-div {
  max-width: 95%;
  background-color: yellow;
  display: inline-block;
}
.image {
  float: left;
}

<div class="outer-div">
  <img class="image" src="http://www.w3schools.com/images/colorpicker.png">
  <div class="test">Here is some text that I want the outer div to size to without line-breaking.</div>
</div>
&#13;
&#13;
&#13;

注意,它如何根据文本单独创建外部div大小,然后插入浮动图像,导致文本换行。我希望外部div宽度是浮动图像的宽度+文本的宽度,然后只有当它达到最大宽度95%时才会换行。

编辑:一旦第一行到达页面边缘,我也不希望所有文本都在图像下方。但是,当有很多文本时,我确实希望它包装在图像下面。

4 个答案:

答案 0 :(得分:2)

您可以使用flexbox来实现这一目标,请参阅以下示例:

<强> jsFiddle

.outer-div {
  display: inline-flex;
  align-items: flex-start;
  max-width: 95%;
  background-color: yellow;
}
<div class="outer-div">
  <img class="image" src="http://www.w3schools.com/images/colorpicker.png">
  <div class="test">Here is some text that I want the outer div to size to without line-breaking.</div>
</div>

答案 1 :(得分:1)

在测试DIV上使用“inline-block”应将其设置为在另一个块旁边对齐。将以下内容添加到CSS部分,您应该很好。

.test {
display: inline-block;
}

如果您希望它在顶部而不是底部居中,则可以添加以下内容:

vertical-align: top;

希望这会帮助你!祝你好运!

答案 2 :(得分:0)

我的一个朋友在乱搞并找到答案。答案是使用文本将图像浮动到测试div中。无需对CSS进行任何更改。

以下示例:

.outer-div {
  max-width: 95%;
  background-color: yellow;
  display: inline-block;
}
.image {
  float: left;
}
<div class="outer-div">
  <div class="test"><img class="image" src="http://www.w3schools.com/images/colorpicker.png">Here is some text that I want the outer div to size to without line-breaking.</div>
</div>

这是一个包含大量文本的示例,用于验证它是否包含在图像下。

.outer-div {
  max-width: 95%;
  background-color: yellow;
  display: inline-block;
}
.image {
  float: left;
}
<div class="outer-div">
  <div class="test"><img class="image" src="http://www.w3schools.com/images/colorpicker.png">Here is some text that I want the outer div to size to without line-breaking. And here is a ton more text to add to the post to show that it properly wraps around the image even with a ton of text.Here is some text that I want the outer div to size to without line-breaking. And here is a ton more text to add to the post to show that it properly wraps around the image even with a ton of text.Here is some text that I want the outer div to size to without line-breaking. And here is a ton more text to add to the post to show that it properly wraps around the image even with a ton of text.Here is some text that I want the outer div to size to without line-breaking. And here is a ton more text to add to the post to show that it properly wraps around the image even with a ton of text.</div>
</div>

感谢所有提供答案的人。你的答案肯定会帮助我将来的事情,所以赞成你们所有人。 :)

答案 3 :(得分:0)

尝试将其添加到您的代码中

width: fit-content;