Can I apply a CSS style to an element name? - html

I'm currently working on a project where I have no control over the HTML that I am applying CSS styles to. And the HTML is not very well labelled, in the sense that there are not enough id and class declarations to differentiate between elements.
So, I'm looking for ways I can apply styles to objects that don't have an id or class attribute.
Sometimes, form items have a "name" or "value" attribute:
<input type="submit" value="Go" name="goButton">
Is there a way I can apply a style based on name="goButton"? What about "value"?
It's the kind of thing that's hard to find out because a Google search will find all sorts of instances in which broad terms like "name" and "value" will appear in web pages.
I'm kind of suspecting the answer is no... but perhaps someone has a clever hack?
Any advice would be greatly appreciated.

You can use the attribute selector,
input[name="goButton"] {
background: red;
}
<input name="goButton">
Be aware that it isn't supported in IE6.
Update: In 2016 you can pretty much use them as you want, since IE6 is dead. http://quirksmode.org/css/selectors/
http://reference.sitepoint.com/css/attributeselector

Text Input Example
input[type=text] {
width: 150px;
}
input[name=myname] {
width: 100px;
}
<input type="text">
<br>
<input type="text" name="myname">

You can use attribute selectors but they won't work in IE6 like meder said, there are javascript workarounds to that tho. Check Selectivizr
More detailed into on attribute selectors: http://www.css3.info/preview/attribute-selectors/
/* turns all input fields that have a name that starts with "go" red */
input[name^="go"] { color: red }

For future googlers, FYI, the method in the answer by #meder , can be used with any element that has a name attribute, so lets say theres an <iframe> with the name xyz then you can use the rule as belows.
iframe[name=xyz] {
display: none;
}
The name attribute can be used on the following elements:
<button>
<fieldset>
<form>
<iframe>
<input>
<keygen>
<map>
<meta>
<object>
<output>
<param>
<select>
<textarea>

Using [name=elementName]{} without tag before will work too.
It will affect all elements with this name.
For example:
[name=test] {
width: 100px;
}
<input type=text name=test>
<div name=test></div>

If i understand your question right then,
Yes you can set style of individual element if its id or name is available,
e.g.
if id available then u can get control over the element like,
<input type="submit" value="Go" name="goButton">
var v_obj = document.getElementsById('goButton');
v_obj.setAttribute('style','color:red;background:none');
else if name is available then u can get control over the element like,
<input type="submit" value="Go" name="goButton">
var v_obj = document.getElementsByName('goButton');
v_obj.setAttribute('style','color:red;background:none');

input[type=text] {
width: 150px;
length: 150px;
}
input[name=myname] {
width: 100px;
length: 150px;
}
<input type="text">
<br>
<input type="text" name="myname">

This is the perfect job for the query selector...
var Set1=document.querySelectorAll('input[type=button]'); // by type
var Set2=document.querySelectorAll('input[name=goButton]'); // by name
var Set3=document.querySelectorAll('input[value=Go]'); // by value
You can then loop through these collections to operate on elements found.

if in case you are not using name in input but other element, then you can target other element with there attribute.
[title~=flower] {
border: 5px solid yellow;
}
<img src="klematis.jpg" title="klematis flower" width="150" height="113">
<img src="img_flwr.gif" title="flower" width="224" height="162">
<img src="img_flwr.gif" title="flowers" width="224" height="162">
hope its help. Thank you

have you explored the possibility of using jQuery? It has a very reach selector model (similar in syntax to CSS) and even if your elements don't have IDs, you should be able to select them using parent --> child --> grandchild relationship. Once you have them selected, there's a very simple method call (I forget the exact name) that allows you to apply CSS style to the element(s).
It should be simple to use and as a bonus, you'll most likely be very cross-platform compatible.

Related

Target class by name for tooltip [duplicate]

