【问题标题】:Material Radio Label Content Wont Apply Text Wrap CSS Angular材质单选标签内容不会应用文本换行 CSS Angular
【发布时间】:2022-04-14 17:22:36
【问题描述】:

我有一个固定宽度的单选组,我希望按钮标签可以换行。我尝试向 html 的每个部分添加类并向元素添加“空白:正常”,但它只是忽略了它。我怎样才能让它发挥作用?

Here is an example of where I am at

如果我将此 CSS 添加到顶级 styles.scss 文件中,它会按预期工作。

.mat-radio-label-content {
  white-space: normal;
}

但我想避免这种情况,并保持 css 仅与特定组件相关,而不是应用范围。

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    使用选择器将标签文本包装在跨度中。

        <style>
            .wrap-mat-radio-label {
                white-space: normal;
            }
        </style>
    
        <mat-radio-group>
            <mat-radio-button>     
                <span class="wrap-mat-radio-label">
                    {{ season }}
                </span>
            </mat-radio-button>
        </mat-radio-group>
    

    【讨论】:

    • 谢谢,非常有帮助!你知道为什么.mat-radio-label-content 不接受 CSS 吗?
    • @Maverick283 这是因为元素 .mat-radio-label-content 是作用域的,而不是组件的一部分。但是您可以在styles.scss 等全局样式中设置此样式,例如.mat-radio-label-content { white-space: normal; }。然后它工作。但要小心全局样式。在这里显式总比隐式好。意味着您可以在此处创建一个自定义选择器,例如 mat-radio-group.text-wrap,然后访问 .mat-radio-label-content 以设置换行选项。
    【解决方案2】:

    只是另一种具有全局样式的解决方案(例如styles.scss)。

    简单的蛮力解决方案:

    .mat-radio-label-content {
      white-space: normal;
    }
    

    但要小心全局样式。我们应该添加一个自定义类选择器以避免全局意外问题。

    自定义类选择器:

    mat-radio-group.text-wrap {
      .mat-radio-label-content {
        white-space: normal;
      }
    }
    

    为什么不在mat-radio-button 上使用text-wrap?因为 Angular Material 会覆盖该元素上的所有类。 mat-radio-group 的类也为我们提供了更多的选择(见下文),并且写得更少。

    进一步打磨:

    mat-radio-group.text-wrap {
      /* Add some space between the options for readability. */
      /* Especially when we align the radio symbol on start position. */
      gap: 2px;
    
      .mat-radio-container {
        /* The default behavior is center. */
        /* But the radio options are then difficult to tell apart. */
        /* Therefore we align the radio symbol on top position. */
        align-self: start;
      }
    
      .mat-radio-label-content {
        /* Wrap the label text. */
        white-space: normal;
      }
    }
    

    (StackOverflow 没有突出显示 SCSS。因此它是一个 CSS 块。因此是注释样式。如果有人想知道... 琐事:在 SCSS 中,您应该更喜欢 // cmets,它将在构建时删除。/**/ 保留正在构建中。)

    随意走自己的路。舞台是你的。您还可以尝试唠叨 Angular Material 开发人员以正式提供文本换行功能以避免自定义“黑客攻击”。但根据我的经验,他们严格遵守材料指南。即使这意味着改进,他们也很难说服。您也可以考虑切换 UI Framework。

    【讨论】:

      猜你喜欢
      • 2015-08-28
      • 2023-03-16
      • 2020-03-31
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多