xxleyi / learning_list

聚集自己的学习笔记
11 stars 3 forks source link

CSS Inheritance #228

Open xxleyi opened 4 years ago

xxleyi commented 4 years ago

Some CSS attributes inherit from parent, while some don't, it mostly lives up to our common sense.

For example, color and font-size inherit, width and height don't.

Look for specs if you can not be sure.

About inheritance, we can alter by

In some cases, we want apply a css rule to all descendants of an element, which is also one form of inheritance, which is done by developer.

HOW?

/* the star is the key */
.some-class * {
    overflow: hidden;
}

Similarly, we can also apply a css rule to all children of an element.

/* > and * is the key */
.some-class > * {
    overflow: hidden;
}

增加一个实例,涉及到 flex overflow white-space 以及 text-overflow,关键点是使用继承简化 CSS 处理逻辑。

我们想要 son2 自身 overflow 为 hidden,且所有后代继承(overflow默认不继承)

<!DOCTYPE html>
<html>

<head>
  <title>Flex Demo</title>
  <style>
    .parent {
      width: 100%;
      height: 500px;
      background: red;
      display: flex;
    }

    .son1 {
      width: 50vw;
      background: green;
      flex: none;
    }

    .son2 {
      flex: 1;
      background: blue;
      overflow: hidden;
    }

    .son2 * {
      overflow: inherit;
    }

    .son2-son {
      font-size: 28px;
      color: #fff;
      white-space: nowrap;
      /* overflow: hidden; */
      text-overflow: ellipsis;
      margin-top: 10px;
    }
  </style>
</head>

<body>
  <div class="parent">
    <div class="son1"></div>
    <div class="son2">
      <div>
        <div class="son2-son">
          long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long 
        </div>
      </div>
    </div>
</body>

</html>