Apply Different CSS Stylesheet for Different Parts of the Same Web Page

Apply different css stylesheet for different parts of the same web page

You can't apply different stylesheets to different parts of a page. You have a few options:

The best is to wrap the different parts of the page in divs with class names:

<div class='part1'>
....
</div>

<div class='part2'>
....
</div>

Then in your part1 CSS, prefix every CSS rule with ".part1 " and in your part2 CSS, prefix every CSS rule with ".part2 ". Note that by using classes, you can use a number of different "part1" or "part2" divs, to flexibly delimit which parts of the page are affected by which CSS rules.

Different css for different pages

I would suggest, put an ID into your home page like,

<body id="home"> and other ids for other pages

Now the CSS changes would be

/* on home page, it should appear like this */
#home #box {
background: green;
width:200px; height:100px;
}

/* on other pages, it should appear like this */
#others #box {
background: red;
width:200px; height:200px;
}

Apply different css style file on different section tags on single page

CSS applies to the entire document, so your options are:

  • Use separate documents
  • Rewrite the CSS to prepend section#your-section (followed by a descendant combinator) to each selector.

(You could also hope and wait for scoped CSS to be well supported).

Use a different CSS file for within a DIV?

You can achieve it in the following way :

1. Assign a class to the concerned div like

<div class="different"> 

And then style this class different in your default css, for example :

.different{
font-size:12px;
}

2.The other way is to use IDs , since ids are unique to one element and on page only one element can have that ID .

<div id="diff">

And than in your current css file you can write something like :

#diff{
font-size:12px;
}

They both will serve your purpose but classes can be used multiple time and IDs are unique to a given element. So it's up to you to decide which method you follow.

Is it good idea to make separate CSS file for each HTML page?

Your example shows you using one design.css file for your entire website.

Generally, it is better to have one single .css file containing data for all pages for 2 reasons:

  1. You will allow browsers to cache .css files thus resulting in faster loading times;
  2. It will ease the maintenance process.

I would advise you, if you really want to divide .css in separate blocks to use CSS' @import to divide blocks of code f.e form styles and so on.



Related Topics



Leave a reply



Submit