CSS :before content two colors

喜欢而已 提交于 2019-12-06 13:22:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!