Are .css files always needed? Or may I have a .css "basic" file and define other style items inside the HTML page?
Does padding, borders and so on always have to be defined in a .css file that is stored separately, or may I embed then into an HTML page?
It is technically possible to use inline CSS formatting exclusively and have no external stylesheet. You can also embed the stylesheet within the HTML document. The best practice in web design is to separate out the CSS into a separate stylesheet. The reason for this is that the CSS stylesheet exists for the purpose of defining the presentation style of the document. The HTML file exists to define the structure and content of the document. And perhaps you may have JavaScript files which exist to add additional behavior to the document.
Keeping the presentation, markup, and behavior separate creates a cleaner design.
From a practical perspective, if you have a single external CSS stylesheet the browser can cache it. If multiple pages on your site have the same look and feel, they can use the same external stylesheet which only needs to be downloaded once by the web browser. This will make your network bandwidth bills lower as well as creating a faster end user experience.
You can include CSS inside an HTML page. It goes within the <style> tag, which goes within the <head> tag:
<head>
<style type="text/css">
body{ background-color: blue; }
</style>
</head>
Note, however, that it is best practice to use .css files.
Putting rules into the HTML page gives them greater "specificity," and therefore priority, over external rules. If several CSS rules conflict, ID wins over class, and inline styles win over ID.
<head>
<style type="text/css">
span.reminder {color: blue;}
span#themostimportant {color: red;}
</style>
</head>
<body>
<span class="reminder" id="themostimportant">
This text will be red.
</span>
<span class="reminder" id="themostimportant" style="color: green;">
This text will be green.
</span>
</body>
You can define CSS at three levels, externally, embedded in the document (inside a <style> tag), or inline on the element.
Depending on your needs, you might use all three, as a rule of thumb external sheets are good for overall styles as you can apply them globally. If you have specific cases that you must handle you can then use the other levels.
You can do either. However, by shifting your CSS out to a separate file, it can be cached. This reduces the amount of data that you need to transmit for each page, cutting down on bandwidth costs, and increasing speed.
You don't have to keep your CSS in an external file, no. What you're asking about is "inline" css: including style directives directly within the page itself via <style> blocks.
There are times where that may makes sense, in moderation, but in general it's not the way you want to go. Keep your CSS isolated in an external stylesheet makes it much easier to maintain both your HTML and your styling, especially as a project scales and changes hands.
One big advantage of having CSS in an external file is that one rule can apply to many different pages. Here is a contrast of three CSS approaches:
Inline Styles - to change the color to blue, you have to find each place that the red style exists - maybe on many pages.
<span style="color: red;">This is a warning.</span>
Page Styles - this allows you to label what something is - in this case, a warning - rather than what it looks like. You could change all the "warnings" on the page to instead have a yellow background by changing one line of code at the top of the page.
<head>
<style type="text/css">
.warning {color: red;}
</style>
<body>
<span class="warning">This is a warning.</span*>
External File - same code as above, but the fact that the style info is in a separate file means that you can use the "warning" class on many pages.
You can use anywhere, css files are not a requirement. using css files however is recommended as it makes the site easier to maintain and change in the future
Have to? No. You can do it however you prefer.
Generally it's better stype to keep your CSS out of your html whenever possible though.
That's what i usually do.
At least at the begining. When a page design gets close to final, I move most things to the 'main' style.css
I prefer to keep styling in CSS as it separates view from presentation, allowing me to swap between presentations fairly easily. Plus it keeps all the information in one place instead of split between two places.
Css can improve performance, because they are cached from browser, and pages are smaller!
Use an external file for all styles that are used sitewide, document stylesheet for styles that are only used on that page and use inline styles when the style only affects that single element.
External stylesheets do not always lower bandwidth. If you put every style for every page in your site into one giant css file, your users incur a large initial download even if they only visit your homepage once ever.
Thoughtful division of your styles into a main.css with the most common styles and then into additional stylesheets as users drill down deeper can help to make the downloads smaller for some paths through the site.
Related
I want to preface this with the understanding that I'm aware this is sub-optimal for web design but my hands are tied.
I am working within my organization of my company to add documentation in an html format through a form field.
The html I am coding will be, essentially, inserted into the rest of the page's body and I don't have access to the style sheets or to the style tags in the header.
Right now I am embedding my css in the html but I would like to have a little bit cleaner code so, to the question at hand.
Is there a way to embed a second section under style tags where I can define IDs and classes in the body. I've tried to just put style tags in the body but it's conflicting with the header of the overall page.
Please let me know if more clarification is needed and thank you, before the fact, for any help!
Is there a way to embed a second section under style tags where I can define IDs and classes in the body. I've tried to just put style tags in the body but it's conflicting with the header of the overall page.
Multiple style tags are ok. When you have multiple style tags, the cascade rule applies, so you just need to make sure your selectors have higher specificity than the page's default style.
The second issue is of where you put the style tag. Strictly speaking, the <style> tag is supposed to go in the <head>, but in practice all browsers will apply <style> anywhere in the page. Having style in body, the page will not validate, however it will work fine.
I'm doing this, defining a <style>...</style> block within the HTML and it's working fine across the browsers I've tested (Firefox, IE10, Chrome).
What do you mean by "it's conflicting with the header of the overall page"? Is there a PHP error saying that their is an output and header can't be set (so the system seems like using ob_start/ob_flush)
Normaly following should work:
<body>
<style>
.class {
border: 1px solid #000;
}
</style>
</body>
Maybe some of the CSS given in the header using !important and make it impossible to overwrite or you just missing some attributes so it looks like you not changing anything at all.
You probaly could use this technik to load stylesheet dynamically into the header: How to create a <style> tag with Javascript
var ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = "style.css";
document.getElementsByTagName("head")[0].appendChild(ss);
or you creating a style element and fill it with styles, but this will be more complex, because you have to do it completly with Javascript and at some point it sucks.. also to have it clean a extra file would be perfect solution.
I like a directoy css or stylesheets (based on the directory pattern I am following, either short terms like img, css, js or long terms like scripts, images, stylesheets) and a default.css inside. It's your decision what you call it.
Okay, this is a gross oversimplification, but I have a javascript application to help people develop webpages. It has its interface superimposed over the page that is being developed, and it all works fine, apart from one thing.
If the div class used in the interface is used by the webpage that is being developed, the interface' embedded stylesheet overrides the properties of the webpage!
This happens on jsfiddle, the embedded css is takes precedence over the external css.
JSfIDDLE
external css:
.color {
color: green;
}
Index.html:
<style>
.color {
color: blue;
}
</style>
<div class="color"> Text to be coloured </div>
When run, the text is blue. If someone could make the text turn green, I think it would demonstrate how to overcome the problem.
Obviously, one way to fix this would be to change the interface classes and rules to something like this:
<style>
.color_interface {
color: blue;
}
</style>
<div class="color_interface"> Text to be coloured </div>
And make them unique, but the project has hundreds of css rules, and I'm just wondering if there's a better way, and a safer way (there's still a small chance someone has a rule "color_interface") to do nullify css rules, so they won't contaminate the page.
I'm thinking the only way to do it is probably a 'reset' stylesheet concerning my rules, setting them all back to their defaults. Is there a way to do this dynamically with jquery, maybe?
What you're witnessing is CSS by design. Specifically, specificity.
If your goal is to release some kind of library that can be used publicly and you want to avoid naming conflicts, I think a fair practice is to simply namespace your selectors, e.g., .starkers-color { color: blue; }. That won't necessarily avoid specificity issues, but it should prevent against having your selectors overridden by implementors.
If you inspect the JSFiddle page you'll see that the reason for it not working is that your inline style definition is placed in the body where it has no effect.
The CSS rules you specify is instead placed as an inline style in the head element.
To your problem:
Again, referring to JSFiddle, would it be possible to load the page in development inside an iframe? This would mean you get the separation you require.
This is because the order of the CSS when rendering. Your include is at the top of the page but your style tags are below that, meaning your style tags will alway take precedence over you include at the top. You could try adding an important to you css includes but this is majorly hacky and could create a whole load of new issues.
I have been told, as well as read that using the style attribute in html is considered bad/sloppy/poor form. Further, that all rendering specific bits should be divorced into css and other parts as appropriate. I am trying to understand why exactly this is.
I can see why you might want to keep the HTML a pure semantic DOM, that speaks about the structure of the document, but for practical pages, the importance is that the page looks right and functions appropriately.
Is there some more compelling reasons for this separation?
Separation of concerns This makes it easy to replace the styles without changing the markup, or vice versa. Plus you can have one person working on CSS and another working on content
Don't Repeat Yourself You can apply a style to many elements without having to repeat it over and over. Smaller pages means quicker load times using less bandwidth. Plus it's easier to modify later, because you can change it in one place in one file, instead of many places in many files.
Cachability If the same style sheet is used on every page of your site, browsers can download it once and then cache it, instead of downloading the styles with the content of every single page. And they won't have to re-download it whenever the content of those pages changes.
Multiple Versions It is easy to create multiple versions of the visual layout and appearance of your site since you just need to swap out the stylesheet file to change the appearance of every page. For instance, you can create a white-label version of a web application which your partners can re-skin to match their brand. See CSS Zen Garden for some great examples of how flexible this approach can be.
Start with this code:
<ul>
<li style="color: blue;">One</li>
<li style="color: blue;">Two</li>
<li style="color: blue;">Three</li>
<li style="color: blue;">Four</li>
</ul>
Let's say that today, you decide to change the link color to red. Since these styles are inline, you tediously have to walk through each element and change the style attribute. Imagine doing this for 10, maybe 20 HTML pages and you'll see why this becomes a problem.
Using a stylesheet separates the content:
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
From the style:
ul li {
color: blue;
}
Had you used a stylesheet from the beginning, changing the color is as simple as changing blue to red in your stylesheet.
Aside from making the document easier to style, there's also selector specificity. Imagine that you inherited the first code chunk from a previous developer and would like to change the color again, but you (being a nice developer) prefer stylesheets:
ul li {
color: red;
}
You'll soon become frustrated and resort to using !important, as your selectors can't override the inline styles.
CSS should be another file included in HTML because, if you want to change one style of an element that is included in more than one pages you will just change one style from CSS and the changes will be applied to all of the files. If you have the style in HTML, you would need to go on the pages one by one and change the styling. Its a good template building practice.
By separating markup and css. You can use css to change the look of everything, without affecting the markup.
Benefits include:
Creating different designs for the same html.
Dividing work within a team. One front-end developer can focus entirely on the css.
Back-end developers, do not have to hassle with the css.
Easier to change the look in the future.
Easier to migrate the html-markup to a new platform or content management system in the future.
Does placement of:
<style type="text/css">
...
</style>
matter? Is there any difference if I place it inside page div, or inside body? I recently found out it matters with javascript. I had some problems with my CSS also (jQuery Mobile). Could it be the reason?
The style element should apply to the whole document, wherever it is placed, however it is common practice to always put it in the head element. I would not be surprised if browser handling is a bit flaky if you put it in other places.
Note that html5 allows you to specify the scoped attribute for the style element, which means that it will only apply to the parent element of the style element and all its children.
By the way, usual practice is to put the css in a separate file and use the <link> tag to include the CSS in your document. This way you can share the css across multiple pages.
The placement matters as regards to order of style sheets. When resolving conflicts between style sheets, then at the last step, when other things are equal, the rule that comes last wins. Thus, it matters how the style element is placed relative to other style element and to link elements that refer to style sheets. (It does not matter as regards to style attributes in elements, since other things can’t be equal: the attributes win, by specificity.)
It also matters in validation: a style element is not valid except within a head element. Browsers don’t care about this, though.
JavaScript code can of course be dependent on the placement of the elements it processes. It’s all up to the code.
Ideally it should not, but don't do it, it is just bad practice, plus makes your code looks messy
To answer the question directly, usually if you're placing your code straight in the page, you'll be placing it in the <head> of the page. Should work regardless of where you put it, but <head> is common practice. Not sure what exactly your goal is, but for email, I typically split it up into inline styling (placing relevant code in the HTML tags themselves, like <p style="line-height:1.4em;">).
If you're working on webpages, though, unless there's a particular reason to have the CSS embedded in the code of the page itself, it's almost always better (and it considered best practice) to link to an external stylesheet in between your <head> tags (<head> <link rel="stylesheet" href="[YOUR STYLESHEET]" type="text/css"> </head>). It keeps your HTML cleaner, and helps with the separation of markup (HTML), styling (CSS), and functionality (JavaScript).
Hope that answers your question somewhat, haha.
What is the preferred method for setting CSS properties?
Inline style properties:
<div style="width:20px;height:20px;background-color:#ffcc00;"></div>
Style properties in <style>...</style> tags:
<style>.gold{width:20px;height:20px;background-color:#ffcc00;}</style><div class="gold"></div>
Style rules can be attached using:
External Files
In-page Style Tags
Inline Style Attribute
Generally, I prefer to use linked style sheets because they:
can be cached by browsers for performance; and
are a lot easier to maintain for a development perspective.
However, your question is asking specifically about the style tag versus inline styles. Prefer to use the style tag, in this case, because it:
provides a clear separation of markup from styling;
produces cleaner HTML markup; and
is more efficient with selectors to apply rules to multiple elements on a page improving management as well as making your page size smaller.
Inline elements only affect their respective element.
An important difference between the style tag and the inline attribute is specificity. Specificity determines when one style overrides another. Generally, inline styles have a higher specificity.
Read CSS: Specificity Wars for an entertaining look at this subject.
Here's one aspect that could rule the difference:
If you change an element's style in JavaScript, you are affecting the inline style. If there's already a style there, you overwrite it permanently. But, if the style were defined in an external sheet or in a <style> tag, then setting the inline one to "" restores the style from that source.
It depends.
The main point is to avoid repeated code.
If the same code need to be re-used 2 times or more, and should be in sync when change, use external style sheet.
If you only use it once, I think inline is ok.
To answer your direct question: neither of these is the preferred method. Use a separate file.
Inline styles should only be used as a last resort, or set by Javascript code. Inline styles have the highest level of specificity, so override your actual stylesheets. This can make them hard to control (you should avoid !important as well for the same reason).
An embedded <style> block is not recommended, because you lose the browser's ability to cache the stylesheet across multiple pages on your site.
So in short, wherever possible, you should put your styles into a separate CSS file.
From a maintainability standpoint, it's much simpler to manage one item in one file, than it is to manage multiple items in possibly multiple files.
Separating your styling will help make your life much easier, especially when job duties are distributed amongst different individuals. Reusability and portability will save you plenty of time down the road.
When using an inline style, that will override any external properties that are set.
I agree with the majority view that external stylesheets are the prefered method.
However, here are some practical exceptions:
Dynamic background images. CSS stylesheets are static files so you need to use an inline style to add a dynamic (from a database, CMS etc...) background-image style.
If an element needs to be hidden when the page loads, using an external stylesheet for this is not practical, since there will always be some delay before the stylesheet is processed and the element will be visible until that happens. style="display: none;" is the best way to achieve this.
If an application is going to give the user fine control over a particular CSS value, e.g. text color, then it may be necessary to add this to inline style elements or in-page <style></style> blocks. E.g. style="color:#{{ page.color }}", or <style> p.themed { color: #{{ page.color }}; }</style>
Whenever is possible is preferable to use class .myclass{} and identifier #myclass{}, so use a dedicated css file or tag <style></style> within an html.
Inline style is good to change css option dynamically with javascript.
There can be different reasons for choosing one way over the other.
If you need to specify css to elements that are generated programmatically (for example modifying css for images of different sizes), it can be more maintainable to use inline css.
If some css is valid only for the current page, you should rather use the script tag than a separate .css file. It is good if the browser doesn't have to do too many http requests.
Otherwise, as stated, it is better to use a separate css file.
You can set CSS using three different ways as mentioned below :-
1.External style sheet
2.Internal style sheet
3.Inline style
Preferred / ideal way of setting the css style is using as external style sheets when the style is applied to many pages.
With an external style sheet, you can change the look of an entire Web site by changing one file.
sample usage can be :-
<head>
<link rel="stylesheet" type="text/css" href="your_css_file_name.css">
</head>
If you want to apply a unique style to a single document then you can use Internal style sheet.
Don't use inline style sheet,as it mixes content with presentation and looses many advantages.
Inline CSS have more precedence than CSS within tag.
There are three ways to add CSS.
Read this article on w3school, very informative.