ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Alternating backgrounds for divs with the same class name

Updated on December 21, 2015

This is what we are going to acomplish.

Alternate backgrounds
Alternate backgrounds

With purpose

Let's say you have an awesome website where your users enter any sort of data but you would like for the background to change between two colors every time a new data is entered. Does that sound cool? OK let's get Started.

Things we need to do:

  • Let's create the main container in which the data will be entered give it an id of 'main-container'.
  • Inside 'main-container' let's create 9 divs inside where your individual data will go. Give it a class name of 'data-div' and enter an individual number inside them wrapped on a <p> tag. Remember this will come from a database so that you do not have to change every div individually. The creation of the database is outside of the scope oft this tutorial.

Your HTML code should look like this so far

<div id="main-container">
    <div class="data-div"><p>1</p></div>
    <div class="data-div"><p>2</p></div>
    <div class="data-div"><p>3</p></div>
    <div class="data-div"><p>4</p></div>
    <div class="data-div"><p>5</p></div>
    <div class="data-div"><p>6</p></div>
    <div class="data-div"><p>7</p></div>
    <div class="data-div"><p>8</p></div>
    <div class="data-div"><p>9</p></div>
</div>

The CSS process

OK now let's give it some styling.

The CSS code break down!

  • Get rid of the default margin and padding by placing an *{} and inside the curly braces set margin and padding to 0. Set the background to #FFB3EE.
  • Give the body a width: of 800 pixels and margin auto.
  • Now to 'main-container', give it a white background just to tell it apart. a width of 100% and set a min height of 300 this tells the browser to keep it at 300 when there is no data or not enough data to overflow the div but once the div overflows it will push everything down as needed, float it to the left this will insure that the div expands down.
  • The div by the class of 'data-div' must have a default background set it to #91268F, width should be 32% height leave it at 300px, also float the divs left so that they stack next to each other set it to display flex to center the contents inside give it a border-radius to 15px and margin-bottom give it 15px.
  • Inside the 'data-div' there should be a p tag , set its margin to auto, text-align center, color to white, font-size to 100 px and chose any font you like.

So far this is how it should look

same color bacgrounds
same color bacgrounds

The important part of the css

We are going to use a selector called nth-of-type() in this case we will use it like .data-div:nth-of-type() we will select any element inside the div of the id name 'data-div' but we can specify it inside the parentheses, we can chose to select all the even numbers or all the odd numbers, we can also specify a certain number, but for now we will select all the even numbers and give them a background color of #EC008B.


This is how it should read

.data-div:nth-of-type(even) {
	background:#EC008B;
}

We are getting there

Some problems that need to be addressed

As you can see there are no spaces in between the boxes yet. How to solve this? we have a couple of choices but they are not so good.

  1. We can specify a margin-right to the first two boxes in a row leaving the third box tucked in to the right, but remember you will not be inserting the boxes in, a pre-thought out script will once a user enters data.
  2. If we set the margin left and right to each box it looks promising but all the boxes will end up inside the lines of the main box, we need them to be aligned to the edge of the main box also the boxes in the middle will have a much larger margin and it will look very odd.
  3. The solution will be to give the middle of the boxes an even margin to the left and right.
  4. We can then use the the .data-div:nth-of-type() but we ca not specify even or odd numbers because some middle boxes are odd and some are even.

This is where Jquery will come in handy here is what we need to do;

  • We need to install the JQuery library.
  • We need to count all the divs with class of 'data-div';
  • We need to run a for loop to assign add a class to the boxes we specify, the box numbers will be 2, 5, 8, and so on as you can see they are odd and even numbers.
  • We need to make another class rule and set margin-left and margin-right to 2%, make sure you use both margin-left and margin-right rules instead of margin: 0 2% 0 2%; as this will throw off your already margin bottom rule;

So bellow is the code

Set new class rules

.div-margin{
	margin-left:2% !;
	margin-right:2%;
}

JQuery library And Code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script>
$( document ).ready(function() {
	/* count all the boxes */
	var element = document.querySelectorAll('.data-div').length;
	/* run th loop */		
	for (i = 2; i <= element; i+=3) { 
	/* Set the margin on all the middle boxes */
		$('.data-div:nth-child('+i+')').addClass('div-margin');
	}		
});
</script>

The for loop break down!

  • We set a JavaScript function to run as soon as the page is loaded.
  • We then count all the divs with the class of 'data-div' to limit the loop.
  • We run a for loop we set the i = 2 because that is the first box in the middle on the first row
  • We then say to run the loop as long as the variable i is equal or less than the number of boxes counted.
  • Then we add 3 to the current i variable, making the first run 2 then 5 then 8 and so on, just the way we wanted.
  • Each time the loop runs we will add a class to the specified boxes set on the i variable, and that makes all the middle boxes have an even margin and the side boxes are tucked in their respective sides.

That is all folks I hope this helps you in your coding

I hope this helps you in your coding, leave a comment and say hi!

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)