Questions tagged [css]

CSS (Cascading Style Sheets) is a representation style sheet language used for describing the look and formatting of HTML (HyperText Markup Language), XML (Extensible Markup Language) documents and SVG elements including (but not limited to) colors, layout, fonts, and animations. It also describes how elements should be rendered on screen, on paper, in speech, or on other media.

CSS, or Cascading Style Sheets, is a language used to control the visual presentation of documents written in a markup language, including HTML, XML, XHTML, SVG, and XUL.

The visual presentation of HTML was originally defined by HTML attributes, but HTML 4 deprecated these attributes as CSS was introduced to separate the control of the visual presentation from content. In October 1994, Håkon Wium Lie first proposed Cascading HTML Style Sheets while working at CERN with Sir Tim Berners-Lee, who had been developing a web browser and inventing HTML.

A basic CSS document is made of rule sets. Each rule set starts with a selector, a pattern that matches elements in an HTML or XML document, and is followed by a block of zero or more property declarations that define the presentation of the matching elements. The selector is quasi-identical to the selector used by JavaScript's .querySelectorAll. For example:

/* This is a comment */ 

a {                             /* Select all <a> elements (HTML links), */
    color: orange;              /* change their text color to orange, */
    background-color: pink;     /* their background color to pink, */
    text-decoration: none;      /* and remove text decorations like underlines. */
}

a:hover {                       /* Select all <a> elements which are currently being hovered over with the :hover pseudo-class*/
    color: red;                 /* change the color to red */
    text-decoration: underline; /* and add an underline again */
}

The simple example above also illustrates the cascading element of CSS. When you hover over a link (i.e., an <a> element) in an HTML page with this style sheet applied to it, both rules apply. Because of the first rule, the link will have a pink background. But, since the a:hover selector is more specific, its color and text-decoration properties override those from the <a> rule-set.

The cascading order defines how specificity and other factors determine which property value is applied to an element.


Selector precedence and specificity

Each component of a CSS selector can be based on one or more of four possible attributes of an HTML element:

  1. The element's ID (from the id attribute)
  2. The name of one of the element's classes (in the class attribute)
  3. The element's tag name
  4. The element's properties or their values

Selectors using an ID selector have higher priority than selectors using class names, and selectors using a class name have higher priority than selectors using tag names. This is called the selector precedence. The !important annotation can be used to override selector precedence, by elevating a normal declaration to an important declaration. Whenever possible, however, higher specificity within a normal declaration should be used in preference to the creation of an important declaration via the !important annotation, in order to prevent overrides on any other styles that might need to be added, particularly those that are subsequently added with a natural precedence intent.

For example:

/* any anchor element */
a {                
    color: orange;
}

/* any element with class name class1 */
.class1 {          
    color: red;
}    

/* the element with id anchor1 */
#anchor1 {
    color: green;
}
<!-- Creates an anchor with a class of class1 and an ID of anchor1 -->
<a class="class1" id="anchor1">Sample</a>

In the above example, the text color of the content of the <a> element, the string "Sample", will be green.

Repeated occurrences of the same selector also increase specificity, as noted in the Selectors Level 3 W3C Recommendation.

.class1.class1 {    /* repeated class selector */
    font-weight: bold;
}

.class1 {
    font-weight: normal;
}

Here, the repeated selector has higher specificity than the singular selector, and the font-weight of our sample string will be bold.

According to MDN,

Specificity is basically a measure of how specific a selector is — how many elements it could match. [...] element selectors have low specificity. Class selectors have a higher specificity, so [classes] will win against element selectors. ID selectors have an even higher specificity, so [IDs] will win against class selectors.

Complex selectors can be created by joining multiple simple ones together. It is also possible to style elements depending on an attribute:

/* The first <a> element inside a <p> element that's next to an <h3> element
   that's a direct child of #sidebar matches this rule */
#sidebar > h3 + p a:first-of-type {
    border-bottom: 1px solid #333;
    font-style: italic;
}

/* Only <img> elements with the 'alt' attribute match this rule */
img[alt] {
    background-color: #F00;
}

A CSS rule specificity calculator is available here. It may help when a project has one or multiple large CSS files.


Inheritance

Inheritance is a key feature in CSS.

Inheritance is the mechanism by which properties are applied not only to a specified element but also to its descendants. In general, descendant elements automatically inherit text-related properties, but box-related properties are not automatically inherited.

  • Properties that are inherited by default are color, font, letter-spacing, line-height, list-style, text-align, text-indent, text-transform, visibility, white-space and word-spacing.
  • Properties that are usually not inherited are background, border, display, float and clear, height, and width, margin, min/max-height/width, outline, overflow, padding, position, text-decoration, vertical-align and z-index.

It is worth noting that any property can be inherited by using the inherit property value. This should be used with care, however, since Internet Explorer (up to and including version 7) doesn’t support this keyword. As an example:

/* Set the color of <p> elements to a light blue */
p {
    color: #C0FFEE;
}

/* Set the color of #sidebar to a light red */
#sidebar {
    color: #C55;
}

/* <p> elements inside #sidebar inherit their parent's color (#C55) */
#sidebar p {
    color: inherit;
}


/* You may also override inherited styles using the !important annotation */
#sidebar p:first-of-type {
    color: orange !important;
}

Important Notice:

