Color Fields

Color fields provide a flexible way to store hexadecimal color values. You can define a palette to guide authors 5.6.0+, or use an open-ended input.

Screenshot of a color field interface in the Craft control panel

# Settings

my-craft-project.ddev.site/admin/settings/fields/new
Color field settings screen in the Craft control panel
Adding a new color field via the control panel.

# Palette

Each field contains a Palette of colors that authors can select from a dropdown menu.

# Custom Colors

Turn on Allow custom colors to display a compact input and color preview UI. When used in conjunction with a palette, an additional Custom… option is listed at the bottom of the dropdown menu.

In browsers that support <input type="color"> (opens new window), clicking on the color preview “well” opens a native OS color picker.

# Development

Accessing a color field returns a craft\fields\data\ColorData (opens new window) object, or null if no color was selected.

Casting a ColorData object to a string by outputting it directly produces a hexadecimal representation of the color:

{% if entry.myColorField %}
  <style type="text/css">
    .content a {
      {# Directly outputting the value... #}
      color: {{ entry.myColorField }};
    }
    .content b {
      {# ...is equivalent to: #}
      color: {{ entry.myColorField.getHex() }};
    }
  </style>
{% endif %}

ColorData objects have a number of methods that streamline working with color values:

{% if entry.myColorField %}
  {{ entry.myColorField }}                 {# output: #e5422b #}
  {{ entry.myColorField.getHex() }}        {# output: #e5422b #}
  {{ entry.myColorField.getRgb() }}        {# output: rgb(229,66,43) #}
  {{ entry.myColorField.getHsl() }}        {# output: hsl(7,81%,90%) #}
  {{ entry.myColorField.getLuma() }}       {# output: 0.38820862745098 #}
  {{ entry.myColorField.getHue() }}        {# output: 7 #}
  {{ entry.myColorField.getLightness() }}  {# output: 90 #}
  {{ entry.myColorField.getSaturation() }} {# output: 81 #}
  {{ entry.myColorField.getRed() }}        {# output: 229 #}
  {{ entry.myColorField.getGreen() }}      {# output: 66 #}
  {{ entry.myColorField.getBlue() }}       {# output: 43 #}
{% endif %}

Refer to the ColorData (opens new window) class reference for a complete list of methods!

# Querying by Color

There are no special query features for color fields; refer to the plain text field for a list of standard string comparison syntaxes.