问题
I have a structured semantic data that I would like to display, styling it with CSS. Here is a sample:
...<user name="John">...</user>...
I would like it to be rendered like this:
...
User John ...
...
If I wanted 'User' and 'John' to have the same color, I could use the following CSS:
user:before{
content: 'User ' attr(name);
}
However, I want 'User' to be blue, and 'John' to be red. How can I achieve this with CSS?
P.S. I don't want to transform my data representation. I know I could easily get such formatting by transforming the data to have extra divs, etc, but I would like to display my pure semantic data directly in the form it is.
回答1:
If the user
element is empty, you could use the following CSS:
user::before {content:"User "; color:blue;}
user::after {content:attr(name); color:red;}
If the user
element contains content, you may use:
user::before {content:"User "; color:blue; float:left; margin-right:0.5em;}
user::after {content:attr(name); color:red; float:left; margin-right:0.5em;}
(using float
to get the element content behind the "User John" string; using margin
to get whitespace between the words; there are probably neater ways to fix those things)
回答2:
You can't style part of content of :before
pseudo differently in CSS. You need an extra element (like a span
) somewhere. :first-letter
and :first-line
(and content of :before
as a whole) are exceptions to that but that's not what you want to achieve.
来源:https://stackoverflow.com/questions/14288847/css-before-content-two-colors