Style half of a word, sentence, etc - css

I'd like to show a title with the first three characters in different color.
I know this can be done with <h2><span>The</span> awsome title</h2> but I was wondering if there is some kind of "nth-child" property that can be applied to characters inside an element.
I'd like to avoid breaking the text by inserting other elements ( etc.)
A (relatively) crossbrowser solution would be welcome.

There is no cleaner way than what you already have.
<h2><span>The</span> awesome title</h2>
With CSS:
h2 {
color: red
}
h2 span {
color: blue
}
There's :first-letter and :first-line, but no :first-word.
I imagine the reason for this is that it's hard to define exactly what a "word" should be.
The only way to do it without changing your markup is to use JavaScript to enclose the first word with a <span> (and style it the same way), but I would only recommend that if the rest of your site already heavily relies on JavaScript to function.

Yep, JavaScript is the only way I can think of (as everyone else has already said!). Demo here.
$(function() {
$('h2').each(function(){
$(this).html( $(this).text().replace(/(^\w{3})/,'<span>$1</span>'));
});
});

This isn't possible with the current CSS operators you are talking about nth-whatever,
This could however be done with JavaScript... if of course you want to go down that route, the best way to do it would be with <span> tags as then you will have no problems with people who have disabled JS.
It is entirely up to you, but if I were in your position I would just man up and use JS, it is called progressive enhancement and unobtrusive JS, as long as the content is not wrecked if the user disables JS it is acceptable, see here:
http://dowebsitesneedtobeexperiencedexactlythesameineverybrowser.com/

Sadly, there isn't a way to do this with stylesheets. CSS3 provides us with first-letter and first-line, but not first-word, and certainly not first-n-letters.
See also the answers to this question for more: CSS to increase size of first word
JQuery does implement a first-word selector, so if you're prepared to go with the Javascript option, you may be able to do it.
Heh. It seems that JQuery doesn't actually implement it after all. I must have been using a plugin when I saw it.
But here's a link to a Javascript solution that might help: http://www.dynamicsitesolutions.com/javascript/first-word-selector/

Related

Best way to replace a text using CSS [duplicate]

This question already has answers here:
How can I replace text with CSS?
(25 answers)
Closed 9 years ago.
I would like to replace a text say 'company name' in my project. The use-case is to produce documents (after pre-processing) for different companies only by maintaining a different stylesheet for different company.
SEO not much of the importance here.
I am using this approach:
html
<span class="company-name"> YourCompanyName </span>​
css
.company-name{font-size: 0}
.company-name:after{
content: "New Company Name";
font-size: 14px;
}​
and here is the jsFiddle http://jsfiddle.net/cN9gZ/
so here is my quick question: Is there any better way of doing the same thing, using css only?
If you really need to do such things in CSS, the following is a little more logical and a little less risky (with the Usual CSS Caveats in mind):
<style>
.company-name:after{
content: "New Company Name";
}​
</style>
<span class="company-name"></span>
That is, use an element with empty content, so you don’t need any trick to hide the dummy content.
CSS really isn't designed for this kind of thing. You'd be better off using Javascript, or even better, just altering the HTML code itself.
There really isn't any other way to do what you're asking in CSS other than the way you've done it: The content property isn't available in most CSS styles, because CSS isn't intended for placing content.
Is there any better way of doing the same thing, using css only?
No. Every other effect would basically result in the same method used: hide the original content and replace it with a pseudo-element (::after or ::before).
Note that search engines are likely to ignore the stylesheet, which could result in some strange search results. It's almost always a better idea to replace fixed content in the markup instead. In almost all cases it will take only a simple find-and-replace. JavaScript and CSS can be deactivated - markup can't.

CSS hacks (tricks)

Sometimes when I see a website I like or sites from respected people, I see the source codes and try to understand them (as we all do).
On Jeremy Keiths site he uses the following code:
[role="navigation"] a {
font-weight: bold;
text-decoration: none; }
I have never seen this before, and a few other times I saw code (which can be considered a "trick") that I had never seen before.
Other than asking what the above code means, my question is - is there any documentation, book or blogs that go through to learn about the advanced/less known CSS "tricks"?
The above targets elements that have a role attribute, such as:
<div role="navigation">
...
</div>
A class would make sense here too, but it's just another way of doing it. Attribute selectors are a standard part of CSS2, but at the time IE6 didn't support them so it hasn't been used much until recently.
There are many other such selectors that have been around for a long time but couldn't be used due to limitations imposed by IE. See Quirksmode for more examples.
That is a CSS attribute selector. It's saying "All <a> tags that are descendents of an element that has an attribute of role with a value of navigation should be styled in the following way ..."
He's using it for accessibility principally, and for styling only secondarily.
If you are looking to learn some of the newest things about CSS, I'd recommend css3.info and css3please.com. The first is a great source of examples of new tricks, and the second one lets you play with the new stuff in the browser. Other than that ... I've found that the best way to learn is to answer questions here (looking things up when you are not sure) combined with reading -- Eric Myers, Paul Irish, Quirksmode -- all of these are good resources for learning things that are new to you.
In this example, the <nav> is wrapped in a <div> and then then assigned a navigation role. The same can be achieved with just
nav a {}
A lot of sites seem to mix a "little" HTML5 with XHTML. I really don't see a reason why they don't use HTML5 "completely". The whole point of HTML5 is to be more semantic and to write less code that's more meaningful.
Some useful links.
http://html5doctor.com/
http://htmldog.com/
http://desizntech.info/2009/03/discover-the-cool-of-css-25-advanced-css-techniques/
As of now, you'll need a bit of javascript to make HTML5 elements work in IE. These links should help
http://html5doctor.com/how-to-get-html5-working-in-ie-and-firefox-2/
http://remysharp.com/2009/01/07/html5-enabling-script/
Role is a new XHTML2 attribute.
http://www.wait-till-i.com/2009/05/16/pitching-a-hack-or-a-product-dos-and-donts/
http://www.w3.org/TR/2008/WD-xhtml-role-20080407/
Cool, which browser did it work in?
http://www.w3.org/TR/2001/CR-css3-selectors-20011113/#selectors
E[foo="bar"]
an E element whose "foo" attribute value is exactly equal to "bar"

Removing a word from a <p> only using css

Due to mod rights on a site, I can only add css (no js etc...). When users input text in a comment box, it saves it and then displays it as a <p>. is there any way through css i can search for a specific word in the <p> tag and remove/censor it?
Thanks
There is no practical solution for that ( You may be able to select elements based on the value and hide them in CSS3 but it wouldn't be cross-browser friendly, if at all possible ). I'm afraid you'll have to use JS/server-side for a real solution.
On the hacky side of things and for IE only, you may be able to use an expression and display:none elements which contain certain strings in their nodeValue, it wouldn't work for modern browsers.
If parent element in this case input field has class or id you can hide elements inside like this
textarea#mytextarea p
display:none;
}
Once upon a time, there was a pseudo-class :contains() in the wonderful spec of CSS3 selectors ... but it disappeared early and afaik well before any implementation.
A JS solution has one problem: search bots and any user without JS (or displaying the source code) will see the f***ing original text :)

What's so bad about in-line CSS?

