正如 Jasper de Vries 所提到的,我会将 img 设置为 display:block。由于内联元素的边距具有不可预测的结果。我还将 p 标签设置为 display:block。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JS Bin</title>
<style type="text/css">
div {
border: 1px solid red;
margin: 20px 0;
width: 200px;
}
p {
background: #EEE;
border-right: 1px solid green;
margin: 0;
margin-right: 20px;
padding-left: 30px;
display:block
}
img {
background: pink;
float: left;
display:block;
margin-left: -30px;
padding: 5px 0;
}
.nf {
float: none;
}
.abs {
position: absolute;
}
.hightlight {
background: rgba(255,255,0,0.2);
}
</style>
</head>
<body>
<h2>No Float</h2>
<div>
<p>
<img class="nf" src="http://static.jsbin.com/images/favicon.png" alt="This make it W3C compliant">
no sea takimata <span class="hightlight">sanctus estestest</span> Lorem ipsum dolor sit amet.
</p>
</div>
<h2>Float Left</h2>
<div>
<p>
<img src="http://static.jsbin.com/images/favicon.png" alt="This make it W3C compliant">
no sea takimata <span class="hightlight">sanctus estestest</span> Lorem ipsum dolor sit amet.
</p>
</div>
<h2>Position Absolute</h2>
<div>
<p>
<img class="abs fn" src="http://static.jsbin.com/images/favicon.png" alt="This make it W3C compliant">
no sea takimata <span class="hightlight">sanctus estestest</span> Lorem ipsum dolor sit amet.
</p>
</div>
</body>
</html>
此代码已通过 W3C 最新标准的验证。将代码复制并粘贴到验证器中以进行确认。
W3C 验证器(按输入)