html显示代码块
在HTML中显示代码块通常使用<code>和<pre>元素。<code>元素用于内联代码,而<pre>元素用于显示预格式化的文本,保留空格和换行符。通常,代码块放在<pre>标签内,而具体的代码行则在<code>标签中。
html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Code Block Example</title>
</head>
<body>
<pre>
<code>
function greet() {
console.log("Hello, world!");
}
greet();
</code>
</pre>
</body>
</html>
在这个例子中,<pre>元素包含了一个<code>元素,其中包含了JavaScript代码块。<pre>元素会保留代码中的空格和换行符,以确保代码的格式得以保留。
除了上述的基本结构,你还可以使用一些CSS样式来进一步美化代码块的显示。例如,可以使用样式表来设置代码的字体、颜色、背景等。
html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Styled Code Block Example</title>
<style>
pre {
background-color: #f4f4f4;
padding: 10px;
border-radius: 5px;
}
code {
font-family: 'Courier New', monospace;
color: #333;
}
</style>
</head>
<body>
<pre>
<code>
function greet() {
console.log("Hello, world!");
}
greet();
</code>
</pre>
</body>
</html>
在这个例子中,使用了<style>标签内的CSS样式来设置<pre>元素的背景颜色、内边距和边框圆角,同时设置<code>元素的字体和颜色。这些样式可以根据你的设计需求进行调整。