Hidden features of CSS [closed]
Asked Answered
B

27

60

I have definitely picked up some useful tips in the hidden features style questions concerning PHP and XHTML.

So here is one to cover CSS. While easy to pick up, it takes a little while to learn about everything, their default behaviors, properties etc

Here are some to start the ball

@charset "UTF-8"; /* set the character set. must be first line as Gumbo points out in comments */

.element {
        /* takes precedence over other stylings */
        display: block !important;

        /* mozilla .... rounded corners with no images */
        -moz-border-radius: 10px; 

        /* webkit equivalent */
        -webkit-border-radius: 10px 
}

These are not so much hidden, but their use is not often widespread. What tips, tricks, rare features have you discovered with CSS?

Boneyard answered 9/3, 2009 at 23:17 Comment(19)
Yup. Double check all the other 'hidden-features', I'd wager that just about all of them are too.Bruns
why not add border-radius: 10px; for browsers supporting CSS3?Confidential
@Ólafur Waage: What's with the s/behaviour/behavior/ ? Behaviour is just as correct as behavior is, even more so since it is the Queens English.Jephthah
The @charset rule must be in the first line of the file.Palter
Firefox says i must change it, all obey the Fox!Sporocyst
Wikified as requested... -moz because it's not supported by all browsers yet... I think they (W3C) recommend a vendor prefix?Boneyard
Properties beginning with a - are vendor-specific, yes. Browsers are free to ignore them completely and still be standards-compliant.Peterkin
@Strager: that's what I thought, thanks.Boneyard
What does an accepted answer mean on a 'hidden features' question? Is it the most hidden feature?Pivoting
@Pivoting I'm not sure... I can't remember why I accepted it.Boneyard
@Jephthah - ahem Queen's English (note the apostrophe)Prickly
Removed accepted answer - don't know why I accepted it in the first place. Shouldn't affect Gumbo's rep as it is CW.Boneyard
@dmckee @Roger Pate @Matthew Flaschen @Ether @Aiden Bell Why did you guys close this question? Do you think all hidden features questions are not real questions?Boneyard
@alex: BTW, I found this by a web alert on my name, only the first @name is recognized. Yes, the questions should not be deleted for legacy purposes, but new ones should definitely be discouraged and old ones should be closed (which helps in the discouragement, too). Closed questions can still be voted upon and have comments, just no new answers.Brotherhood
Also, Meta is a better place to discuss this than comments strewn throughout various random questions. See meta.stackexchange.com/questions/56669/… in addition to the other I linked and I'm sure there's more.Brotherhood
@Roger Pate I was just thinking that because browsers are implementing new CSS stuff all the time, it should have been left open to add the new lesser known features as they are implemented. I wasn't aware of the meta discussion sorry. I deleted the other meta type comments on this question.Boneyard
@alex: If you have questions about new browser features, please ask them. If you want to discuss new browser features, SO isn't a discussion board.Brotherhood
@Roger Pate A link to the FAQ? Thanks... Anyway I'll add my close vote to this now after reading meta and to keep everyone happy.Boneyard
@alex: The FAQ states SO "is not a discussion board", that's what I wanted to point out by linking.Brotherhood
P
58

You can display the document’s title element:

head, title {
    display: block;
}
Palter answered 9/3, 2009 at 23:17 Comment(4)
that's unique. I thought none of the <head> elements were renderable.Gravel
Strangely, it works with <style> and <script>, as well (at least in Firefox).Simplicity
@Danko Durbić: Sure, they are also just elements in the DOM.Palter
this is something I really like, .el{background: red;position:absolute;top:0;left:0;right:0;bottom:0;}Vandalize
M
39

Apply multiple styles/classes to an element like this class="bold red GoldBg"

