Question

I want to set the height of a div based on CSS expression.

Basically it should be set as some % (say 90%) of the viewport width I tried the following, but is not working;

height:expression(document.documentElement.clientWidth ? document.documentElement.clientWidth : window.innerWidth );

I am looking at a cross-browser way of doing this (IE7+, FF4+, Safari)

Was it helpful?

Solution

CSS expressions are not supported anywhere except IE (and are considered a bad idea even there).

However, there isn't really another way of doing what you're asking, at least not using just CSS.

The only alternative is to use Javascript, and this is what I think you're going to have to do.

In fact, IE's CSS expressions are themselves Javascript, which allows quite powerful expressions, but also has the negative effect of removing the abstraction of layout and script. This is why they're frowned on, but there are use cases such as yours where pure layout requires some form of expression.

As I say, there really isn't any answer for you right now in CSS.

There might be some hope for the future, as Google are currently experimenting with some enhancements to CSS which include variables. Article about it here: http://johanbrook.com/design/css/webkit-css-variables-mixins-nesting/. However, I'm not sure whether even this would allow the kind of expressions you're needing.

So possibly this is something that might continue needing needing Javascript into the future. It certainly does for now, either way.

OTHER TIPS

You're combining CSS and javascript, which will not work.

You either want to just set height:90%; (which will do 90% of the width of the parent element, not the page - unless the div is at the root of the page).

Otherwise you should create a javascript block (preferably as part of an onload script), e.g... (not tested)

<body onload="document.divName.style.width=(document.documentElement.clientWidth ? document.documentElement.clientWidth : window.innerWidth)*0.9">

Edit - Thanks @Chris for pointing out that the questioner was asking for the height to be set, not the width.

I think javascript is your only way of doing this...

<body onload="document.divName.style.height=(document.documentElement.clientWidth ? document.documentElement.clientWidth : window.innerWidth)*0.9">
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top