大多数HTML元素被定义为块级元素或内联元素。块级元素在浏览器显示时通常会以新行来开始,例如<h1>、<p>、<table>、<ul>等;内联元素通常不会以新行开始,例如<td>、<a>、<img>等。
1.<div>和<span>
HTML可以通过<div>和<span>将元素组合起来。<div>元素是块级元素,它可用于组合其他HTML元素的容器,没有特殊含义;<span>元素是内联元素,可用作文本的容器,也没有特殊的含义。
<div>元素作用:
- 与CSS一同使用,对大的内容块设置样式属性
- 文档布局,取代了老式的表格定义布局的方法
<span>元素作用:
- 可用作文本的容器
- 与CSS一同使用时,<span>元素可用于为部分文本设置样式属性
2.HTML布局
利用DIV进行页面布局:
<body>
<div id="container" style="width: 500px">
<div id="header" style="background-color: #FFA600;">
<h1 style="margin-bottom: 0;">网页标题</h1>
</div>
<div id="left" style="height: 200px;width: 100px;background-color:#FFD900;float: left;">
<b>HTML</b><br/>
<b>CSS</b><br/>
<b>JavaScript</b>
</div>
<div id="right" style="height: 200px;width: 400px;background-color:#00FFFF;float: left;">内容就在这里</div>
<div id="footer" style="height: 18px;background-color: #FFA600;clear:both;text-align: center;">footer</div>
</div>
</body>
运行结果:
利用表格进行布局:
<body>
<table width=500px cellspacing="0">
<tr style="background-color: #FFA600">
<td colspan="2"><h1 style="margin-bottom: 0;margin-top: 0;text-align: center;">网页标题</h1></td>
</tr>
<tr style="height: 200px">
<td style="background-color: #FFD900;width: 100px;vertical-align: top;">
<b>HTML</b><br/>
<b>CSS</b><br/>
<b>JavaScript</b><br/>
</td>
<td style="background-color: #00FFFF;width: 400px;vertical-align: top;">内容就在这里</td>
</tr>
<tr>
<td colspan="2" style="height: 18px;background-color: #FFA600;text-align: center;">footer</td>
</tr>
</table>
</body>
运行结果:
我们可以看到利用DIV进行分块页面布局和利用表格进行页面布局可以达到同样的效果,但是DIV+CSS是专门用来进行页面布局的方法,而表格虽然也能达到同样的效果,但是不建议用来进行布局,毕竟表格不是布局工具。