Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Conditional Formatting with CSS? 1

Status
Not open for further replies.

tomh1

Programmer
Feb 6, 2004
13
0
0
US
I'm developing a website and would like to alter the formatting of <p> tags based on their position in a document. For instance, a <p> tag following another <p></p> tag should have one formatting, but a <p> following an <h?></h?> should have a different formatting.

I know how to do this using classes, (e.g. "<p class='format1'>" or "<p class='format2'>") but I'd like something more automated so that authors can freely re-arrange paragraphs without screwing up the formatting. If every paragraph started with the same <p> tag, but rendered the CSS based on the prior formatting tag, that would be great.

I can't use any server-side tricks.

Thanks.
 
tomhopper said:
I can't use any server-side tricks.

the phrase "not a prayer" comes to mind. certainly not in html anyway.

A javascript answer may be possible but could be staggeringly complex. try forum216

Even a server-side solution would not be trivial.

Chris.

Indifference will be the downfall of mankind, but who cares?
A website that proves the cobblers kids adage.
Nightclub counting systems

So long, and thanks for all the fish.
 
The good news is that you can do this with CSS using an adjacent selector:
Code:
<html>
<head>
  <title>First Para Bold</title>
  <script>
    /* Define a rule for p immediately following a h1, h2 or h3 */
    h1 + p, h2 + p, h3 + p {
      font-weight: bold;
    }
  </script>
</head>
<body>
  <h1>My Article</h1>
  <p>This is the first paragraph</p>
  <p>This is the second paragraph</p>
</body>
</html>
The bad news is (wouldn't you know it) it won't work in IE. If you're only adding a little eye candy, maybe that isn't important. If it is, you could try using IE7 on your site to fix IE's behaviour, or you could write some (probably not all that complex) Javascript to parse your page and add a class to <p>s following <hn>s.

-- Chris Hunt
Webmaster & Tragedian
Extra Connections Ltd
 
Also possible with IE extensions to CSS:
Code:
<style type="text/css">
p {	
	font-weight: expression(  'H1, H2, H3'.indexOf( this.previousSibling.tagName ) >= 0? 800: 100 );  
}
</style>
.. but I wouldn't do that unless really necessary.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top