开发者

CSS sizing to fill parent, staying square

开发者 https://www.devze.com 2023-03-28 13:14 出处:网络
Is there a purely CSS-based way to size a block-level element such that it fills its parent as much as possible, but remains square?

Is there a purely CSS-based way to size a block-level element such that it fills its parent as much as possible, but remains square?


An interesting use case

I have written a very simple analogue clock using mostly CSS, and a pinch of JavaScript.

http://jsbin.com/iqicuk

It has been written scalably:

http://jsbin.com/emiyer

I would like to scale it to fill the page, but stay in proportion, obviously.

If I set the width and height of #clock to 100%, of course, it will be pulled out开发者_如何学JAVA of proportion:

http://jsbin.com/esubol


You can't do that with pure CSS, but you can do it with Javascript - and I assume you have Javascript running anyway to resize the parent element.


A solution in progress

thirtydot came up with a very clever technique that takes advantage of the fact that images with only one defined dimension scale proportionately, and he harnesses this to size the element. We now have a clock that can scale properly, but only if the viewport width is greater than the height, not the other way around:

http://jsbin.com/isixug

Likewise, if we change img and #clock to have a defined width, instead of a defined height, then we have a clock that can scale properly, but only if the viewport height is greater than the width:

http://jsbin.com/awucun


The solution

We can combine the two 'tricks' above, that each only work for one orientation, by using a media query for orientation, and specifying the right 'trick' depending on the viewport orientation. We now have a completely scalable clock, no matter what the viewport orientation or size:

http://jsbin.com/okodib


Any in flow block level element will already inherit the width from its parent. For the height however you will need to find an alternative.

I doubt this is something you will want to do but if you set your parent to position: relative; and then the child you want to make fill up that parent position: absolute;. Then specify where it needs to stick to relative to its parent with top:0;left:0;bottom:0;right:0;.

However this solution has compatibility issues in lower versions of IE and is rarely acceptable for application...


As Jens Roland already said, this is not possible through pure CSS. Maybe LESS is helpful to you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号