change style of a Label of a Component

Hello,
I’m using Vaadin 13.0.0 . I have a text field with a Label

TextField myTextField = new TextField();
myTextField.setLabel("My Field");

how to change the label style? I’m trying to make it bold. I tried with no success:

myTextField.getElement().getStyle().set("fontWeight","bold");

Hi! With Vaadin 10+, all components are implemented on he Web Component standards, and as such have different rules for styling. If you have a shared-styles.html file already in your project, add this inside the custom-style tag:

  <dom-module id="custom-textfield" theme-for="vaadin-text-field">
    <template>
      <style>
        [part~="label"]
 {
          font-weight: bold;
        }
      </style>
    </template>
  </dom-module>

Everthing inside the part block is regular CSS, it’s just the packaging that’s new :slight_smile:

If you don’t have that particular file, create one under src/main/webapp/frontend/styles, with this content:

<link rel="import" href="../bower_components/vaadin-lumo-styles/color.html">
<link rel="import" href="../bower_components/vaadin-lumo-styles/typography.html">

<custom-style>
    
  <dom-module id="custom-textfield" theme-for="vaadin-text-field">
    <template>
      <style>
        [part~="label"]
 {
          color: red;
        }
      </style>
    </template>
  </dom-module>
  
</custom-style>

You’ll also need this annotation on your root (main) layout:

@HtmlImport("frontend://styles/shared-styles.html")

this worked like a charm! thank you!

and now the fun part: I have only some labels to make bold :slight_smile: some labels have to be not bold.
how to manage this?

More fun indeed!

		TextField tf = new TextField();
		tf.setLabel("bold?");
		// tf.setThemeName("boldlabel");
		add(tf);
:host([theme~="boldlabel"]
) [part~="label"]
 {

That way the css only targets textfields with the ‘boldlabel’ theme.

And this also worked fine! Thank you!
BUT
This is the last question I promise!
I also have a ComboBox and a DatePicker that require a bold label, I can’t find setThemeName on them… ho wo do the last trick?

You can add a class name to those instead.

ComboBox cb = new ComboBox();
cb.addClassName("bold-label");
<dom-module id="bold-combo-box" theme-for="vaadin-combo-box">
    <template>
      <style>
        :host(.bold-label) [part~="label"]
 {
          font-weight: bold;
        }
      </style>
    </template>
  </dom-module>