Using CSS to style labels pointing to elements with a certain attribute - css

I am using unobtrusive validation in an ASP.Net MVC3 app. I would like to style the label elements associated with required elements in a certain way.
My concern is not to tweak the visual indicators around the required field itself, but to modify the appearance of a different element based on the attributes of this element.
Now, I believe it would be possible to style the elements themselves just with CSS by using a CSS rule whose selector applied to all elements with the [data-val-required] attribute. It would look something like this:
input[data-val-required] { color: red; }
But is it possible to style the labels? To say (with a CSS selector) that a CSS rule applies to all label elements whose for attribute points to an input element that has the [data-val-required] attribute?
I'm currently applying styling with a little bit of jQuery currently, and it works nicely. But it would be even nicer if I could just set up a CSS rule and be done with it.

You can't get there from here. As #vlgalik says, the only CSS options are selectors that are 1) not supported on some browsers, and 2) have limited ability to find other elements, forcing you to construct your markup to comply.
So, your current solution -- use JQuery to find the labels and their corresponding inputs -- is your best bet.
However, I'd approach your jQuery solution in the opposite direction: first find all the inputs matching input[data-val-required], and for each of those, get its ID, then select the corresponding label: label[for="<id-from-input>"] -- that seems like it will be less work. But that's an optimization; if you don't have a lot of labels and inputs on the page, either direction will work fine.

This jsfiddle example is using CSS3 selectors, but there is a downside that the label must follow after input element in the HTML (can be placed before using addition CSS like in example).
Much simpler and effective would be to give the label element class attribute like:
<label class="required">
or to place the label input pair in div element:
<div class="required">
<label for="input1">Label 1</label>
<input id="input1" ... />
</div>
and apply desired CSS styling by simply using:
.required label {
...
}

The example you gave should be very close to what you would need to do. Try using this:
input[for=data-val-required]{}
This selector is based off of the attributes of a given tag. That should give you what you are looking for.

Related

Css3 select all input fields residing in a class but not ones containing a specific data attr not working

I have an issue with my CSS3 selection. I have a table, inside the table are input elements (text) 3 for each row. Each one in that row containing a specific data-attr. Now I have a css selection for selecting all but ones containing the data-attr labeled data-sl="inputs-calc-sub-label" and data-sl="inputs-calc-add-label" (for now) I am just trying to change the background. But here is my selection
.getLength > input:not([data-sl='inputs-calc-sub-label'])
But it applies styles to all elements. Again I want to ignore the input with that data-attr. How can I do this? What am I doing wrong? I am working on the latest version of chrome right now. Maybe the version before. Can someone help me with this? All I want to do is select all but the ones containing the data-attr.
We can't really help without seeing your corresponding html to this css, however I think the problem is with the css selector you are using.
The element>element selector is used to select elements with a specific parent.
Note: Elements that are not directly a child of the specified parent, are not selected.
therefore in your example
the .getLength must have a direct child of input
<td class="getLength"><input type="text" data-attr="normal"</td>
here's a fiddle for more help
https://jsfiddle.net/7s1nbarh/1/
.getLength:not([data-sl='inputs-calc-sub-label']) {
background-color: lightblue;
}
input {
background-color: black;
}
<input class="getLength"/>
<input class="getLength" data-sl='inputs-calc-sub-label'/>
If you want to keep the inputs the way they are, without adding in unnecessary parent elements, simply change the CSS selector to act directly upon the elements of the class, and not their children.

CSS "select" text spacing

I've the following issue: there is <select> option in my website, and it have 3 different logic data in one <option> which needs to be separated like this:
I was thinking about word-spacing, but as you can see there is some spaces in last data, so it will not work. :after and :before will be not good either. And as I know there is no way to insert <div> or <span> inside <option>. I was wondering is there any other ways to implement this, because currently I have only bad solution with .
If you want to present option elements in a tabular manner, as it seems, then the clumsy way of using no-break spaces and a monospace font seems to be the only way.
Consider using a different approach, such as a set of radio buttons with associated labels and other texts. Then you can use a table element.
I did a few changes to a library called Chosen ... I think it's just what you need.
DEMO
This is the usage in JS:
$('.chosen-select').chosen({
width: '250px',
html: function(option){
return $(option).data('html');
}
});

CSS - Selector of label for type?

I'm using this post explaining how to add a selector of a label for a given element. However, I'd like to use it to select all labels for a given type (specifically, the type radio). Trying:
label[for=input[type="radio"]] {
/* Styles */
}
and
label[for=[type="radio"]] {
/* Styles */
}
does not work and I'm not sure what I'm doing wrong or how to do it right. Can someone explain the solution to me? Thank you much!
Unfortunately, what you're wanting can't be done using current CSS3 selectors.
There are plans for this feature to be included in CSS level 4 selectors, but the spec for this is not yet finalised, and certainly not implemented in any current browsers.
The idea is for a selector that would look something like this:
label /for/ [type="radio"] {
/* styles */
}
But that's for the future, not for now. Sorry.
You can read about it here: http://css4-selectors.com/selector/css4/reference-combination/
In the meanwhile, if you need this kind of thing, you will need to make sure you structure your HTML such that the elements can reference each other using current CSS selectors.
For example, if they're next to each other, you could use this:
label + input[type="radio"] { .... }
That's as close as you'll get for the time being.
You should use special classes for those labels instead. You cannot style a parent element based on its children's atttributes in CSS [presently].
<label class='radio'><input type='radio'></label>
Your stylesheet would say
label.radio{
/* add styles here */
}
First - a correction
The for attribute is only to be tied to an id of the form element it is associated with, so you are misusing the attribute for what you are seeking to do. The design of for is to tie it to one specific element in the form. So something like this:
<label for="RadioChk">My Radio Button</label><input id="RadioChk" type="radio" />
So the for is not the solution to just checking for a type.
Second - the only CSS only solution
The only clean way it can be done with pure CSS is if your elements are ordered like so (label following the input):
<input type="radio" /><label>My Radio Button</label>
Which then allows this css to select:
input[type=radio] + label {
/* styles */
}
If that cannot be done, then I would go with AbsoluteƵERØ's solution of using a class.
What you are trying to do is not possible (with CSS alone anyway). The [attribute=value] syntax works by checking the value of the attribute for that specific element. Thus, for=[type="radio"]] is looking for something like <label for='[type="radio"]'> (if the syntax is even valid).
Try this:
input[type=radio]
{
CSS goes here
}

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.

Resources