<html><head>
<style>
.bold {font-weight:bold}
.red {color:red}
.GoldBg {background-color:gold}
</style>
</head><body>
<p class="bold red GoldBg">Foo.Bar(red)</p>
</body></html>
Messeigneurs answered 9/3, 2009 at 23:17 Comment(7)
Why did I assume you can only do this with two classes.....Englis
Also note the fine distinction between .bold.red {} and .bold .red {}...Scoles
If multiple classes had conflicting properties (e.g. if .red and .GoldBg both specified the color property) then the CSS specificity rules apply; the order of classes in the class="..." attribute shouldn't matter.Gaitskell
Be aware IE6 doesn't support multiple classes and will only apply the last one - GoldBg in this instance.Buckeye
to elaborate on what ide says, specificity works from more specific superseding less. so," #table_id td.special{}" supersedes "td.special {}" supersedes a generic ".special {}"Translucid
but try to avoid naming classes like '.red' if you can. One day the client will want all the red text to be blue and now you've confused every developer that has to touch that code going forward.Commutator
@Gaitskell If the specificity is the same, the order of the classes does matter. Newer declarations (i.e. the ones that come later in the code) precede the older ones.Lesser
F
38

I really like CSS sprites.

Rather than have 20 images for all your site buttons and logos (and therefore 20 http requests with the latency around each one) you just use one image, and position it each time so only the bit you want is visible.

It's difficult to post an example as you'd need to see the component image and the placement CSS - but I've blogged Google's use of it here: http://www.stevefenton.co.uk/Content/Blog/Date/200905/Blog/Google-Uses-Image-Sprites/

Forsberg answered 9/3, 2009 at 23:17 Comment(4)
You can also use spriting for javascript controlled animations. Just cycle through the sprites on a setInterval etc.Bra
Good suggestion from Matthew Lock - the bonus with that suggestion is that you just change the position of the image, rather than the source of the image - so pre-loading isn't necessary on your entire animation set.Forsberg
jQuery UI uses this in their themes for framework icons jqueryui.com/themerollerAdige
Not so much a feature as a design pattern.Eulaeulachon
C
25

The fact that floating a parent element will cause it to expand to contain all of its floated children.

Calamus answered 9/3, 2009 at 23:17 Comment(3)
Knew this one but pretty handy. Also don't forget if that isn't an option, you can use the overflow property without resorting to ugly clearing divs.Boneyard
I don't know why everyone uses divs with a clear, i think br is a much more semantically relevant element to use, and I would consider a br with a clear on it to be less ugly then floating everything whether it needs it or notFlashback
@Matt Using overflow: hidden is even more semantic I believe - why introduce an element that is only there to fix a layout?Boneyard
J
23

You can set a variable width for an absolutely positioned element by specifying both left and right properties. This gives you more control than simply setting width to a percentage.

For example:

#myElement {
    position: absolute;
    left: 5px;
    right: 10px;
}

An alternative Example

#myElement{ /* fill up the whole space :) */
   background: red;
   position:absolute;
   left: 0;
   right:0;
   top: 0;
   bottom: 0;
}
Jesusa answered 9/3, 2009 at 23:17 Comment(5)
I don't believe this works in IE, though.Seton
I think this is supported all the way down to IE5.5Polloch
absolute positions are never preferred for flexible layouts.Extracanonical
Doesn't really work as you'd expect; it's also buggy as hell. IE6 will leave behind artifacts for the content after it for example.Valvulitis
You might need to put this in a relatively positioned element.Lesser
P
23

Maybe negative margins and absolute positioned elements in relative positioned elements.

See How would YOU do this with CSS? for examples.

Palter answered 9/3, 2009 at 23:17 Comment(1)
care to rather explain? also plz wiki itDemitasse
Q
21

Take a look at Webkit CSS Transformations, e.g. -webkit-transform: rotate(9deg);

sample

