Customize the output style of a view field or list

Last updated on
21 June 2023

You can customize the HTML and CSS for a view. You can also enable or disable the default CSS classes.

Customize a view field

  1. Navigate to the edit screen for a view (for example, admin/structure/views/view/MYVIEWNAME/edit).
  2. In the Fields section, click a field. The Configure Field dialog box displays.
  3. Click Style Settings.
  4. Enable one or more of the following options:
    • Customize Field HTML
    • Customize Label HTML
    • Customize Field and Label Wrapper HTML.
  5. For each of the enabled options, specify the HTML element to wrap around the item. You can also click Create a CSS Class and specify a class name.
  6. Enable or disable the Add Default Classes option. When enabled, this option specifies that the field uses Views default classes.
  7. Click Apply.

Customize a view list

You can wrap a view list in one or more classes.

  1. Navigate to the edit screen of a view, as outlined above.
  2. Click Advanced in the right hand side.
  3. Click Add class.
  4. Add one or more classes, separated by spaces.
  5. Click Apply.

Note: An added class only wraps the view content, so if you are creating a block, the class is not inserted in the root of the block. To add a class or ID to the parent block, you can set the machine name, or use the Block Class contrib module.

If you use the machine name, it is important to do this before placing the block. Changing the machine name of an already placed block is not recommended, since it will break all references to it, and require placing the block again.

Another way to add a class is with a block preprocess hook in the mytheme.theme file of your theme. Replace views_block__my_view_machine_name with the elements #id of your block. The example includes a line which outputs all #id's on the page, which you should remove after it has served its purpose. The #id should be output right before the block.

function mytheme_preprocess_block(&$variables) {
  if (!empty($variables['elements']['#id'])) {
    // output all elements #id's on the page
    echo $variables['elements']['#id'] . '<br>';
    if ($variables['elements']['#id'] == 'views_block__my_view_machine_name') {
      $variables['attributes']['class'][] = 'my-custom-class';
    }
  }
}

Note: You might assume that $variables['elements']['#id'] is the same as the id in the HTML, but they are not. The source could be id="block-views-block-example-views" but the $variables['elements']['#id'] value is views_block__example_views.

Help improve this page

Page status: No known problems

You can: