我目前正在学习CSS,并且正在做实验,偶然发现了输出中的这种差异。 这是代码:
<html>
<body>
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">
<style>
.red-text {
color: red;
}
h2 {
font-family: Lobster, monospace;
}
p {
font-size: 16px;
font-family: monospace;
}
.smaller-image {
width: 100px;
}
.thick-green-border {
border-width: 10px;
border-color: green;
border-style: solid;
}
</style>
<h2 class="red-text">CatPhotoApp</h2>
<main>
<p class="red-text">Click here to view more <a href="#">cat photos</a>.
</p>
<a href="#"><div class="thick-green-border"><img class="smaller-image"
src="https://s3.amazonaws.com/freecodecamp/relaxing-cat.jpg" alt="A cute orange cat lying on
its back."></div></a>
</main>
</body>
</html>
但是,如果我更改此行:
<a href="#"><div class="thick-green-border"><img class="smaller-image"
src="https://s3.amazonaws.com/freecodecamp/relaxing-cat.jpg" alt="A cute orange cat lying on
its back."></div></a>
对此(只需将div替换为span):
<a href="#"><span class="thick-green-border"><img class="smaller-image"
src="https://s3.amazonaws.com/freecodecamp/relaxing-cat.jpg" alt="A cute orange cat lying on
its back."></span></a>
所以有人可以解释一下代码中发生了什么吗?
答案 0 :(得分:3)
<div>
标签是一个块级元素,因此它占用了整个块。但是<span>
标签是内联元素。
<div>0000000<div>111111</div>222222</div>
<span>0000000<span>111111</span>222222</span>
检查此示例以进行澄清。
如果我添加display:block
以使其跨越,则其行为就像一个块。所以它需要全宽度
span{display:block;border:1px solid green}
<span>0000000<span>111111</span>222222</span>
答案 1 :(得分:2)
关于display
风格
div
默认为display:block
:width:100%
→原因border
属于所有width
span
默认为display: inline
,这意味着只需要width
→border
需要width
的原因span
在此处了解更多信息:https://www.w3schools.com/cssref/pr_class_display.asp 看到这里:
div,span{
background-color:red;
}
<div>I take 100% of width the prove for it is background-color</div>
<span>I take width as my content prove for it is background-color</span>
答案 2 :(得分:0)
<div>
和<span>
之间的基本区别在于,<div>
占据了可用宽度的100%,而<span>
则占据了里面的元素。我们也可以说<div>
是block
元素,而<span>
是inline
。元素