Quixotism answered 9/3, 2009 at 23:17 Comment(4)
How much support is there for this one accross major browsers?Sejm
@Shawn: WebKit based browsers (Safari + Chrome), Firefox 3.1+ (I think), and Opera 10.5. So it's pretty widespread, except for IE--as always. :)Culminate
You can transform using the proprietary IE "filter:" thing like you used to do for transparent PNGs. Though the IE transform/rotation parameters require some basic trigonometry calculations. And standard obnoxious "filter:" bugs still apply.Rato
Ahahaha, just rotated this text block! So much fun. Going to write a greasemonkey script to mess with people.Kipkipling
L
15

Last week I came across an amazingly useful CSS property I had never heard of:

text-rendering: optimizeLegibility;

Safari, Chrome and Firefox all understand this property, and when set enable advanced kerning and ligatures. Here's a great demo.

Labile answered 9/3, 2009 at 23:17 Comment(2)
it makes Chinese characters look horrible on some browsers/systemsDemitasse
This is an SVG property that those browsers happen to support on HTML elements.Ahlgren
M
15

Not really a feature, but useful nonetheless: The child selector works in all browsers except IE6, allowing you to isolate IE6 without using hacks or conditional stylesheets or invalidating your code. Thus, the link in the following code will be red in IE6, blue in every other browser.

CSS

/*Red for IE6*/
.link {color:#F00;}
/*Blue for everything else*/
#content>.link {color:#00F;}

HTML

<div id="content">
    <a class="link" href="#">Link</a>
</div>

Here is a list of selectors (for CSS2) and a browser compatibility chart.

Metallurgy answered 9/3, 2009 at 23:17 Comment(2)
I'm pretty sure child selectors ARE a feature. =]Peterkin
They ARE a feature, but the fact that you can use them to isolate IE6 is more of a trick.Metallurgy
W
15

My ones are:

  • all properties of aural sheets like azimuth, pitch...
  • some properties of the print module like page-break-after: avoid;
  • counter-increment: section 1;
  • border-collapse: collapse;
  • background-color: transparent;
  • outline: 1px solid...
Whimwham answered 9/3, 2009 at 23:17 Comment(0)
S
14

Transparent PNG in IE6 This fixes PNG transparency in IE6. Set background to non and include the image in filter. No need for any javascript or htc.

.whatever {
   background: none; /* Hide the current background image so you can replace it with the filter*/
   width: 500px; /* Must specify width */
   height: 176px; /* Must specify height */
   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='vehicles.png');
}

Sets page-breaking behavior after an element - Cross browser

table {
   page-break-after:always
} 

You can use the properties always, avoid, auto, left, right, inherent. Read docs at http://www.w3schools.com/CSS/pr_print_pageba.asp

A way to number sections and sub-sections with "Section 1", "1.1", "1.2", etc - Cross browser

h2:before 
{
   counter-increment:subsection;
   content:counter(section) "." counter(subsection) " ";
}

http://www.w3schools.com/CSS/pr_gen_counter-increment.asp

Collapse Table borders into a single border or detached as in standard HTML - Cross browser

table
{
   border-collapse:collapse;
}

http://www.w3schools.com/css/pr_tab_border-collapse.asp

Remove selection Border or dotted line from button or input fields. Has other great uses - Cross browser

button{
   outline:0;
}

http://www.w3schools.com/CSS/pr_outline.asp

* html for 100% height in IE6

* html .move{
   height:100%;
}

Allow long words to break and wrap onto the next line - CSS3 Cross browser

.whatever {
   word-wrap:break-word;
}

http://www.w3schools.com/css3/css3_pr_word-wrap.asp

Shorthands

Before

font-size: 1em;
line-height: 1.5em;
font-weight: bold;
font-style: italic;
font-family: serif 

After

font: 1em/1.5em bold italic serif;

Before

background-color: #fff;
background-image: url(image.gif);
background-repeat: no-repeat;
background-position: top left;

After

background: #fff url(image.gif) no-repeat top left;

Before

list-style: #fff;
list-style-type: disc;
list-style-position: outside;
list-style-image: url(image.gif) 

After

list-style: disc outside url(something.gif);

Before

margin-top: 2px;
margin-right: 1px;
margin-bottom: 3px;
margin-left: 4px 

