I am trying to use one CSS class to many DIV. Is it a good practice? or else are there any disadvantages of doing that. because in VS it says "another object already uses this ID", not an error message but a warning.
CSS classes are meant to be reused. CSS IDs are meant to be used uniquely on a component. Are you sure you're using a css class?
There is nothing wrong with styling multiple divs at the same time. This is actually expected and not many people do that. To style all divs;
body {Body Code Here;}
div {Div styling here;}
Styling all div's with one class;
body {Body Code Here;}
div.YourClass {Div Styling Here;}
Notice how there is no space between the div and selector(.) That specifies a class in any div where as div .YourClass will search in all divs for a class. IDs are different than Classes, you can have multiple Classes on the page but only 1 ID on the page. To fix that message, make sure you are using Class instead of ID and search the page for that ID and if it comes up twice or more, thats your problem. Again Classes are reusable and IDs are single-element selectors. Hope I helped!
In css, class is meant to be reused, so it is ok. In case you don't know about id, id in css is meant to be used noce. But nowadays, I've seen few people use class all over place even they just use it once. So, just keep your markup and styling clear, use class or id in your way if you work alone [ personal project ] and keep it persistence when working alone or in a team.
html
<div class="class1 class2">afd</div>
<div class="button class1">asffsdf</div>
css
.class1 { /* styling your class1 here */ }
It is absolutely fine to use the same class for many elements in CSS. Be careful not to do the same for the "id" attribute, which really should only be used for a single element as it is considered a unique ID.
You can use same CSS class for any number of elements, but ID must be unique for each and every element in the page
ID is somewhat different from class. You can have multiple classes on page but ID should only be used once. Do follow best practices :)
i know... this information is not what exactly you want as answer but may be of some little help :)
example:
div.className { } //covers all div with a particular classname
Related
We have a modal and full page view of our application. For the modal, we attach a "modal" class to the body, so that we can select elements based on whether or not they are contained within this "modal" class.
Several of the items we need to target have IDs. Is it bad practice to select these items like so?
.modal #child-element-with-id { ... }
The above works perfectly fine in all the browsers I've tested, but someone on the code review is complaining about it from a code smell perspective.
I know IDs are supposed to be unique and shouldn't be nested, but doesn't this constitute an exception? To me it seems like the cleanest way to target the ID, instead of coming up with separate IDs for modal and full page views.
This will work, yes. However, if you need to reuse this style for multiple elements, you should create a class.
For example if you do:
.modal #child-element-with-id { /* same style */ }
.modal #child-element-with-id-2 { /* same style */ }
.modal #child-element-with-id-3 { /* same style */ }
Then you should be making a class to avoid style duplication.
To answer your question, the jury is still out and you'll have to decide if selecting a nested ID works for your use case :)
The only issue I could see that if you move the ID to a different element, this may cause confusion and be hard to debug, because your CSS expects the ID to be nested in a class.
Styling by ID is generally frowned upon. If you have the opportunity to edit the markup, why not add a class to those elements with IDs?
You may find that once you have introduced a highly specific selector (0, 1, 1, 0) you may end up having to add to it later for something even more specific – this is the scenario we try to avoid.
…instead of coming up with separate IDs for modal and full page views
I would reconsider this setup and add classes onto the elements with ID's. If you are already styling those elements by #id it's quite easy to swap the CSS selector to a class. If you find it's not easy to style those #ids now that they are classes - my point may already be proven :)
Hope that helps!
I was trying to put a image (logo) in the header element provided by HTML5 and I am curious if anyone knows if it is possible to declare a class in CSS something on the lines of header.image?
I tried header.image and it didn't seem to work, however as soon as I had the class named just .headerimage then it seem to be picking up the padding property I was trying to apply.
I'm doing some very basic learning as it's been sometime I picked up HTML code. Please help if your time permits. Thanks
I was trying to put a image (logo) in the header element provided by HTML5 and I am curious if anyone knows if it is possible to declare a class in CSS something on the lines of header.image?
I tried header.image and it didn't seem to work, however as soon as I had the class named just .headerimage then it seem to be picking up the padding property I was trying to apply.
I'm doing some very basic learning as it's been sometime I picked up HTML code. Please help if your time permits. Thanks
This is not the entire HTML/CSScode, but I could manage to take some screenshots. You guys helped me answer some questions and understand how period is not relevant to what I was trying to do.
Screenshot 1: https://skitch.com/android86/fm4r7/dreamweaver ( HTML design view) Screenshot 2: https://skitch.com/android86/fm4fd/dreamweaver ( CSS)
In the screenshot 1, I tried to have the links for website Contact and Login as a part of the Nav tag provided by html 5, however I wanted these to be horizontally next to the hgroup. I assigned a width to hgroup and now I have a lot of space to the right of hgroup however the nav is starting to line up horizontally, is this something I should handle with position or float property in CSS? I tried both in various combinations, I assigned a width to nav in order to fit in the area however it doesn't seems to be working. Any clue? The CSS code is in screenshot 2. After looking at the discussion here I thought using class might not be required instead rather parent child relation might be most relevant. I personally thought and read that one should use id's in CSS when it is a very unique scenario and class when we expect to use a certain thing very commonly, is this parent child relation a way of declaring a class? Thanks everyone.
In CSS, a period without spaces like this.thing means:
select elements that have the class thing but only if they are of type this
Period (.) is a special character in CSS, so you can't name classes with periods. Try an _ or a -.
Actually you can't use period in class names, because it is a class selector. For example, is you have a class "foo" applied to some html element, you can style this element in css linking to it as ".foo".
Example HTML:
<header class="foo">
<img class="bar" src="some/path/here">
Some content here
</header>
Example CSS:
.foo { color: #AAA; }
or
header.foo { color: #AAA; }
In first CSS example the style will be applyed to all elements, wich have class "foo". In the second - to all elements, wich have class "foo" and same time are of "header" type.
Returning to your case, I think the only aim is to apply style to image inside of header element. It can be done different ways:
Use the image class
.bar { width: 100px; }
or more concretely
img.bar { width: 100px; }
Use parent-child relations
header img { width: 100px; }
above will apply styles wich lay inside the header element or in its
children elements
header>img { width: 100px; }
this will be ok only for the direct child of header.
Combine two approaches.
If you know for shure that there will be only one image in header element, I can recommend the approach with ">". Read more about different css selectors, ids and classes. It will do the job.
Assuming your markup looks like this:
<header><img /></header>
The selector you want would be this:
header img {...}
If you really did class your image with class="image" (kinda redundant), then you'd want:
header .image {...} /* note space */
This assumes that the browser supports the html header element. If it doesn't, you'd want to use something like html5shim 1 or modernizer 2
I want to package up a widget to be easily included in an arbitrary project. I don't want to require that the user link to my personally-created style sheet in their host page - I just want the css to be magically injected when they use my code.
I understand that CssResource can go some ways towards this dream, but after scouring documentation I haven't found any reference to natural type selectors. For instance, I want to style the <tr>s in my widget without having to add a class name to each one.
Is this achievable with GWT? GWT's own widgets all come pretty thoroughly styled, but it seems they've added a style class to every single element in the DOM!
You're on the right track - a CssResource or UiBinder's inline <ui:style> will achieve what you're looking for. With regards to styling elements by type instead of class it certainly can be done:
<ui:UiBinder>
<ui:style>
.myTable tr {
color: red;
}
</ui:style>
<table class="{style.myTable}">
<tr><td>A row!</td></tr>
</table>
</ui:UiBinder>
GWT, however, has a reason for preferring explicit class names over descendent selectors: if you have the above style, for example, every time the browser renders a <tr> element it has to walk up the DOM and visit all of the ancestors of that element to see if any of them have the .myTable class. If your application uses a lot of <tr> elements (<div> would be a better example here), most of which don't have a .myTable ancestor, it can cause a noticeable decrease in rendering performance.
I think, I would use UiBinder, and only give the outermost element a class name, like this:
<ui:style>
.outer tr {
...
}
</ui:style>
<div class="{style.outer}">
...
<tr>...</tr>
...
</div>
Now you don't have to assign a class to each tr - you just use the selector ".outer tr", which only applies to <tr>s within some element marked with the class attribute {style.outer} (doesn't have to be a <div> by the way). The same principle would work without UiBinder, too, of course.
Ok I didn't really understand the whole question, maybe still don't but I think your asking for a way to "bulletproof your CSS" from specificity - I get the CSS bit now after seeing the other answers
Unique classnames (a bit of a oxymoron is CSS terms but heyho) added to everything are advised by most to make sure the site (not your) CSS fails as quickly as possible no matter how specific (weighted) their rules are
But you can make you widget CSS completely unique, i.e. so that it cannot be overruled by a site CSS,no matter how many ID's are in their selectors, without very much ado and without specifically classifying everything
e.g. #mywidget div {} could be overruled by site CSS very easily #wrapper #content div {} will do it - your div is a descendant of those two ID's too, and as their rule had 2 ID's versus your one, your CSS will lose - it's impossible to guess every permutation of a site CSS so the easiest thing is to add all those "extra" classes and why YUI and Blueprint are as they are
however if you write your CSS: #mywidget>div {} yours will likely always win, as never in their CSS will a div they're targetting likely be an immediate child of your widget ID (unless of course they choose to customise yours, which they could do with the 'class everything' method too)
so to bulletproof your CSS without adding classes to everything .. I assume your widget already has a unique iD wrapper? then if you don't already have an inner div wrapper, add one, it doesn't need to have a class but giving it one will place an extra layer of bulletproofing on this technique.
then prefix all your rules with #mywidget>div.myclass e.g. #mywidget>div.myclass td {} - the sites own rules, no matter how heavily weighted (many ID's and classes in a selector make a selector more weighted) theirs will fail as soon as they cannot match that particular combination - so your tr's are safe from site CSS takeover ;)
add one div or class and search and replace your CSS to add the prefix to everything.. as for how to package I've no idea
I always was told to take out multiple properties in your css that you use more then once, and add them all in one rule. Like below. (please excuse the poor example)
I always seen this:
.button, .list, .items { color: #444; }
With multiple rules, can't that leave a lot of clutter?
Only in css tutorials and examples Ive seen this:
.someColor { color: #444; }
And in the css, just add another class of '.sameColor'. (div class="button someColor")
I've never seen this and feels like it would leave less clutter in your CSS. Would this be okay? Or do you think it could leave with more clutter in your HTML ?
Try to name your classes independently of their visual effect. It is a nature of CSS to play with the design and layout without having to change the HTML. Class names such as .someColor or .left-sidebar are a bad practice. Colors and position can change.
And also apply rules to semantic HTML elements rather than adding classes on all different divs and spans. It should be obvious, although many people get this wrong.
CSS is a limited set of rules and that makes it a perfect creativity stimulator.
It's all based on personal preference. I've tried both methods and prefer the second method you listed, except with more generic class names such as middleParagraph or headerGraphic so it applies to an area rather than a specific color because colors can change.
Good classnames and IDs are the first place you should optimize. THEN move onto multiple class names.
Multiple classnames can help out quite a bit though, consider:
<div class="leftColumn">Left</div>
<div class="rightColumn">Right</div>
<div class="middleColumn hasLeft hasRight">I have padding-left of 210px and padding-right of 210px</div>
<!-- alternatively, you could have -->
<div class="rightColumn">Right</div>
<div class="middleColumn hasRignt">I have padding right of 210px</div>
<!-- or -->
<div class="leftColumn">Left</div>
<div class="middleColumn hasLeft">I have padding left of 210px</div>
<!-- or -->
<div class="middleColumn">I have no padding</div>
and your css
.leftColumn { width:200px; float:left; }
.rightColumn { width:200px; float:right; }
.middleColumn.hasLeft { padding-left:210px; }
.middleColumn.hasRight { padding-right:210px; }
The result is floated right/left columns and the center area compensates for them with padding. This means you can style your middleColumn how you want to (e.g. .middleColumn .otherCoolSelector ).
It's perfectly acceptable to apply multiple classes to HTML elements. The trick is to be judicious; I usually find that when I do this, the additional classes are additions or exceptions to the basic styling being applied. For example, here are some classes I occasionally add to an element that already has a class:
error -- to style the current element if the user entered invalid data
first -- to style the first element in a list or in a table row, e.g. to suppress padding-left
last -- to style the final element in a list or in a table row, e.g. to suppress margin-right
even -- to apply zebra-striping to alternate elements
hidden -- to hide an element if it's not currently relevant
These extra classes are typically generated dynamically with a server-side language like ASP.NET or PHP. They can also be added or removed on the client side with JavaScript, esp. with a library like jQuery. This is especially useful to show or hide elements in response to an event.
There are a lot of good answers here. The trick is finding out which one fits your situation best.
One thing to consider is your markup size. In a high-traffic situation, your markup size is critical to the speed of your page loads...every byte counts. If this is the case for you, then you may want to create more CSS classes and put less in your markup. That way, the client is caching more and your website is serving up less.
What you're suggesting is a bit like an in-line style, e.g. style="color:#444". So if you want to change the color of your element you'd have to make a change to the html, which means you've defined style as part of your content. Which is exactly what css is supposed to avoid.
Imagine if you'd included 'someColor,' multiple times across multiple html files and you decide some of these elements shouldn't have 'someColor,' after all, you've got a lot of files to go through.
I'd probably avoid the list option too, if I'm making a component, say a button, I want to find .mybutton class in my css file and see all the rules for that component, without having to go through all sorts of unhelpful global classes. Also if someone comes along and changes the color in our global class he may break my button, where as if the button controlled it's own styles it can't be broken in this way.
I have a page that looks like: <div id="header">...</div><div id="navigation">...</div> similar for body and footer.
I'd like to use a grid system to style the page, all of which seem to rely on giving the divs mentioned a class based on their presentation. But I don't want to do this (and can't because of the way the markup is generated)
Is there a way to do this, without just putting a class on the divs? I could copy the details of the class desired to a stylesheet mentioning the divs by id, but that feels wrong.
Edit to clarify:
The OP wants to avoid adding class="grid_3" etc. to the HTML, but also doesn't want to add #header { width: 960px; margin: 0px; } (which I think is okay) – Rory Fitzpatrick 3 hours ago
Exactly, I don't want to put presentation information in my HTML, but I hoped I wouldn't have to just take the css classes that make up the grid system apart, and apply the relevant parts (like margin:0px and width:960px), since that is bad from a maintenance and reuse angle.
So, I'll look at an automated system for doing what I need, unless there is an answer to how do you apply a css class to an HTML element, using css, without adding class="blah" to that element? Because that doesn't seem like a crazy thing to want to do to me.
Well if you use blueprint-css as your grid system you can use the compress.rb to assign the rules for given bp framework classes to a specific selector of your choice like #footer or what have you. for example in your project yaml you could have:
semantic_styles: # i dont think this is the right key definition but you get the idea
'#footer,#navigation': ['span-12','clearfix']
'#footer': ['push-1']
# etc...
Then when you call compress.rb on the project file it will roll up the necessary declaration from the array of selectors on the right into the selector on the left producing:
#footer,#navigation{ /* composite delcalrations from .span-12 and .clearfix */}
#footer {/* declarations from .push-1 */}
But all in all this is essential an automation of copying the declarations to a separate file that you say seems "wrong". But i mean other than doing this (automated or manually) i dont see what the possible options could be.
I'm not sure I understand the question. Why don't you want to put styles in a stylesheet and reference them by id?
#header{
position:relative;
...
}
I have the same reservations about grid systems, adding class names just goes against separating markup and style (but is often sacrificed for productivity).
However, I don't see what's wrong with setting the right column widths and margins using your own CSS. You could have a specific site.grid.css file that contains only selectors and widths/margins for the grid. I think this is perfectly okay, it's just a way of using CSS like variables. For instance, all 3-column elements would appear under
/* 3-column elements, width 301px */
#sidebar, #foobar, #content .aside {
width: 301px;
}
Then rather than adding class="grid_3" to your HTML, you just add the selector to the CSS.
You might want to consider using the class names initially, until you're happy with the layout, then convert it into CSS selectors. Whichever works best for your workflow.
If you don't have access to the markup you must either copy the styles, referencing the ids, or maybe you can apply the class to the ids using javascript?