2026-05-29 22:25:40
内联CSS通过style属性直接嵌入HTML标签中,适用于快速定义单个元素的样式。以下是具体写法及使用技巧:
一、基本语法结构在HTML标签的style属性中编写CSS声明,格式为属性: 值;,多个属性用分号分隔:
<p style="color: red; font-size: 16px;">示例文本</p>直接调整文字外观,适合局部强调:
<h1 style="color: #ff0000; font-size: 24px; font-family: 'Arial', sans-serif; text-align: center;">标题</h1>color: 文字颜色(如#ff0000或red)。
font-size: 字体大小(如20px)。
font-family: 字体类型(如Arial, sans-serif)。
text-align: 对齐方式(如center)。
增强元素视觉效果:
<div style="background-color: yellow; background-image: url('bg.jpg'); border: 2px solid black; border-radius: 8px;"> 内容区域</div>background-color: 背景色(如yellow)。
background-image: 背景图路径(需确保路径正确)。
border: 边框样式(如2px solid black)。
border-radius: 圆角(如8px)。
精确控制元素布局:
<div style="width: 300px; height: 100px; padding: 10px; margin: 20px auto;"> 盒模型示例</div>width/height: 固定宽高(如300px)。
padding: 内边距(如10px)。
margin: 外边距(如20px auto实现水平居中)。
通过脚本实现交互式样式变化:
// 方法1:直接修改style属性document.getElementById("myElement").style.color = "blue";// 方法2:批量替换内联样式const element = document.querySelector(".box");element.setAttribute("style", "color: green; font-weight: bold;");通过以上方法,可灵活利用内联CSS实现高效样式控制。