After

margin:2px 1px 3px 4px; /*also works for padding*/
margin:0; /*You can also do this for all 0 borders*/
margin:2px 3px 5px; /*  you can do this for top 2px, left/right 3px, bottom 5px and ;    
Stinger answered 9/3, 2009 at 23:17 Comment(2)
outline: 0; Don't do it! outlinenone.comConceal
whenever I see w3schools links I cringeSemifinal
P
9

You can create scrolling areas without resorting to frames by using CSS's overflow property. Example:

div.foo {
    border:   1px solid;
    width:    300px;
    height:   300px;
    overflow: auto;
}

overflow: auto means if the content can't fit within the div, horizontal and/or vertical scroll bars will appear as needed.

overflow: scroll means both scroll bars will always be present. If you only want one scroll bar to always be present, use overflow-x or overflow-y (which are supported by modern browsers and IE6).

Some of you may be thinking "duuuh", but I was surprised to learn that scrolling areas can be created without frames.

Pigment answered 9/3, 2009 at 23:17 Comment(3)
Beware, I discovered recently that the iPad (and presumably iPhones and iPods) do not support this, by which I mean it doesn't display the scrollbar and cuts off your content.Buckeye
iOS, or, more precisely, mobile Safari support this just fine. What they don't do, though, is show scroll bars. You have to two-finger scroll. So, not always intuitive. Not sure why apple made that decision.Commutator
@John iOS versions before 5 make you use two fingers to scroll overflow:scroll content, but you can use iScroll 4 to fix this. iOS 5, however, doesn't need that script and does it all natively. Ad@mThanatopsis
L
8

The :before and :after pseudo-elements

The following rule causes the string "Chapter: " to be generated before each H1 element:

H1:before { 
  content: "Chapter: ";
  display: inline;
}

For more, http://www.w3.org/TR/CSS2/generate.html

Ladylike answered 9/3, 2009 at 23:17 Comment(0)
A
7

We can display the style tag as a block element and edit CSS dynamically using the HTML5 contenteditable attribute. Demo Here.

   <body>
       <style contenteditable>
           style {
            display: block;
           }
           body {
            background: #FEA;
           }

       </style>
   </body>

Credits: CSS-Tricks

Albin answered 9/3, 2009 at 23:17 Comment(2)
It's worth noting that this does not work in IE -- see: msdn.microsoft.com/en-us/library/ms537837(v=vs.85).aspxTuning
I wouldn't depend on it working anywhere. It's invalid HTML put to a particularly hacky use.Lauralauraceous
W
7

Inline @media assignments:

/* Styles.css */
.foo { ... bar ... }
...
@media print{
    .ads{display:none}
}

So that you can get rid of another HTTP request.

Wyne answered 9/3, 2009 at 23:17 Comment(0)
N
7

inline blocks (alternative to floating divs):

.inline_block
{
    display:-moz-inline-box;
    display:inline-block;
}  

Don't apply this class to a div! it won't work! apply it to a span (or an inline element)

<span class="inline_block">
</span>
Nmr answered 9/3, 2009 at 23:17 Comment(6)
IE6 only supports with inline elements, am I correct?Boneyard
not sure which browser supports or doesn't support divs, but that's why I said it doesn't work on divs!Demitasse
Why would divs not be supported? A div is a span with display: block (but may have extra styling by a browser or author stylesheet).Peterkin
don't you know how browsers are nice to us? it doesn't work on an element that has block display, online inline elements.Demitasse
@Peterkin while you are correct, don't underestimate IE's implementation (or lack) of standardsBoneyard
.iblock { display: -moz-inline-stack; display:inline-block; zoom:1; display:inline; / Alignment Fix */ vertical-align:top; }Counterpoison
C
7

Not so much hidden features, but a question featuring CSS tips which every beginning developer should know about

Confidential answered 9/3, 2009 at 23:28 Comment(0)
P
6

