Super simple way to add an extra CSS class to content area items

PLACE FOR BLOG

Super simple way to add an extra CSS class to content area items

Super simple way to add an extra CSS class to content area items

marija

These days, I keep getting the same question: how to add an extra CSS class based on position of Content area item in the Content area. Unfortunately, people opt for the known solutions, whereas, a bit of investigation will make this a lot simpler and cleaner.

The code is as simple as follows:

    public class EvenOddContentAreaRenderer : ContentAreaRenderer
    {
        protected override void RenderContentAreaItems(HtmlHelper htmlHelper, IEnumerable contentAreaItems)
        {
            var index = 0;

            foreach (ContentAreaItem contentAreaItem in contentAreaItems)
            {
                var cssClass = (++index) % 2 == 0 ? " even" : " odd";

                RenderContentAreaItem(htmlHelper, contentAreaItem, GetContentAreaItemTemplateTag(htmlHelper, contentAreaItem), GetContentAreaItemHtmlTag(htmlHelper, contentAreaItem), GetContentAreaItemCssClass(htmlHelper, contentAreaItem) + cssClass);
            }
        }
    }

Ofc, you might not need even / odd, you might only want to add a CSS class to the first or the last item, but that I leave to you :)

Happy coding!

LEAVE A COMMENT