Styled buttons in Ionic date picker

April 1st 2022 Ionic 4+

The new date picker in Ionic 6 brings many improvements, but it can be tricky to style. In a previous blog post, I was asked a question about this. I gave a short answer there, but I decided to expand on it in a separate blog post.

The component is difficult to style because most of the markup is protected with shadow DOM and few CSS custom properties are available.

Interestingly, global styles are not even applied to parts of the date picker. For example, you could use the following global style to prevent uppercase labels on Android:

ion-button {
  text-transform: none;
}

However, if you add default buttons to the date picker by setting showDefaultButtons, they will still be displayed in uppercase on Android:

<ion-datetime presentation="date" [showDefaultButtons]="true"></ion-datetime>

I could only prevent this by defining my own custom buttons in the buttons slot:

<ion-datetime presentation="date">
  <ion-buttons slot="buttons">
    <ion-button color="primary" fill="clear" (click)="cancel()"
      >Cancel</ion-button
    >
    <ion-button color="primary" fill="clear" (click)="done()">Done</ion-button>
  </ion-buttons>
</ion-datetime>

The global styles are applied to these buttons as expected, so they are no longer displayed in uppercase. However, this requires additional code to bind the buttons to the appropriate methods:

@ViewChild(IonDatetime, { static: true }) datePicker: IonDatetime;

cancel() {
    this.datePicker.cancel();
}

done() {
    this.datePicker.confirm();
}

When you create your own custom buttons, you can now style them however you like. You are not limited to global styles. Any component-level style works just as well:

ion-datetime ion-button {
  font-weight: bold;
}

You can find a full working example in my GitHub repository.

Shadow DOM does a great job of preventing unwanted changes to a component's appearance. But it also prevents intentional changes. At the very least, the documentation includes a detailed list of available appearance customization options. At the bottom of the documentation page for each component, you'll find a list of exposed CSS shadow parts, CSS custom properties, and slots.

Get notified when a new blog post is published (usually every Friday):

Copyright
Creative Commons License