What's the difference between "." and "#" in CSS and how to choose to use? - css

I'm learning in CSS, I am really confused when to use .(dot) and when to use # in CSS file. Sometimes I really wondered which one I should use.

#You are .Human
While there are many humans, there is only one you. As such, . is for classes, which can appear over and over in a document. # is for IDs, which are unique to a document.
<div class="firstname" id="personA">
<p class="lastname">Sampson</p>
</div>
<div class="firstname" id="personB">
<p class="lastname">Sampson</p>
</div>
Note the unique identifier for both div, personA and personB. However both elements have classes in common, such as .firstname, and .lastname.
Professional Examples
You can see how these are used out in the wild by looking at tools like Modernizr. This feature-detection tool assists you by adding classes to the <html> element that inform you as to what the device or browser is capable of:
<html lang="en" dir="ltr"
id="modernizrcom"
class="js no-touch postmessage history multiplebgs boxshadow...">
Here we see the one unique value for the <html> element, #modernizrcom. Following, a series of classes that give more general info about the element. This is a clear example of how an element can have only one id, but many classes.
Careful with those IDs!
Because these values are completely unique, they can cause you to paint yourself into a corner at times. It's worth reading Disallow IDs in Selectors to know more about the potential issues with using IDs in your selectors.

The # is used for the id of an element and . is used for classes of an element. In a HTML document, an id is unique (there should only be one element with that id) while classes can occur multiple times.
<div id="content" class="shade light">
</div>
You can now do:
#content { border: solid 1px black; }
to add styling to that particular div element. But you can also do:
.light { background-color: #eeeeee; }
The difference is that the latter will apply that background color to all elements with that class (i.e., all elements with the class light while the first CSS statement will only add styling to the element with the id content).

a dot (.) represents a class, a hash (#) represents an id.
There is more to it, but this is the gist:
An id (#myID) should be used when you only intend to use that selector once
A class (.myClass) should be used to create a reusable piece of styling code (e.g. to make text blue)

. is represent class
# is represent ID(but used only once in a page)
always the id is having the first priority in the race.
ex:
in the style
.alignmeleft{float:left;}
#alignmeright{float:right;}
in the html:
<div class="alignmeleft" id="alignmeright">
<!--div content-->
</div>
OUTPUT
THE DIV WILL ALIGNED RIGHSIDE

Related

Hide all elements with duplicate class names besides the first with CSS

I have a loop displaying some markup that has dynamic class names. Is it possible to hide all elements with duplicate class name besides the first instance? For example below I would only want the first .SomethingDynamic1 and the first .SomethingDynamic2 to be visible.
I think I might be able to use the div[class^="group"] "starts with" attribute selector to achieve this but am I able to match dynamic text after that and filter out the duplicates? I would prefer a CSS only solution if possible.
<div class="group-SomethingDynamic1">
<div class="group-SomethingDynamic1">
<div class="group-SomethingDynamic1">
<div class="group-SomethingDynamic1">
<div class="group-SomethingDynamic2">
<div class="group-SomethingDynamic2">
<div class="group-SomethingDynamic2">
<div class="group-SomethingDynamic2">
Update (credit #Temani Afif)
If you want a CSS only solution, you will need to know the classes to filter beforehand.
Given that, you can simply use a siblings selector like the following:
.group-SomethingDynamic1 ~ .group-SomethingDynamic1 {
display: none;
}
Here is a stackblitz example

Could <Section> and <div> be used interchangeably in html?

I understand from reading similar posts that the <section> tag in html is meant for semantic and organizational purposes. I was wondering, however, why using the <div> tag with a class attribute wouldn't have a similar effect.
(e.g. <div class = "SectionOne">)
Given these two methods, I could refer to each of them in CSS by using their respective names:
Section
{
color = white;
}
or
.SectionOne
{
color = white;
}
Personally, I think the second method allows for greater versatility in webpage design and I don't see many advantages to the new HTML5 feature. Would anyone care to clear this up for me?
section is usually used for having article like contents whereas div are meant to combine various block elements in order to style them differently. The main difference is just semantics.
Refer https://www.thoughtco.com/difference-between-div-and-section-3468001 for derails
Let me know if you require any further help
The <section> tag defines sections in a document, such as chapters, headers, footers, or any other sections of the document.
Whereas: The <div> tag defines a division or a section in an HTML document. The tag is used to group block-elements to format them with CSS.
Maybe you mean section and not Section. Anyway, the semantics is a thing and the selectors another. In CSS it is better to select using classes than tag selectors, because you gain a lot in terms of versatility. So you are right from this point of view. Semantics is another matter: is not given by a class. Even if you give a "section" class to a div, you are not giving semantic meaning to a div.
<div> is simply a generic block-level element which predates the later, semantically-named, document-related elements which arrived with HTML5, such as:
<header>
<nav>
<main>
<section>
<aside>
<footer>
When dividing up a document into its anatomical parts, you could still use:
<div class="header">
<div class="section">
etc.
But... you don't need to anymore.
Of course, even if you still use all of the above in your document you might still want to add other block-level elements and when you do... <div> is general purpose.

What does text before selectors in css mean?

Apologies for the beginner css question but it's rather difficult to find an answer for this.
I'm looking at the duckett book for html and css and it has a couple of selector syntax confusing to me.
table.one{}
input#web{}
I thought that the .x indicates that x is a class selector and similarly that #x indicates that x is an id selector but why did the author choose to put text before these? He didn't give an explanation as far as I can tell.
table.one matches all table elements which have class one.
input#web matches the input element which has id web.
This kind of selector is called "Type selector". You can read these resources:
CSS2.1 spec
Selectors Level 3
Selectors Level 4
MDN article
table.one{}
'[element type].[css class name]{}
input#web{}
'[element type]#[id attribute]{}
When an element type is specified, that means that definition will only work for that element type.
table.myCss{} for the Element, when class='myCss' then apply the css. Don't apply this CSS to <span class='myCss'> or any other element type.
Here is a link to the official specifications page for CSS3. http://www.w3.org/TR/css3-selectors/
Let me break it down:
table.one means, look for a tag with the name table, which also has the class one
input#web similarly means: look for an element with the name input and the id of web
In some cases, these selectors might not be necessary, especially on IDs, since they are supposed to be unique, as opposed to classes, which are reasuable. The usage of element names with classes, however, can help you make different elements look different than others, for example, if you want to center text and a div, you might only want to use one class for both, but since <div> elements are block level, they can't be center like text by default.
div.center {
margin-left: auto;
margin-right: auto;
}
p.center {
text-align: center;
}
<input class="x" ... >
<div class="x" ... ></div>
So now we have:
.x {} // To select both
input.x {} // To select just the input with class "x"
div.x {} // To select just the div with class "x"
This could be used to just make it more clear for what element the styles are for. Or to limit the elements affected.
Similarly we can do this with element ids.
<input id="a" ... >
<div id="b" ... ></div>
So we can write simply #a. Or we can write input#a. Currently these are equivalent.
With the div we would have either #b or div#b.
The use of table and input in front of their respective classes / IDs reference the type of element in the markup. For example:
table.one {
..
}
References a table with class "one" (in code: <table class="one">). This way, if the author has another element with class "one" (example: <div class="one">), the div is not affected by the rule of table.one.
Same idea for input#web, except the selector is targeted towards input tags with ID of "web" (<input id="web">)
Some additional reading from W3 may be of some help (it's from CSS2, but the main points are still present): http://www.w3.org/TR/CSS2/selector.html
DEMO: http://jsfiddle.net/uWkYL/

Is there a way to use wildcards in css id tag

assuming i have few items with similar ids:
<input class="a" id="id_1"/>
<input class="a" id="id_2"/>
i would like to set in my css file something like:
#id_*{width = 100%;}
is there a way i can do that?
i've tried something like:
input[id^='id_']{width:200px;}
but that didnt worked out......
And its need to work on IE :(
EDIT: nedd to work on IE8....
EDIT:
<input tabIndex="1690" class="form" id="cust_1_NUM_OBJ_5-00461" dataFld="cust_1_NUM_OBJ_5-00461" dataSrc="#FIELDVALUES" style="text-align: right; height: 20px;" onkeypress="validateNumberChar(this)" onfocus="resetGFocusField('cust_1_NUM_OBJ_5-00461');" onblur="validateChangedNumber(this);" onbeforedeactivate="onbeforedeactivateLookup(this);" type="text" size="20" maxLength="55" datatype="number" numbertype="24,6" valueFieldID="null" tabStop="true" value="1"/>
and CSS:
input[id^='cust_1_NUM_OBJ_5-0046']{width:200px;}
input[id^='id_']{width:200px;} should work. It certainly does in this fiddle:
http://jsfiddle.net/jYZnX/
EDIT: Also, to show that it doesn't pick an input without an id beginning 'id_':
http://jsfiddle.net/jYZnX/1/
EDIT 2: As your Document Mode seems to be set to Quirks this will cause issues with the css selector. Set your doc type correctly, eg using <!DOCTYPE HTML>. This will need access to the original code for the web pages though, so without that you will be in a spot of bother.
The selector you used (^), works correctly in IE:
input[id^='id'] {
background: red;
}
And here is the result:
IE7
IE8
IE9
IE10
As I saw in your pictures, your IE is rendering your page with Quirks Mode.
Maybe you have no doctype or wrong doctype at your page. Make your doctype valid as below:
<!doctype html>
My answer is quite general and never directly related to the question because this is already very old and so far solved by other answers on this page.
The first part of this answer is dry theory which is useful to understand the options.
The second part is an example for usage of this theory.
1) ATTRIBUTE SELCTORS
Substring matching attribute selectors:
[att^=val]
Represents an element with the att attribute whose value begins with the prefix "val". If "val" is the empty string then the selector does not represent anything.
[att$=val]
Represents an element with the att attribute whose value ends with the suffix "val". If "val" is the empty string then the selector does not represent anything.
[att*=val]
Represents an element with the att attribute whose value contains at least one instance of the substring "val". If "val" is the empty string then the selector does not represent anything.
Additionally there are still more selectors, in the specification they are sorted in the chapter Attribute presence and value selectors:
[att]
Represents an element with the att attribute, whatever the value of the attribute.
[att=val]
Represents an element with the att attribute whose value is exactly "val".
[att~=val]
Represents an element with the att attribute whose value is a whitespace-separated list of words, one of which is exactly "val". If "val" contains whitespace, it will never represent anything (since the words are separated by spaces). Also if "val" is the empty string, it will never represent anything.
[att|=val]
Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D).
2) EXAMPLE HOW TO SELECT SEVERAL THINGS ON A PAGE DEPENDING ON AN EVENT
Wildcards are especially then useful when an event is triggered like that a page is visited with a special hash-tag. For a completely static page in contrast they are also useful but still could be noted different, even it would be more CSS-code.
Assume a page is visited with the hash-tag action, so the URL would look like this:
https://example.com/index.html#action
While only one id is triggered like that we can use it to note a whole stack of related actions in CSS, we just have to enclose the whole area where something shall happen in an element with the id action:
/* all div-elements which are direct child of element with class `wrapper` are hidden: */
.wrapper>div {
display: none;
}
/* following line addresses all elements inside element with the id "action"
where the id is starting with "action_". This is only triggered when the
URL with hashtag "action" is called, because of usage of ":target":
*/
#action:target [id^="action_"] {
display: block;
}
/* following line addresses all elements inside element with the id "amother-action"
where the class is "another-action". This is only triggered when the
URL with hashtag "another-action" is called, because of usage of ":target".
This example shows that we never need ids but can use classes too:
*/
#another-action:target .another-action {
display: block;
}
<div id="action">
<div id="another-action">
<div class="wrapper">
<!-- this small menu is always shown as it's an unordered list and no div: -->
<ul>
<li>No Action / Reset</li>
<li>Action</li>
<li>Another Action</li>
</ul>
<!-- The following div-elements are by default hidden and
only shown when some event is triggered: -->
<div id="action_1" class="another-action">
<!-- this is on both actions shown as the div has an id starting
with "action" and also a class "another-action" -->
Hello
</div>
<div id="action_2">
<!-- this is above only triggered by the CSS-rule
#action:target [id^="action_"] -->
World!
</div>
<div class="another-action">
<!-- This is above only triggered by the CSS-rule
#another-action:target .another-action -->
Everybody!
</div>
</div>
</div>
</div>
The different results are these:
When the page is called without any hash, only the menu is shown:
Action
Another Action
When the page is called with the hash action, below the menu can be seen:
Hello
World!
When the page is called with the hash another-action, below the menu can be seen this instead:
Hello
Everybody!
Like this we can mix much content where each division is only shown in special cases.
Mixing several ids and classes does only work if the elements with the ids are enclosing the elements with content and select-able properties. In my example above you can see that everything in HTML is written between <div id="action"><div id="another-action"> and </div></div>, like this every used event can optionally trigger everything in the content between.
Naturally it's possible by CSS to use this method for other effects too. Hiding or showing the elements is only a simple example but you could change colors, start CSS-animations and do many other things by CSS.
Keep care that you don't publish any confidential things in any of those elements, because this CSS-solution is no security but only for distinguishing cases for visual display.
Any things you hide or show like this are always visible in the HTML-source.
Given a three-column table with 200 rows and each row having an individual id like this row:
<tr id="row_177">
<td><a class="btn" href="..">Link1</a></td>
<td>Name of PDF File</td>
<td><select class="pdf_sel">
<option value=""> ---- </option>
<option>Crowell, Thomas</option>
</select>
</td>
</tr>
and given that you want to vertically center the content in each td, then the following css wildcard will cause the content of each td to be centered vertically** (I'm sure you could also use this to adjust width):
tr[id^='row_'] > td {
vertical-align:middle
}
** One caveat - the third column in the table contains a Select in each td. While the anchor button in the first column and the text anchor in the second column are centered vertically in each td by using the above css, the Select in the third column does not respond to this css for some reason - but there is a fix. The following css will cause the Select elements to be properly centered vertically:
tr[id^='pdfrow_'] > td > select {
margin-top:5px;
margin-bottom:5px
}
That is precisely what classes are for. What you want is:
.a { width: 100% }

wildcard * in CSS for classes

I have these divs that I'm styling with .tocolor, but I also need the unique identifier 1,2,3,4 etc. so I'm adding that it as another class tocolor-1.
<div class="tocolor tocolor-1"> tocolor 1 </div>
<div class="tocolor tocolor-2"> tocolor 2 </div>
<div class="tocolor tocolor-3"> tocolor 3 </div>
<div class="tocolor tocolor-4"> tocolor 4 </div>
.tocolor{
background: red;
}
Is there a way to have just 1 class tocolor-*. I tried using a wildcard * as in this css, but it didn't work.
.tocolor-*{
background: red;
}
What you need is called attribute selector. An example, using your html structure, is the following:
div[class^="tocolor-"], div[class*=" tocolor-"] {
color:red
}
In the place of div you can add any element or remove it altogether, and in the place of class you can add any attribute of the specified element.
[class^="tocolor-"] — starts with "tocolor-".
[class*=" tocolor-"] — contains the substring "tocolor-" occurring directly after a space character.
Demo: http://jsfiddle.net/K3693/1/
More information on CSS attribute selectors, you can find here and here.
And from MDN Docs MDN Docs
Yes you can do this.
*[id^='term-']{
[css here]
}
This will select all ids that start with 'term-'.
As for the reason for not doing this, I see where it would be preferable to select this way; as for style, I wouldn't do it myself, but it's possible.
An alternative solution:
div[class|='tocolor'] will match for values of the "class" attribute that begin with "tocolor-", including "tocolor-1", "tocolor-2", etc.
Beware that this won't match
<div class="foo tocolor-">
Reference:
https://www.w3.org/TR/css3-selectors/#attribute-representation
[att|=val]
Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D)
If you don't need the unique identifier for further styling of the divs and are using HTML5 you could try and go with custom Data Attributes. Read on here or try a google search for HTML5 Custom Data Attributes

Resources