I need to customize the look of the MubBlazor MusSelect component. Basically I want to apply a background to the input and let the label with a transparent background.
original:

Custom:

This could be easily achieved by overriding some mudblazor css classes in some global css file (e.g. site.css):
.mud-input-control > .mud-input-control-input-container > div.mud-input.mud-input-text {
background: #ffffff;
margin-top: 15px;
}
In order to be able to use the custom one in combination with the original mudSelect I added a class to the mudSelect component:
<MudSelect Class="custom-select" T="string" Label="Coffee" AnchorOrigin="Origin.BottomCenter">
<MudSelectItem Value="@("Cappuccino")" />
<MudSelectItem Value="@("Cafe Latte")" />
<MudSelectItem Value="@("Espresso")" />
</MudSelect>
.custom-select .mud-input-text {
background: #ffffff;
margin-top: 15px;
}
But I don´t want to add a class every time I need to use my custom look so I decided to implement a component that inherits from mudSelect.
SelectBox.razor
@inherits MudSelect<T>
@typeparam T
@namespace Common.Components
@RenderBase()
@code {
public RenderFragment RenderBase() => builder => base.BuildRenderTree(builder);
protected override void OnParametersSet()
{
base.OnParametersSet();
Class = $".custom-select {Class}";
}
}
Now we can use our custom component:
<SelectBox T="string" Label="Coffee" AnchorOrigin="Origin.BottomCenter">
<MudSelectItem Value="@("Cappuccino")" />
<MudSelectItem Value="@("Cafe Latte")" />
<MudSelectItem Value="@("Espresso")" />
</SelectBox>
The goal from this solution was to differentiate between MudSelect and my CustomSelect but also css isolation by moving the css to the component. This solution is working but I couldn´t move the css rules because css isolation is not working.
Is there a better way to solve this?
After reading the Child component support from ASP.NET Core Blazor CSS isolation documentation I realized that my problem was that I was not using a parent element where to apply the scope identifier.
So by adding the div and using the ::deep pseudo-element in my scoped css. Everything worked
SelectBox.razor
@inherits MudSelect<T>
@typeparam T
@namespace Common.Components
<div>
@RenderBase()
</div>
@code {
public RenderFragment RenderBase() => builder => base.BuildRenderTree(builder);
protected override void OnParametersSet()
{
base.OnParametersSet();
Class = $".custom-select {Class}";
}
}
SelctBox.razor.css
::deep .mud-input-text {
background: #ffffff;
margin-top: 15px;
}
::deep .custom-select input {
padding-left: 5px !important;
}
::deep .mud-input-control {
margin-top: 0px;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With