Monday

CSS generated content issue on Chrome/Safari

Recently I needed to use CSS content to help with some display stuff. Skipping through the typical debate about separation of concerns, I had to use this method because in this case I don't have access to the actual markup of this part of the page. This really does happen to web developers on occasion, typically due to 3rd party generated content, which was the case here.

Basically, all I needed to do was add a text "header" before my content. So, I added something like the following;

p:before {
    content: "Header Text";
    display: block;
}
Note I wanted to add "display: block" here to introduce a line break between my new CSS generated content and the pre-existing text of my paragraph. No big deal, because I know that this is a supported feature with just about every browser sans the usual IE6/7, which I'm comfortable with leaving alone without the added content: http://www.caniuse.com/#feat=css-gencontent.

My particular case of 3rd party content was a bit more troublesome than usual, because it's made up of a bunch of unclassed paragraph tags, with bold tags representing what the 3rd party thought would be like a sub-header for each paragraph. The paragraph I need to edit was the 5th in this structure. This block of HTML looked something like this:

Sub header 1 A bunch of content

Sub header 2 A bunch of content

Sub header 3 A bunch of content

Sub header 4 A bunch of content

Sub header 5 A bunch of content

Sub header 6 A bunch of content

My thinking was that I wanted my generated content to be within my 5th paragraph, but before the bold tagged "sub-header"; as such, I change my selection to something a bit more complicated. So, I updated my CSS selector:

.some-content p:nth-of-type(5) b:before {
    content: "Header Text";
    display: block;
}
And it works as expected in recent versions of Firefox (though CSS3 selection isn't supported in IE8, so there's an issue there now), but yay! But this did not work as expected in either Chrome or Safari. What the heck?

Resolution

As it turns out (for reasons currently unknown to me), both Chrome and Safari didn't like adding the :before pseudo-class onto the b tag. Changing the selector to remove the bold, things worked:
.some-content p:nth-of-type(5):before {
    content: "Header Text";
    display: block;
}
I've always tried to avoid this type of combined selector with 2 pseudos, in this case "p:nth-of-type(5):before" would seem to elicit some buggy behavior. Only I've been shown I was a bit wrong, at least in this case. The above is working for Chrome 18, Safari 5, Firefox 11, IE 9 (sort of buggy re: positioning). IE8 and older are sort of out of the picture here now due to my fancy selector; I'm OK with this.

No comments:

Post a Comment