I'm currently working on a project where I have no control over the HTML that I am applying CSS styles to. And the HTML is not very well labelled, in the sense that there are not enough id and class declarations to differentiate between elements.
So, I'm looking for ways I can apply styles to objects that don't have an id or class attribute.
Sometimes, form items have a "name" or "value" attribute:
<input type="submit" value="Go" name="goButton">
Is there a way I can apply a style based on name="goButton"? What about "value"?
It's the kind of thing that's hard to find out because a Google search will find all sorts of instances in which broad terms like "name" and "value" will appear in web pages.
I'm kind of suspecting the answer is no... but perhaps someone has a clever hack?
Any advice would be greatly appreciated.
You can use the attribute selector,
input[name="goButton"] {
background: red;
}
<input name="goButton">
Be aware that it isn't supported in IE6.
Update: In 2016 you can pretty much use them as you want, since IE6 is dead. http://quirksmode.org/css/selectors/
http://reference.sitepoint.com/css/attributeselector
Text Input Example
input[type=text] {
width: 150px;
}
input[name=myname] {
width: 100px;
}
<input type="text">
<br>
<input type="text" name="myname">
You can use attribute selectors but they won't work in IE6 like meder said, there are javascript workarounds to that tho. Check Selectivizr
More detailed into on attribute selectors: http://www.css3.info/preview/attribute-selectors/
/* turns all input fields that have a name that starts with "go" red */
input[name^="go"] { color: red }
For future googlers, FYI, the method in the answer by #meder , can be used with any element that has a name attribute, so lets say theres an <iframe> with the name xyz then you can use the rule as belows.
iframe[name=xyz] {
display: none;
}
The name attribute can be used on the following elements:
<button>
<fieldset>
<form>
<iframe>
<input>
<keygen>
<map>
<meta>
<object>
<output>
<param>
<select>
<textarea>
Using [name=elementName]{} without tag before will work too.
It will affect all elements with this name.
For example:
[name=test] {
width: 100px;
}
<input type=text name=test>
<div name=test></div>
If i understand your question right then,
Yes you can set style of individual element if its id or name is available,
e.g.
if id available then u can get control over the element like,
<input type="submit" value="Go" name="goButton">
var v_obj = document.getElementsById('goButton');
v_obj.setAttribute('style','color:red;background:none');
else if name is available then u can get control over the element like,
<input type="submit" value="Go" name="goButton">
var v_obj = document.getElementsByName('goButton');
v_obj.setAttribute('style','color:red;background:none');
input[type=text] {
width: 150px;
length: 150px;
}
input[name=myname] {
width: 100px;
length: 150px;
}
<input type="text">
<br>
<input type="text" name="myname">
This is the perfect job for the query selector...
var Set1=document.querySelectorAll('input[type=button]'); // by type
var Set2=document.querySelectorAll('input[name=goButton]'); // by name
var Set3=document.querySelectorAll('input[value=Go]'); // by value
You can then loop through these collections to operate on elements found.
if in case you are not using name in input but other element, then you can target other element with there attribute.
[title~=flower] {
border: 5px solid yellow;
}
<img src="klematis.jpg" title="klematis flower" width="150" height="113">
<img src="img_flwr.gif" title="flower" width="224" height="162">
<img src="img_flwr.gif" title="flowers" width="224" height="162">
hope its help. Thank you
have you explored the possibility of using jQuery? It has a very reach selector model (similar in syntax to CSS) and even if your elements don't have IDs, you should be able to select them using parent --> child --> grandchild relationship. Once you have them selected, there's a very simple method call (I forget the exact name) that allows you to apply CSS style to the element(s).
It should be simple to use and as a bonus, you'll most likely be very cross-platform compatible.

CSS Syntax for children that are not direct descendents?

The question I want to ask is, "Is it possible/good practice to refer to a child of an element that is not a direct child?"
For instance, if you have HTML like this:
<form class="formation">
<p>
<span>
<input class="phone input">
</span>
</p>
<p>
<span>
<input class="text input">
</span>
</p>
</form>
And you want to refer in CSS to the inputs only in that particular form, so you call the class of the form followed by the class of the inputs without referring to the elements in between, like this:
.formation .input {
width: 10px;
}
will this work properly?
I tend to think I've done this already on projects and it has worked properly but usually I refer to all the children in between (because I don't go that deep). But I'm currently working on a media query for a wordpress site that doesn't seem to be respecting this rule. Is this bad practice? Or is this downright incorrect? Thanks for all your help!
Yes, it is not only possible but also advisable to do so. Choose your selectors for your css rules as lean as needed to reduce dependency on your markup structure. This is not only wise for performance reasons, it also saves you quite some work in case your markup should ever change, e.g. later on you notice the span is not needed any longer and you remove it to keep your markup as clean as possible. In case you used the full DOM path to your .input you will then also have to adjust your css selectors. Same if for any reason in the future your <p> should become a <div>.
Just make sure you give the rules as much DOM context as necessary to not apply your rules to the same classed element in other contexts (if you have any at all, and if you want to apply a different set of style rules for it).
Yes, it'll work fine. What youv'e got with .form .input allows for any number of intermediate nodes between the two classes.
If you'd had .form > .input, then your CSS wouldn't match at all. > is the "immediate descendant" selector, so
.form .input { color: green }
.form > .input { color: red }
<div class="form">
<div class="input">This is red</div>
<div class="whatever">
<div class="input">This is green</div>
</div>
</div>

