塊元素和行內元素的區別與轉換

ZaireSinatra發表於2020-11-27

塊元素和行內元素的區別與轉換

塊元素和行內元素的區別與轉換在前端面試中常被問到,這裡做個總結.

行內元素:

常見:<span>\<a>

行內元素又稱為內聯元素,在內僅容納文字或其他行內元素;

塊元素:

常見:<div>\<p>\<h>

塊元素可以容納文字,行內元素和其它塊元素.

其中<span>常適應於小段文字,<div>用於長HTML


實際使用行內元素與塊元素效果程式碼如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
		span{
			background-color:bisque;
		        }
		p{
			background-color:pink;
				}
		</style>
	</head>
	<body>
		<span>行內元素</span>zairesinatra
		<p>塊元素</p>zairesinatra
	</body>
</html>

效果如圖:
行內元素與塊元素效果

1. 塊級元素:內容獨佔一行.塊元素會在內聯的方向上擴充套件並佔據父容器在該方向上的所有可用空間.
2. 行內元素:不會產生換行.行內元素只佔放置其中內容的寬度,塊元素忽視內容佔據全行.

設定行內元素與塊元素引數程式碼效果如下:
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
		span{
			background-color:bisque;
			width:100px;
			height:100px;
			margin: 30px 60px 90px 120px;
		        }
		p{
			background-color:pink;
			width:100px;
			height:100px;
			margin: 30px 60px 90px 120px;
				}
		</style>
	</head>
	<body>
		<span>行內元素</span>zairesinatra
		<p>塊元素</p>zairesinatra
	</body>
</html>

效果如圖:
設定行內元素與塊元素尺寸程式碼效果

3. 塊元素中width 和 height 屬性可以發揮作用.內邊距(padding)外邊距(margin)和邊框(border)起效.
4. 行內元素width 和 height 屬性將不起作用.
5. 行內元素垂直方向的內邊距、外邊距以及邊框會被應用但是不會把其他處於 inline 狀態的盒子推開.
6. 行內元素水平方向的內邊距、外邊距以及邊框會被應用且會把其他處於 inline 狀態的盒子推開.

塊元素與行內元素轉化:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
		span{
			display:block;
			background-color:bisque;
			width:100px;
			height:100px;
			margin: 30px 60px 90px 120px;
		        }
		p{
			background-color:pink;
			width:100px;
			height:100px;
			margin: 30px 60px 90px 120px;
				}
		</style>
	</head>
	<body>
		<span>行內元素</span>zairesinatra
		<p>塊元素</p>zairesinatra
	</body>
</html>

行內元素轉化塊元素效果如圖:
行內元素轉化塊元素效果
塊元素轉化行內元素:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
		span{
			background-color:bisque;
			width:100px;
			height:100px;
			margin: 30px 60px 90px 120px;
		        }
		p{
			display:inline;
			background-color:pink;
			width:100px;
			height:100px;
			margin: 30px 60px 90px 120px;
				}
		</style>
	</head>
	<body>
		<span>行內元素</span>zairesinatra
		<p>塊元素</p>zairesinatra
	</body>
</html>

塊元素轉化為行內元素效果如圖:
塊元素轉化為行內元素
行內元素轉換為塊元素-display:block;
塊元素轉換為行內元素-display:inline.

相關文章