I recently got asked if it was possible wrap the column headers in a list view web part. The user had a WebPart with quite a few columns with long names and was trying to prevent the page from scrolling left to right.

Column Header (nowrap)

What we needed to do was wrap the column header so that it fit more to the data in the grid.

Column Header (wrapped)

The solution is relatively simple to implement; all you need is a Content Editor Webpart at the bottom of the page somewhere with the following JavaScript in it:

<script type="text/javascript">
function WrapColumnHeaderText(columnName) {
    try {
        var tables = document.getElementsByTagName("table");
        for (i = 0; i < tables.length; i++) {
            // find the table that is for the column we're looking for
            var attrItem = tables[i].attributes.getNamedItem("displayname")
            if (null != attrItem && attrItem.nodeValue === columnName) {
                var cells = tables[i].getElementsByTagName("td");
                for (c = 0; c < cells.length; c++) {
                    if (null != cells[c].attributes.getNamedItem("nowrap")) {
                        cells[c].attributes.removeNamedItem("nowrap");
                        // after removing nowrap, IE won't actually wrap the content
                        // until it "changes".. so we touch it to force it to wrap
                        cells[c].innerHTML = cells[c].innerHTML;
                        break;
                    }
                }
            }
        }
    } catch (ex) {
        alert(ex.toString());
    }
}

function WrapColumnHeaders() {
    // TODO: repeat the line below to wrap more columns
    WrapColumnHeaderText("Company Product Code");
}

_spBodyOnLoadFunctionNames.push("WrapColumnHeaders");
</script>

3 Responses to “Wrap ListViewWebPart Column Headers”

  1. Ryan Says:

    Hi Kit – a simpler method just using CSS that might be of interest.

    http://blog.pentalogic.net/2011/06/word-wrapping-sharepoint-list-column-headers/

  2. Kit Says:

    Very cool! The CSS does look a lot easier… especially if you want all of the columns to wrap. :)

    I kinda like the JavaScript way because it allows you to choose a specific column.

  3. Brady Says:

    Hello,

    I tried to implement this in SharePoint 2010 and my column heading did not wrap.  Any ideas?

    Thanks  

Leave a Reply

In order to provide better answers to questions, please read the following before posting a comment:

  1. General question about SharePoint? Please ask a question at SharePoint StackExchange
  2. Comment or feedback specific to this post only? Please post a comment below