changing text inside label element using CSS

I have a code snippet:
<fieldset class="shareMe"><br />
<input type="checkbox" id="share_me" name="share_me" value="1" {if $default_share_pref}checked="checked"{/if} onclick="if (this.checked) { var perms = 'publish_stream'; fb_login_cached(function(response){ if (!response.perms.match(new RegExp(perms))) $('share_me').checked = false; }, perms); }"/>
<label for="share_me">Post this question to my friends on
<span class="">
<a class="fb_button fb_button_small">
<span class="fb_button_text">Facebook</span>
</a>
</span>.
</label>
</fieldset>
I want to change the text in <label for .. > field via CSS.
I know i can do it by placing duplicate copy of this snippet and use css to toggle. However, i want to do it minimum code change. May be using some CSS trick to change <label for..> text and not affecting the code inside <label for...> at all.
You can't change text with CSS. The exception to this rule is the ::before and ::after psuedo-elements. In theory you could use classes to toggle the text like so:
label[for="share_me"]:before{content:'Post this question to my friends on '}
label[for="share_me"].othertext:before{content:'Some other text!'}
However, just because you can doesn't mean you should. It's an accessibility nightmare, and can you imagine coming back later and trying to work out where the text is coming from if not from the HTML?
Following the example at https://blog.escapecreative.com/how-to-replace-text-with-css/, this is what worked for me:
label[for="donate-choice-14724"]{
visibility: hidden;
position: relative;
}
label[for="donate-choice-14724"]:after{
visibility: visible;
position: absolute;
top: 0;
left: 0;
content:'Make this donation monthly';
}
You can only change the content of :before and :after pseudoelements with CSS. Ali Bassam's answer below shows a 'hacky' way to display the pseudoelements content over the parent so that you can control it. Problems with this solution include, well, how hacky it seems and also the limited IE support of pseudo elements. But that might not be problematic for your project.
Another thing to consider is that you'd have limited control over the toggle with CSS. Your two options are media queries and the familiar pseudo classes. If your toggling needs go beyond what those guys can do, you'd do best turning to Javascript.

Using span margins to align text

A little new to html so if further explanation is necessary or this question just doesn't make sense please feel free to say so.
I am using div to layout a webform I am designing and using the &nbsp to move text within a div doesnt always produce the result I want as far as the layout of the page.
I started experimenting and by using:
<span style="margin-left:(variable)px"></span>
i am able to move the text exactly where I want it.
My question is this, is this a bad practice? is there a better way to do what I am trying to do, or a more conventional way? Or even something built into html that I just have not discovered yet.
Thank you
* Added Block of code to show what i am trying to accomplish
Complainant's Address
<input type="text" size="50" id="complainantAddress"/>
<span style="margin-left:3px"></span>
City
<input type="text" name="city" maxlength="15" size="15"/>
<span style="margin-left:16px"></span>
State
</div>
Using non breakable spaces for layout/positioning is bad practice.
What you are trying to do with style attributes is better, but inline-style attributes are often considered as bad pratice, too.
Style attributes are hard to maintain and you duplicate lots of information etc. In addition this styling has the highest specificity and cannot be overwritten by other styles (like user CSS files). They should be used with caution.
Use CSS attributes margin, padding and text-align for this.
Sample
http://jsfiddle.net/UYUA7/
HTML
Text<br />
Text <!-- Do NOT use this -->
<div class="center">Center</div>
<div class="right">Right</div>
<div class="indent">Indented</div>
CSS
.center {
text-align: center;
}
.right {
text-align: right;
}
.indent {
margin-left: 20px;
}
What you're doing is actually a better way to do spacing, than relying on &nbsps. This will give you a much greater flexibility in the long-term and allow you to make changes quicker. (Less typing)
The only other thing that I would recommend is to read through this CSS manual:
http://www.w3schools.com/css/css_intro.asp
This will help you continue to learn about position with css.
UPDATE:
This is what your code can look like:
CSS - Use it in the header
<style type="text/css">
#complainantAddress {
margin-right: 3px;
}
#city {
margin-right: 16px;
}
</style>
HTML
Complainant's Address: <input type="text" size="50" id="complainantAddress"/>
City: <input type="text" name="city" maxlength="15" size="15" id="city"/>
Notice that I created two css styles, one for each matching input boxes. Within each style I defined a margin which would add the appropriate spacing to the right of the input box.
So the first input box called "complainantAddress" will have 3px spacing to the right and the second one who's id is "city" will have 16px spacing to the right of it.

