我正在处理一个包含大量文字的页面,我想要包含一个图像。问题是img比段落高。有谁知道如何使img 100%的容器?
.container {
width: 40%;
margin: 0 auto;
background: #000000;
color: #ffffff;
padding: 5px;
}
img {
float: right;
}

<body>
<p class="container">
<img src="http://via.placeholder.com/200x250"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras ullamcorper interdum risus eget ultrices. Morbi placerat ante nec accumsan tempus. Donec aliquam ex lectus, quis dignissim lacus tempor sit
amet. Proin varius dui sit amet enim semper, sit amet pharetra metus convallis. Cras at velit mauris. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi dignissim elit turpis, vel pretium leo rhoncus ac. Nunc
egestas arcu non nisi volutpat sagittis. Phasellus porttitor sollicitudin tellus, vel egestas nibh ultrices nec.
</p>
</body>
&#13;
答案 0 :(得分:3)
问题是float
获取标准流的图像otu,因此您需要实现Clearfix:
<强> 1。在CSS中创建clearfix类:
添加以下CSS(注意:这适用于IE8及更高版本。如果您需要支持旧浏览器,请查看上面的链接。)
.clearfix:after {
content: "";
display: table;
clear: both;
}
<强> 2。将clearfix应用于HTML:
将clearfix类添加到包含图像的div,即<p class="container clearfix">
工作演示:
注意: 我的容器宽度为100%,以便您可以看到效果 - 否则在小的CodeSnippet窗口中,文字不短足以导致您描述的问题。
.container {
width: 100%;
margin: 0 auto;
background: #000000;
color: #ffffff;
padding: 5px;
}
img {
float: right;
}
.clearfix:after {
content: "";
display: table;
clear: both;
}
<body>
<p class="container clearfix">
<img src="http://via.placeholder.com/200x250"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras ullamcorper interdum risus eget ultrices. Morbi placerat ante nec accumsan tempus. Donec aliquam ex lectus, quis dignissim lacus tempor sit
amet. Proin varius dui sit amet enim semper, sit amet pharetra metus convallis. Cras at velit mauris. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi dignissim elit turpis, vel pretium leo rhoncus ac. Nunc
egestas arcu non nisi volutpat sagittis. Phasellus porttitor sollicitudin tellus, vel egestas nibh ultrices nec.
</p>
</body>