p { font-size: 16px; line-height: 1.5; color: #333; } pre { background-color: #f5f5f5; padding: 10px; border-radius: 5px; } .box { width: 300px; height: 200px; margin: 50px auto; background-color: #eee; font-size: 24px; font-family: Arial, sans-serif; color: #333; text-align: center; line-height: 200px; }
CSS可以通过定义背景和字体,来美化页面的各种元素。下面我们通过代码来演示如何使用CSS定义背景和字体。
1. 定义背景
/* 使用颜色值设置背景颜色 */
background-color: #f5f5f5;
/* 使用URL设置背景图片 */
background-image: url("bg.jpg");
/* 设置背景重复方式 */
background-repeat: repeat-x;
/* 设置背景位置方式 */
background-position: center top;
/* 设置背景大小 */
background-size: cover;
2. 定义字体
/* 设置字体大小 */
font-size: 16px;
/* 设置字体类型 */
font-family: Arial, sans-serif;
/* 设置字体颜色 */
color: #333;
/* 设置字体粗细 */
font-weight: bold;
/* 设置字体斜体 */
font-style: italic;
/* 设置行高 */
line-height: 1.5;
下面我们结合代码来实现一个包含背景和字体效果的示例:
<div class="box">
Hello World!
</div>
在上面的示例中,我们设置了一个宽300px、高200px的盒子,它有一个灰色的背景色,同时使用了字体大小为24px的Arial字体,字体颜色为黑色,字体居中显示。