CSS有哪些属性以及哪些属性可以继承

72 阅读3分钟

CSS 属性繁多,可分为布局类盒模型类文本类视觉类等多个类别。其中,部分属性具有继承性—— 子元素会自动继承父元素的样式,无需重复设置;另一部分则不会继承,需要显式设置。

一、CSS 常用属性分类及示例

以下是按功能分类的核心属性(非全部,仅列举高频使用的):

1. 文本与字体相关(多为可继承属性)

属性作用示例
color文本颜色color: #333;
font-family字体类型font-family: "微软雅黑", sans-serif;
font-size字体大小font-size: 16px;
font-weight字体粗细(bold/normal/ 数字)font-weight: 600;
line-height行高line-height: 1.5;
text-align文本对齐方式(left/center/right)text-align: center;
text-decoration文本装饰(underline/none)text-decoration: none;
letter-spacing字符间距letter-spacing: 2px;

2. 盒模型与布局相关(多为不可继承属性)

属性作用示例
width/height元素宽高width: 100px;
margin外边距margin: 10px 20px;
padding内边距padding: 8px;
border边框border: 1px solid #ccc;
display元素显示类型(block/inline/flex)display: flex;
position定位方式(static/relative/absolute)position: relative;
float浮动(left/right/none)float: left;
flexFlex 布局子项占比flex: 1;

3. 背景与视觉相关(多为不可继承属性)

属性作用示例
background背景(颜色 / 图片等,简写)background: #f5f5f5;
background-color背景色background-color: white;
background-image背景图片background-image: url(bg.jpg);
border-radius圆角border-radius: 4px;
box-shadow阴影box-shadow: 0 2px 4px rgba(0,0,0,0.1);
opacity透明度(0-1)opacity: 0.8;

4. 其他常用属性

属性作用示例
cursor鼠标指针样式cursor: pointer;
list-style列表样式(如 bullet/decimal)list-style: none;(移除列表符号)
overflow内容溢出处理overflow: hidden;
z-index层叠顺序(定位元素)z-index: 10;

二、可继承的 CSS 属性(核心)

继承属性的特点:子元素会自动沿用父元素的样式,适合文本相关样式(减少代码冗余)。

  1. 文本与字体类
    colorfont-familyfont-sizefont-weightfont-style(斜体)、line-heighttext-alignletter-spacingword-spacing(单词间距)等。
    例:父元素设置 font-family: "宋体";,子元素文本会自动使用宋体,无需重复设置。
  2. 列表相关
    list-stylelist-style-type(列表符号类型)、list-style-position 等。
    例:ul 设置 list-style: none;,内部 li 会自动移除默认圆点。
  3. 其他
    visibility(可见性,hidden/visible)、cursor(鼠标指针)等。

三、不可继承的 CSS 属性(核心)

不可继承属性多与元素自身布局、盒模型、视觉样式相关,需要为每个元素显式设置。

  1. 盒模型与尺寸
    widthheightmarginpaddingborderbox-sizing 等。
    例:父元素设置 width: 500px;,子元素不会自动继承宽度,需单独设置。
  2. 布局与定位
    displaypositionfloatflexz-indexoverflow 等。
  3. 背景与装饰
    backgroundbackground-colorborder-radiusbox-shadowtext-decoration(下划线等,特殊:虽为文本相关,但不可继承)等。
    例:父元素设置 text-decoration: underline;,子元素文本不会自动带下划线。

四、继承的特殊规则

  1. 强制继承:使用 inherit 关键字让子元素强制继承父元素的某个属性(即使该属性默认不可继承)。

    .child {
      width: inherit; /* 强制继承父元素的 width */
      margin: inherit; /* 强制继承父元素的 margin */
    }
    
  2. 默认继承失效:部分元素(如 <a> 链接)会默认覆盖继承的样式(如 color),需显式重置。

    /* 链接默认蓝色,需手动继承父元素颜色 */
    a { color: inherit; }
    

总结

  • 可继承属性:多与文本样式相关(如字体、颜色、行高),目的是保持文本风格一致性。
  • 不可继承属性:多与元素自身布局、盒模型相关(如宽高、边距、背景),需按需单独设置。