Wednesday 31 August 2016

Modify a Single or Group of Web Parts Based on Location in the Layout

If you have an area of your page that needs to style the web parts differently than the rest of the page, modify the master page, content page or page layout to include a container tag for the area that needs to be different. Then use descendent (also called contextual) selectors in your CSS file to target the changes.
The type of container you use will be dependent on your site design/layout/existing code.  You may already have a container set up that could be used.  Generally, you need to create something like this:
<div class=”Column”>
<Web Part Zone />
</div>
This is a very basic example, you will probably have content placeholders and other code involved.  The idea is to create a new CSS class wrapped around the area that will contain the web parts.
(If you are reading this article in full, here is deja vu…) All web parts use the same code for formatting.  It is just a part of the package deal when working with dynamically generated content and web pages.   All OOTB web parts will use .ms-WPHeader, .ms-WPTitle, .ms-WPBody, etc.  For a full list of styles used by web parts, check out my online CSS reference chart.
If you add one of these styles to your custom CSS file and make any changes, all web parts will be affected.   If you want to selectively control a web part(s) based on location in the web page, you will need to employ the use of some other CSS methods.  For this example I will  be usingdescendant selectors.
Descendant selectors allow you to specify CSS rules based on the hierarchal relationship of which the elements appear.   If you want to control every paragraph tag that is within a div tag and only those paragraphs that are within a div, you would use a selector formatted like this:
div p {declaration}
By using the custom container you wrapped around the area of the page you need to control, you can target your web part changes.
Create the CSS Rule
  1. First I am going to set up a basic style that will alter all web part title bars:
    .ms-WPHeader TD {
    background-color:green;
    border-bottom:1px solid red;
    }
    View a screen shot of the results.
  2. I can then add the CSS class name of the newly added parent container:
    .Column .ms-WPHeader TD {
    background-color:yellow;
    border-bottom:1px solid red;
    }
    Now just web parts that are within the Column div tag will pick up the styling.  View a screen shot of the results.  In this sample screen shot I also added a border to my container div so you can see where it is.
This approach is very flexible, but does require that you modify the master page, content page or page layout in order to add that parent container.  If this isn’t an option, poke around your View Source to see if there is a “parent container” already available for the web parts you want to alter.

No comments: