CSS selector declarations - css

This is such a simple issue but I can't seem to find an exact answer anywhere...
Simply, can I declare attributes on a selector in two different places without overwriting the first attribute declaration?
For example, say I declare an attribute to an element within a CSS file loaded into a page:
.x {margin:2px;}
I then want to declare another attribute within the page dynamically:
.x {padding:2px;}
while keeping the CSS file attributes.
While I appreciate that there are plenty of other ways of doing this, is it correct to do it this way ?

This is fine. You can put declarations is as many different places as you like.

You can, yes. First off, the styles declared in the CSS file included on the page will be applied, then any other styles specified ad-hoc on the page will be applied on top of that.

That will work. Since CSS cascades it will inherit the styles as they go and add them to that class. That's why some sites change as the page loads.

First, to declare a paragraph tag, you wouldn't put a period before it. It should be:
p {padding:2px;}
Secondly, CSS is a cascading style sheet, therefore you can open an element declaration however many times you want. The style properties within it will take the last stated object. IE:
p {padding:2px; border:1px solid #000;}
and then later
p {padding:5px;}
Padding is now 5 px but it retains it's 1px border.

THAT IS BAD PRACTICE!!! I would sugest you to create "switch" class which will change some css attributes, rather than dinamicaly inject it later on the page. So later use it by adding it to element or remove
<style>
.p { margin:2px; }
.addition { padding: 2px; }
</style>
<p class="p">.....</p>
to switch to new style either with jquery on some ajax call or what ever you need.
<p class="p addition">....</p>
to switch off padding just remove "addition" class or "p" class if you want to switch off maring.

Cascading Style Sheets will inherit the styles and what you are doing is totally fine from a specification point of view but might not be considered best practice.
Also be aware of, that if you start overriding other styles the css hierarchy may apply: External > Internal > Inline.
for more information see http://nzwhost.com/article/understanding-css-hierarchy

I think the best way to do it is separate CSS declarations by logic.. layout together, colors together and specific medias (like screen, print) together.

If you want to make it to do it dynamically you can do something like that:
NOTE:
This is a PHP example.
<?php $back = 'image.jpg';
**something else can be executed ie conditionals and
more variables can be added**)
?>
<html>
<head>
<style type="text/css">
btn{
margin:0;
padding:0;
background-image: <?php $back; ?>
height:100px;
width:200px;
display:block;
}
</style>
</head>
<body>
<div>
<div class="btn">Test text</div>
</div>
</body>
</html>
You can add the predeclared variables or sets of the variables into CSS code using PHP. Note that CSS needs to be included in the HTML/PHP file you are working on. Lets say you want to randomly generate the background colour. PHP array (of ie '#CCC') > select values from the array randomly > add the variable into the CSS code. #
In your case you can specify two classes and then select one according to the condition in your dynamic code

Related

Reason for CSS block with no code in?

I'm currently optimising a website's code, the programmer who developed it isn't here.
There is a CSS file with around 1000 lines of code, in this file, there are many blocks with no code inside the curly braces.
For example:
.header{
}
Is there a reason to keep these? Or are they completely useless?
.header{
}
.header .menu_div{
background : black;
color:white;
}
<div class="header">
<div class="menu_div">Menu Div</div>
</div>
The person who has written CSS might have given the hierarchy for .header children. He/She might not have given CSS to parent.
If it doesn't reflect in design after removing it then you can remove it.
They serve no function in the final app, since they do not modify the CSS properties of any HTML elements in any way. The original developer probably added them as he/she defined the classes during development, but they were ultimately unused in the CSS. They can be safely deleted. (It's possible that these classes are used for other purposes such as selecting certain elements in JS, but deleting the empty selectors in the style sheet won't affect that.)
commented out or just remove it, otherwise, it will still try to match those rule. (for every single HTML element will go through all CSS rule to match, try and fail.)
You can remove these empty declarations.
Removing the empty selectors will not cause any changes to your design as they do not have any css rules associated with them. So you can safely remove them if they are empty.

Is there a way to take off the style off a certain table?

I have a css file which styles my tables, although I have one table where I would like to use a different style, or no style? is there a way I can do something like <table style="no-style"> and then it is plain and ignores the CSS?
I have looked but I can not find anything related!
Use class definitions for table properties in your CSS file. Whenever you want them, use with class property.
CSS
table.myClass {
...
}
HTML
<table class="myClass">...</table>
<table class="anotherTableWithAnotherClass">...</table>
CSS are cascading style sheets, they only style an element. Can't manipulate anything. You will need to use JavaScript.
Best way I know of, is to use CSS classes for different styles. And use javascript to switch them or remove them.
You need to explore CSS in more depth, and one thing you might focus on is classes. You can create a "class" of styles, and apply it to a particular HTML element like a table, and not have it affect another table you want to leave "plain."
.foo {
border : 1px solid black;
}
Then apply that class to your HTML element:
<table class="foo">
...
</table>
Another way to approach the problem is with selectors.
No, you cannot take off a style that way – there is no way in CSS to say “don’t apply any of my styles inside this particular element.” You can only override style settings. For example, if you have a setting like * { color: red } in your stylesheet (just a foolish example), you cannot add a rule that would exclude a particular element and make the browser apply its default color inside it. But you can set table#foo * { color: black; } to make all text inside a table with id=foo have the black color.
Overriding overall style settings inside a table that way isn’t trivial, but certainly possible. You just need to be explicit about the style you want; you cannot say “use browser defaults.”
However, there’s an indirect way, in a sense, though it is seldom a good idea: If you put your table in a separate document and embed it via an iframe element, then the table will be displayed according to the CSS code specified for the embedded document, quite independently of the style sheets for the embedding document. At the extreme, if you specify no CSS code for the embedded document, it will appear as per browser defaults (though inside a subwindow, an inline frame, with dimensions set by the embedding document).

Have you ever set a class for your css that uses it multiple times?

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.

How can I apply a CSS class to an element with a given id, without modifying the element?

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?

Can we include common css class in another css class?

I am a CSS newbie. I am just wondering, is that possible to include one common class into another class?
for example,
.center {align: center};
.content { include .center here};
I came across css framework - Blueprint. We need to put the position information into HTML, e.g.
<div class="span-4"><div class="span-24 last">
As such, we will place the positioning attribute inside html, instead of css. If we change the layout, we need to change html, instead of css.
That's the reason I ask this question. If I can include .span-4 into my own css, i won't have to specify it in my html tag.
Bizarrely, even though CSS talks about inheritance, classes can't "inherit" in this way. The best you can really do is this:
.center, .content { align: center; }
.content { /* ... */ }
Also I'd strongly suggest you not do "naked" class selectors like this. Use ID or tag in addition to class where possible:
div.center, div.content { align: center; }
div.content { /* ... */ }
I say this because if you do your selectors as broad as possible it ends up becoming unmanageable (in my experience) once you get large stylesheets. You end up with unintended selectors interacting with each other to the point where you create a new class (like .center2) because changing the original will affect all sorts of things you don't want.
In standard CSS, it's not possible to do this, though it would be nice.
For something like that you'd need to use SASS or similar, which "compiles" to CSS.
This is where the Cascading in Cascading Style Sheets comes in to play.
Think of your html element or widget/module (group of nested html elements) as an object. You know you're going to have objects that share the same properties so you'll want to create a reusable class they can utilize.
.baseModule {align: center;}
Say your module is a message (error, flash...). So you "extend" or "include" your .baseModule class because all messages will be center aligned (see final html example).
.message {border: 1px solid #555;}
Furthermore you want your error messages to have a red background. Additionally you can overwrite the border property from .baseModule.message here if you wanted it to be a different color or something.
.error {background-color: red;}
So now you have a few css definitions that can be reused with ease.
<!-- Regular message module -->
<p class="baseModule message">
I am a regular message.
</p>
<!-- Error message module -->
<p class="baseModule message error">
I am an error message. My background color is red.
</p>
To relate this to your question you'd basically leverage multiple class names for maximum reusability. Granted ie6 doesn't support chained selectors (class1.class2.class3), but it's still a neat trick!

Resources