0

I need to findout and apply tablet width from css with css expression. I have a div content. it should apply width 100% in portrait mode and When i turn to landscape the div should change the width to half of the tablet device width(tablet width/2). How to apply this expression method in css?

Pavan Kumar
  • 1,616
  • 5
  • 26
  • 38

1 Answers1

2

I'd try to steer clear of expressions, as they are limited to Internet Explorer 5,6 and 7 (what tablets runs this??), and they slow things down considerably (performance wise). Anyway, try this:

@media screen and (orientation:portrait) {
    /* Portrait styles */
}

@media screen and (orientation:landscape) {
    .element {
        width:expression(document.body.clientWidth / 2);
    }
}

You can also try more specifics - these would be considered as hacks (thanks to TheBlackBenzKid for suggesting it):

/* Windows 7 Phone - WP7 */
@media only screen and (max-device-width: 480px) and (orientation:portrait) {
}
@media only screen and (max-device-width: 480px) and (orientation:landscape) {
}
/* Apple iPhone */
@media only screen and (max-device-width: 320px) and (orientation:portrait) {
}
@media only screen and (max-device-width: 320px) and (orientation:landscape) {

}

If not using expressions, (e.g. to target other browsers and .. well, tablets) you can use a small javascript to detect the orientation, and then add a class to the element:

html:

<body onorientationchange="updateOrientation();">

Javascript:

function updateOrientation() {
    if(window.innerWidth> window.innerHeight){
        //we are in landscape mode, add the 'LandscapeClass' class to the element
        document.getElementById("element").className += " LandscapeClass";
    } else {
        //we are in portrait mode, remove the class
        document.getElementById("element").className = 
           document.getElementById("element").className.replace
              ( /(?:^|\s)LandscapeClass(?!\S)/ , '' );
}

If using jQuery, you could try this, to modify the element's (inline) CSS directly:

function updateOrientation() {
    var $width;
    if(window.innerWidth> window.innerHeight){
        $width = window.innerWidth/2;
    } else {
        $width = '100%';
    }
    $(".element").css({width:$width});
}

I have not tested any of this, but I think it will work

Klaas Leussink
  • 2,208
  • 16
  • 23