When I see website starter code and examples, the CSS is always in a separate file, named something like "main.css", "default.css", or "Site.css". However, when I'm coding up a page, I'm often tempted to throw the CSS in-line with a DOM element, such as by setting "float: right" on an image. I get the feeling that this is "bad coding", since it's so rarely done in examples.
I understand that if the style will be applied to multiple objects, it's wise to follow "Don't Repeat Yourself" (DRY) and assign it to a CSS class to be referenced by each element. However, if I won't be repeating the CSS on another element, why not in-line the CSS as I write the HTML?
The question: Is using in-line CSS considered bad, even if it will only be used on that element? If so, why?
Example (is this bad?):
<img src="myimage.gif" style="float:right" />
Having to change 100 lines of code when you want to make the site look different. That may not apply in your example, but if you're using inline css for things like
<div style ="font-size:larger; text-align:center; font-weight:bold">
on each page to denote a page header, it would be a lot easier to maintain as
<div class="pageheader">
if the pageheader is defined in a single stylesheet so that if you want to change how a page header looks across the entire site, you change the css in one place.
However, I'll be a heretic and say that in your example, I see no problem. You're targeting the behavior of a single image, which probably has to look right on a single page, so putting the actual css in a stylesheet would probably be overkill.
The advantage for having a different css file are
Easy to maintain your html page
Change to the Look and feel will be easy and you can have support for many themes on your pages.
Your css file will be cached on the browser side. So you will contribute a little on internet traffic by not loading some kbs of data every time a the page is refreshed or user navigates your site.
The html5 approach to fast css prototyping
or: <style> tags are no longer just for the head any more!
Hacking CSS
Let's say you're debugging, and want to modify your page-css, make a certain section only look better. Instead of creating your styles inline the quick and dirty and un-maintainable way, you can do what I do these days and take a staged approach.
No inline style attribute
Never create your css inline, by which I mean: <element style='color:red'> or even <img style='float:right'> It's very convenient, but doesn't reflect actual selector specificity in a real css file later, and if you keep it, you'll regret the maintenance load later.
Prototype with <style> instead
Where you would have used inline css, instead use in-page <style> elements. Try that out! It works fine in all browsers, so is great for testing, yet allows you to gracefully move such css out to your global css files whenever you want/need to! ( *just be aware that the selectors will only have page-level specificity, instead of site-level specificity, so be wary of being too general) Just as clean as in your css files:
<style>
.avatar-image{
float:right
}
.faq .warning{
color:crimson;
}
p{
border-left:thin medium blue;
// this general of a selector would be very bad, though.
// so be aware of what'll happen to general selectors if they go
// global
}
</style>
Refactoring other people's inline css
Sometimes you're not even the problem, and you're dealing with someone else's inline css, and you have to refactor it. This is another great use for the <style> in page, so that you can directly strip the inline css and immediate place it right on the page in classes or ids or selectors while you're refactoring. If you are careful enough with your selectors as you go, you can then move the final result to the global css file at the end with just a copy & paste.
It's a little hard to transfer every bit of css immediately to the global css file, but with in-page <style> elements, we now have alternatives.
In addition to other answers.... Internationalization.
Depending of the language of the content - you often need to adapt the styling of an element.
One obvious example would be right-to-left languages.
Let's say you used your code:
<img src="myimage.gif" style="float:right" />
Now say you want your website to support rtl languages - you would need:
<img src="myimage.gif" style="float:left" />
So now, if you want to support both languages, there's no way to assign a value to float using inline styling.
With CSS this is easily taken care of with the lang attribute
So you could do something like this:
img {
float:right;
}
html[lang="he"] img { /* Hebrew. or.. lang="ar" for Arabic etc */
float:left;
}
Demo
Inline CSS will always, always win in precedence over any linked-stylesheet CSS. This can cause enormous headache for you if and when you go and write a proper cascading stylesheet, and your properties aren't applying correctly.
It also hurts your application semantically: CSS is about separating presentation from markup. When you tangle the two together, things get much more difficult to understand and maintain. It's a similar principle as separating database code from your controller code on the server side of things.
Finally, imagine that you have 20 of those image tags. What happens when you decide that they should be floated left?
This only applies to handwritten code. If you generate code, I think that it's okay to use inline styles here and then, especially in cases where elements and controls need special treatment.
DRY is a good concept for handwritten code, but in machine-generated code, I opt for "Law of Demeter": "What belongs together, must stay together". It's easier to manipulate code that generates Style tags than to edit a global style a second time in a different and "remote" CSS file.
The answer to your question: it depends...
Using inline CSS is much harder to maintain.
For every property you want to change, using inline CSS requires you to look for the corresponding HTML code, instead of just looking inside clearly-defined and hopefully well-structured CSS files.
The whole point of CSS is to separate content from its presentation. So in your example you are mixing content with presentation and this may be "considered harmful".
In addition to the other answers, another concern is that it violates the recommended Content Security Policy from MDN, https://infosec.mozilla.org/guidelines/web_security#content-security-policy
The justification they use is that inline javascript is harmful, XSS, etc., but it doesn't justify why inline styles should also be disabled. Maybe someone can comment as to why, but until then, I'll just rely on appeal-to-authority and claim: it's a security best practice to avoid inline styles.
Code how you like to code, but if you are passing it on to someone else it is best to use what everyone else does. There are reasons for CSS, then there are reasons for inline. I use both, because it is just easier for me. Using CSS is wonderful when you have a lot of the same repetition. However, when you have a bunch of different elements with different properties then that becomes a problem. One instance for me is when I am positioning elements on a page. Each element as a different top and left property. If I put that all in a CSS that would really annoy the mess out of me going between the html and css page. So CSS is great when you want everything to have the same font, color, hover effect, etc. But when everything has a different position adding a CSS instance for each element can really be a pain. That is just my opinion though. CSS really has great relevance in larger applications when your having to dig through code. Use Mozilla web developer plugin and it will help you find the elements IDs and Classes.
I think that even if you want to have a certain style for one element, you have to consider the possibility that you may want to apply the same style on the same element on different pages.
One day somebody may ask to change or add more stylistic changes to the same element on every page. If you had the styles defined in an external CSS file, you would only have to make changes there, and it would be reflected in the same element in all of the pages, thus saving you a headache. :-)
Even if you only use the style once as in this example you've still mixed CONTENT and DESIGN. Lookup "Separation of concerns".
Using inline styles violates the Separation of Concerns principle, as you are effectively mixing markup and style in the same source file. It also, in most cases, violates the DRY (Don't Repeat Yourself) principle since they are only applicable to a single element, whereas a class can be applied to several of them (and even be extended through the magic of CSS rules!).
Furthermore, judicious use of classes is beneficial if your site contains scripting. For example, several popular JavaScript libs such as JQuery depend heavily on classes as selectors.
Finally, using classes adds additional clarity to your DOM, since you effectively have descriptors telling you what kind of element a given node in it is. For example:
<div class="header-row">It's a row!</div>
Is a lot more expressive than:
<div style="height: 80px; width: 100%;">It's...something?</div>
Inline CSS is good for machine-generated code, and can be fine when most visitors only browse one page on a site, but one thing it can't do is handle media queries to allow different looks for screens of different sizes. For that, you need to include the CSS either in an external style sheet or in an internal style tag.
In-page css is the in-thing at the moment because Google rates it as giving a better user experience than css loaded from a separate file. A possible solution is to put the css in a text file, load it on the fly with php, and output it into the document head. In the <head> section include this:
<head> ...
<?php
$codestring = file_get_contents("styles/style1.txt");
echo "<style>" . $codestring . "</style>";
?>
... </head>
Put the required css in styles/style1.txt and it'll get spat out in the <head> section of your document. This way, you'll have in-page css with the benefit of using a style template, style1.txt, which can be shared by any and all pages, allowing site-wide style changes to be made via only that one file. Furthermore, this method doesn't require the browser to request separate css files from the server (thus minimising retrieval / rendering time), since everything is delivered at once by php.
Having implemented this, individual one-time-only styles can be manually coded where needed.
According to the AMP HTML Specification it is necessary to put CSS in your HTML file (vs an external stylesheet) for performance purposes. This does not mean inline CSS but they do specify no external stylesheets.
An incomplete list of optimizations such a serving system might do is:
Replace image references with images sized to the viewer’s viewport.
Inline images that are visible above the fold.
Inline CSS variables.
Preload extended components.
Minify HTML and CSS.
Personally, I think the hatred of inline css is just ridiculous. Hardcore cult behaviour, people just sheepishly repeat "Separation of concerns!". Yes, there are times where if there is a repeating element and you will need repeated styling to use a class targeted from a CSS file, but most of the time it improves speed of development and CLARITY OF CODE to put the style inline, it's great if I can look at the code and see that there is a custom margin height, it helps me picture the HTML document as a whole, instead of some named class that gives me little insight into which styles will be applied.
So I will be the contrarian here and say that inline css is great and that people who scream at you for using it are just following what they have been told without actually giving it any original unbiased consideration.
Even though I totally agree with all the answers given above that writing CSS in a separate file is always better from code reusability, maintainability, better separation of concerns there are many scenarios where people prefer inline CSS in their production code -
The external CSS file causes one extra HTTP call to browser and thus additional latency. Instead if the CSS is inserted inline then browser can start parsing it right away. Especially over SSL HTTP calls are more costly and adds up additional latency to the page. There are many tools available that helps to generate static HTML pages (or page snippet) by inserting external CSS files as inline code. These tools are used at the Build and Release phase where the production binary is generated. This way we get all the advantages of external CSS and also the page becomes faster.
In addition to other answers, you cant target the pseudo-classes or pseudo-elements in inline CSS
We have created a template-driven artifact generator that provides an include file capability for any kind of text artifact -- HTML, XML, computer languages, unstructured text, DSV, etc. (E.g., it's great for handling common Web or manual page headers and footers without scripting.)
Once you have that and use it to provide "style" tags inside your "head" tag, the "separation of concerns" argument goes away, to be replaced by "we have to regenerate after every change to the template" and "we have to debug the template from what it generates". Those gripes have been around since the first computer language to get a preprocessor (or someone started using M4).
On balance, we think the meta-izing capability of either a CSS file or "style" tags is cleaner and less error-prone than element-level styling. But it does require some professional judgment, so newbies and scatterbrains don't bother.

Adding strong emphasis to an img tag. Semantics

I'm actually coding a website and a doubt came to me. I have a list of images (it's an artist portfolio, so it should be images), some of which have a "Featured" badge. Is it semantically correct to wrap the img into a strong tag instead of using a class="featured"? Will it add strong emphasis to the image?
Reading the W3C spec., it refers strong and em as text-level semantics, but I'm not sure what happens with media like img.
Thank you so much.
I think that's fine. You may already be doing this, but you need to make sure that the ALT text describes why the images has been emphasized. Eg alt="man with dog - featured"
I think that it would be perfectly acceptable to do this and preferable.
First of all, I think the HTML 4 spec allows it. Question is, can you rely on what browser will do with it. I would not take my chances with that.
But at least, in many browsers you can attach formatting to
strong img {
/* mark up for the featured image */
}
And this should then work for all browser that support it.
I wouldn't use the strong tag on images, I am not sure why it would be preferable since it refers to 'emphasized' text only: an aural user agent may use different voices for emphasis, it would be pointless for images.
Why don't you just use a class?

Resources