For questions related to CSS, try to demonstrate your code in a reproducible manner using either Stack Exchange's Stack Snippets or alternatively any online editor that allows running and sharing code such as JS Bin, JSFiddle or CodePen (though be sure to always include relevant code in the question).


References

Interactive Tutorial

  • CSS Diner - An interactive game to learn about CSS selectors.

Video Tutorial

CSS Pseudo Selector

Validation

Naming conventions & Methodologies

Browser Support

CSS Pre-processors

CSS Post-processors

Reset Stylesheets

CSS Frameworks

The Future

The following currently have very little (if any) browser support and are still a work in-progress:

Chat Room

Chat about CSS (and HTML / DOM) with other Stack Overflow users:


Related tags for specific features

797792 questions
132
votes
8 answers

How to get these two divs side-by-side?

I have two divs that are not nested, one below the other. They are both within one parent div, and this parent div repeats itself. So essentially:
Justin Meltzer
  • 13,318
  • 32
  • 117
  • 182
132
votes
5 answers

Turn off Chrome/Safari spell checking by HTML/css

Is there a way for a web developer to turn off Chrome/Safari/WebKit's spellchecking on particular input or textarea elements? I mean either by special tag attribute or a proprietary CSS instruction. There is a CSS instruction for turning off…
tillda
  • 18,150
  • 16
  • 51
  • 70
132
votes
14 answers

Replace input type=file by an image

Like a lot of people, I'd like to customize the ugly input type=file, and I know that it can't be done without some hacks and/or javascript. But, the thing is that in my case the upload file buttons are just for uploading images (jpeg|jpg|png|gif),…
Nicolas
  • 2,754
  • 6
  • 26
  • 41
132
votes
9 answers

Does opacity:0 have exactly the same effect as visibility:hidden

If so, does it effectively deprecate the visibility property? (I realize that Internet Explorer does not yet support this CSS2 property.) Comparisons of layout engines See also: What is the difference between visibility:hidden and display:none
Chris Noe
  • 36,411
  • 22
  • 71
  • 92
132
votes
8 answers

Can I color table columns using CSS without coloring individual cells?

Is there a way to color spans of columns all the way down. See, starting example below: …
Dennis
  • 7,907
  • 11
  • 65
  • 115
132
votes
10 answers

Is there a srcset equivalent for css background image

img with srcset attribute looks like a great way of doing responsive images. Is there an equivalent syntax that works in css background-image property? HTML yah CSS .mycontainer…
Martin Algesten
  • 13,052
  • 4
  • 54
  • 77
132
votes
1 answer

Print styles: How to ensure image doesn't span a page break

When writing a print stylesheet, is there a way to ensure that an image is always only on a single page, instead of spanning multiple pages. The images much smaller than the page, but based on the document flow, they end up at the bottom of the page…
davidtbernal
  • 13,434
  • 9
  • 44
  • 60
132
votes
9 answers

Changing :hover to touch/click for mobile devices

I've had a look around but can't quite find what i'm looking for. I currently have a css animation on my page which is triggered by :hover. I would like this to change to 'click' or 'touch' when the page is resized past width 700px using media…
DannyBoy
  • 1,604
  • 2
  • 13
  • 12
132
votes
14 answers

Placeholder for contenteditable div

I have the following: FIDDLE The placeholder works fine and dandy until you type something, ctrl + A, and delete. If you do that, the placeholder disappears and never shows up again. What's wrong? How can I have a placeholder for a contenteditable…
Bagwell
  • 2,018
  • 5
  • 18
  • 24
132
votes
5 answers

Advantages of using display:inline-block vs float:left in CSS

Normally, when we want to have multiple DIVs in a row we would use float: left, but now I discovered the trick of display:inline-block Example link here. It seems to me that display:inline-block is a better way to align DIVs in a row, but are there…
Ryan
  • 10,041
  • 27
  • 91
  • 156
132
votes
5 answers

How do you make a div "tabbable"?

I have buttons that are div elements and I want to make them so that it is possible for the user to press the tab key on their keyboard and move between them. I've tried wrapping their text in anchor tags but it doesn't seem to work. Does anyone…
TheBoss
  • 1,994
  • 4
  • 16
  • 21
132
votes
11 answers

iPhone 5 CSS media query

The iPhone 5 has a longer screen and it's not catching my website's mobile view. What are the new responsive design queries for the iPhone 5 and can I combine with existing iPhone queries? My current media query is this: @media only screen and…
Maverick
  • 3,039
  • 6
  • 26
  • 35
132
votes
9 answers

Align two inline-blocks left and right on same line

How can I align two inline-blocks so that one is left and the other is right on the same line? Why is this so hard? Is there something like LaTeX's \hfill that can consume the space between them to achieve this? I don't want to use floats because…
mk12
  • 25,873
  • 32
  • 98
  • 137
131
votes
4 answers

Highlight label if checkbox is checked

Is there a non-javascript way of changing the color of a label when the corresponding checkbox is checked?
Vladimir Keleshev
  • 13,753
  • 17
  • 64
  • 93
131
votes
6 answers

CSS: how to get scrollbars for div inside container of fixed height

I have the following markup:

Title

..blah blah blah...
The CSS looks like this: .FixedHeightContainer { float:right; height: 250px; width:250px; …
David
  • 15,750
  • 22
  • 90
  • 150
Motor Engine Car Body