css笔记12:块元素和行内元素

1.概念:

行内元素:又叫内联元素,内联元素只能容纳文本或者其他内联元素,常见的内联元素有<span><a>

块元素:块元素一般都是从新行开始,可容纳文本,其他内联元素和其他块元素,即使内容不能占满一行,块元素也要把整行占满。常见的块元素<div><p>

 

2.代码演示1:

(1)exam.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>块元素和行内元素</title>

<link rel="stylesheet" type="text/css" href="my.css" />
</head>

<body>
    <!--行内元素:<span>使用方法-->
    <span class="s1">span1</span>
    <span class="s1">span1 hello world</span>
    <span class="s1">span1 hello world</span>
    
    <!--块元素:<div>使用方法-->
    <div class="s2">div1</div>
    <div class="s2">div2</div>
</body>

</html>

(2)my.css文件

@charset "utf-8";
/* CSS Document */

.s1 {
    background-color:pink;
}

.s2 {
    background-color:gray;
}

效果图:

总结:

  行内元素(inline element):特点是只占内容的宽度,默认不会换行。

  块元素(block element):特点不管内容有多少,他要换行,同时占满整行。

3.代码演示2:

(1)exam.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>块元素和行内元素</title>

<link rel="stylesheet" type="text/css" href="my.css" />
</head>

<body>
    <!--行内元素:<span>使用方法-->
    <span class="s1">span1</span>
    <span class="s1">span1 hello world</span>
    <span class="s1">span1 hello world</span>
    
    <!--块元素:<div>使用方法-->
    <div class="s2">div1</div>
    <div class="s2">div2</div>
    <span class="s1">okok</span>
    <p class="s3">p1</p>
    
</body>

</html>

(2)my.css文件

@charset "utf-8";
/* CSS Document */

.s1 {
    background-color:pink;
}

.s2 {
    background-color:gray;
    width:100px;
}

.s3 {
    background-color:pink;
}

效果图:

虽然这里div1和div2阴影不沾满整行,但是这个块元素实际上是占满整行的

 

4.块元素和行内元素的区别

(1)行内元素只占内容的宽度,块元素内容不管内容多少要占全行。

(2)行内元素只能容纳文本和其他行内元素,块元素可以容纳文本,行内元素和块元素(与浏览器类版本和类型相关)

(3)一些css属性对行内元素不生效,比如margin,left,right, width,height.建议尽可能使用块元素定位。(与浏览器类版本和类型相关)

 

 

5.行内元素和块元素--互相转换

display:inline  --->转化为行内元素(比如div)

display:block ---->转化为块元素(比如a)

案例演示:

posted on 2015-07-06 15:48  鸿钧老祖  阅读(210)  评论(0编辑  收藏  举报

导航