I have never thought that using css 'border' property I can make different shaped triangle. Here is the link to go,

(edit) The following link does not work anymore. http://www.dinnermint.org/blog/css/creating-triangles-in-css/

From now, you can try the following, http://jonrohan.me/guide/css/creating-triangles-in-css/

Policlinic answered 9/3, 2009 at 23:17 Comment(2)
This link is no longer valid.Josie
@GeorgeEdison: You are right. I will try to find alternative source to show the example.Ladylike
B
6

Currently only for WebKit but quite interesting: CSS Animations

Boneyard answered 9/3, 2009 at 23:17 Comment(0)
C
6

Not really "hidden", but understanding the box model and positioning model will help tremendously.

Like, knowing that a position: absolute element is positioned relative to its first parent that is styled with position: relative.

Calamus answered 9/3, 2009 at 23:17 Comment(3)
No, it's positioned relative to the closest parent with any 'position:' other than the default, 'static'Innermost
@Innermost - almost, "fixed" also doesn't countMisname
@annakata: Are you sure? I just tried it quickly, and the absolute div was positioned inside it's parent - a fixed div. I added another absolute div with with the same specs but with no parent (well, body would be its default parent), and it was positioned differently than the one inside the fixed - i.e. it was positioned at the bottom of the page. So I assume absolute-inside-fixed works.Coriolanus
E
5

Word wrapping can be done easily using css, without any help of server-side technology.

word-wrap: break-word;
Extremism answered 9/3, 2009 at 23:17 Comment(0)
H
3

Cross-browser (IE6+, FF, Safari) float alternative:

.inline-block {
    display: inline-block;
    display: -moz-inline-box;
    -moz-box-orient: vertical;
    vertical-align: top;
    zoom: 1;
    *display: inline; }
Hallo answered 9/3, 2009 at 23:17 Comment(2)
This only works on elements in IE6/7 that are inline by default right?Boneyard
Works on DIV, which is a block element.Hallo
D
3

Cross browser inline-block works on block and inline elements using the combined declarations:

.column { 
-moz-inline-box; -moz-box-orient:vertical; display:inline-block; vertical-align:top; 
} 

for standards browsers including Firefox 2, and:

.ie_lte7 .column { display:inline; } 
Dennett answered 9/3, 2009 at 23:17 Comment(0)
V
3

Another IE6 selector

* html .something
{
  color:red;
}

Fixing random IE6 rendering bugs - apply zoom:1 which will trigger layout.

Valentinevalentino answered 9/3, 2009 at 23:17 Comment(1)
Note zoom will not validate... if this matters to you then try height: 1% or similar to trigger hasLayoutBoneyard
B
2

I have no Idea whether this is a hidden feature, but I just wowed seeing this: http://www.romancortes.com/blog/css-3d-meninas/

Blackmarketeer answered 9/3, 2009 at 23:17 Comment(0)
B
1
.class {
/* red for chrome, ff, safari, opera */
background-color: red;
/* green for IE6 */
.background-color: green;
/* blue for IE7+ */
_background-color: blue;
}

will render your <whatever> background different in those browser categories

Brewery answered 9/3, 2009 at 23:17 Comment(5)
Browser hacks aern't features? Oh well, still useful!Boneyard
It's best practice to add separate stylesheets for IE6 and IE7 using Conditional Comments quirksmode.org/css/condcom.html instead of relying on rendering engine bugs.Aribold
This is a really BAD practice. Listen to @Aribold ;)Redware
Browser hacks aren't features. They are bugs.Commutator
Even better, use Paul Irish's sweet method: paulirish.com/2008/…Bobo
S
0

The border-radius stuff is part of the CSS3 specification. As CSS3 is still not completely finished the more progressive browsers in the meantime implement parts of it with their own properties (-moz, -webkit). So we can already enjoy rounded corners, cleanly coded in pure css.

Unfortunately the other big player in the browser market still shows no sign of implementing css3 features.

Salchunas answered 9/3, 2009 at 23:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.