El UI components greatly improve our development efficiency, some logic and style encapsulation, we can directly use, very good. However, some of the company’s customization needs, especially styling issues, are not easily addressed by the API provided by the component alone. If we could modify the style of the EL UI component directly, then our job would be simplified to modify rather than duplicate the wheel.

Existing problems

If you want to change the style of EL UI in one page or component, it will inevitably affect the style of other el UI components in the whole project. The reason is that the style is global. If scoped is added, the modification will not take effect.

The solution

After a day of thinking and experimenting, I took many detours, such as writing inline style and adding in postCSS! How to limit the changes to the local page?

usingpostcssanddomHierarchical relationship, targeted modification.

example

For example:

    <el-button type="primary">The main button</el-button>
    <el-button type="primary">Main button 2</el-button>
Copy the code

CSS:

.button1 {
  opacity: 0.5;
}
.button2 {
  width: 100px;
  height: 100px;
}

Copy the code

Now I have two needs:

  • Button 1 changed the background to translucent;
  • Change the shape of button 2 to square;

Looking at the component’s API doesn’t meet this requirement, so I’ll just start making changes!

When you open the console, you can see the following DOM structure:

If we modify it directly, it will definitely affect another button, which cannot achieve the effect we want. So, it can be as follows:

  • Add another class:
<el-button type="primary" class="button1">The main button</el-button>
<el-button type="primary" class="button2">Main button 2</el-button>
Copy the code

The effect is shown below:

  • There is a globally unique DOM layer around it:
<div class="button1">
      <el-button type="primary">The main button</el-button>
</div>
<div class="button2">
      <el-button type="primary">Main button 2</el-button>
</div>
Copy the code

postcss:

.button1{&.el-button {
    opacity: 0.5; }}.button2{&.el-button {
    width: 100px;
    height: 100px; }}Copy the code

The effect is as follows:

This example doesn’t make much difference, but there are cases where the dom of a component is too deeply nested to add classes directly, and the second method of finding them layer by layer is still acceptable. It’s not very elegant by any means, but it also improves the reuse of some logical code and reduces project complexity and duration.