What is id= name= .something #something?

In HTML are the attributes like
<input class="new" type="text" name="title" id="title2" />
and in CSS do I see
.something { ... }
#something { ... }
What is id= name= .something #something used for?
ID: unique identifier for the DOM element
Name: name to be used when submitting a form which is used as the data retrieval key
#something: reference to element with ID 'something'
.something: reference to element(s) with classname 'something'
These are some really basic concepts of HTML and CSS. You will probably want to read a basic HTML tutorial to find out more on the subject, especially the attributes section.
Id's and classnames are primary used for styling elements with CSS and adding behaviour to them with JavaScript. For example:
HTML:
<button id="foo">Click me to unleash the Unicorn</button>
CSS:
#foo {
border: 1px solid #ff0000;
font-weight: bold;
background: #000;
color: #fff;
}
JavaScript:
document.getElementById('foo').onclick = function() {
var img = document.createElement('img');
img.src = 'http://display.ubercomments.com/6/23672.jpg';
document.getElementsByTagName('body')[0].appendChild(img);
};
See also, this beautiful example (Unicorn included).
An id attribute is a unique identifier for the element within the DOM. It's unique in the sense that you cannot have more than one element with this ID contained within the document.
Styling an element based on ID is done using #something.
A name attribute is simply a non-unique name for this element. This is most commonly used in forms as the name that gets POST'd or GET'd through to the server side language.
.something is the style selector for the class= attribute on any element.
For instance, you could style the following element: <div class="testclass" name="testname" id="testid"></div> in any of the following 3 ways:
.testclass {
background-color: black;
}
#testid {
background-color: black;
}
div[name="testname"] {
background-color: black;
}
Remember, both a class and a name are NOT unique, so they can be used to style and define multiple elements.
The .something is a class, and the #something is an id.
the Name= attribute is commonly used in forms, and usually not used in CSS.
In other words, the following code:
<body class="thisisaclass">
<div id='thisisanid'></div>
<div class='thisisanotherclass'></div>
</body>
Would result in a CSS that looks like this:
.thisisaclass {..Code..}
.thisisaclass #thisisanid {..Code..}
.thisisanotherclass {...code...}
Classes are used for repeating stuff, for example if you want to use the same type of text formatting in several areas of your page - whereas ids only should appear once in the html code.
Check out HTMLDog to learn more, it's a great start :)
id="something" means ID. You can have it only once. It's CSS reference is #something. Also, by using #something at end of address, you can directly move browsers to that ID, without using JS.
name= is used while sending form. Using PHP, you can check that value by using $_REQUEST['title']. In other programming languages, there also are methods to get that value.
.something is class in CSS. It's used to style HTML elements with class="something"
class is multiple selector for example if you want many tables have same colors, back ground colors and font etc. You will define class.
In these tables if a specific table is to style in different way you will use id. Id can not be duplicated. And you can assign a same class to as many objects you want.
<style type="text/css">
.MyTable{
background-color:#ff00ff;
}
#centralTable{
background:color:red;
}
</style>
<div class="MyTable">Data </div>
<div class="MyTable"> </div>
<div class="MyTable" id ="centralTable"> Data</div>
<div class="MyTable"> Data</div>
<div class="MyTable">Data </div>
Remember classes are followed by period (.) and Ids (#) in Cascading Style Sheets.