Search code examples
jquerypositioncss

how to write a CSS rule that only applies if position:fixed is not supported or Jquery-test for position:fixed?


I have two CSS files and I can only edit the 2nd file.

My HTML element:

<div class="ui-header ui-header-fixed"></div>

First CSS file sets:

.ui-header        { position: relative };
.ui-header-fixed  { position: fixed };

So when position:fixed is not supported, the CSS falls back to position:relative. However, I need it to fallback to position:absolute in this specific case only.

I'm looking for a way to override the above CSS from the 2nd file with position:absolute, but only if position:fixed is not supported.

Question:
Is this possible at all? I can't use Jquery to change the CSS directly, but if there is a JQuery test for position:fixed being supported, that would be useable (set a class add a CSS rule)


Solution

  • Can you edit the element? In your second stylesheet (assuming it is listed second in the head), add

    .ui-header-abs        { position: absolute };
    

    and change the element itself to

    <div class="ui-header ui-header-abs"></div>
    

    Failing that: If you mean for one document only, and you can edit its <head> element, you might want to try inserting

    <style type="text/css">
    .ui-header        { position: absolute }
    .ui-header-fixed  { position: fixed }
    </style>
    

    I'm fairly sure you don't actually need the second rule, actually. The precedence rules still trip me up sometimes, but IIRC a style element in the document overrides an external stylesheet (for the same selector), so this should override the two rules in that first (uneditable) stylesheet.

    If you can't get that style element into the header, it will probably work in the body element, but that's not valid.


    I'd need to play with it, but this should be solvable without DOM trickery using plain old CSS and its precedence rules; I don't understand why there's a need to complicate matters with jQuery in this case.