No, and Yes (Kinda)
Okay, so the short answer is "no," not possible. The long answer is, "yes," given certain constraints and concessions (i.e. extra html markup, and limitations on what can be done).
Given this CSS:
.square {
position: relative;
margin: 20px;
display: inline-block; /* could be float */
overflow: auto; /* UPDATE: if content may overflow square */
}
.sq-setter-w {
width: 100%;
height: auto;
visibility: hidden;
}
.sq-setter-h {
width: auto;
height: 100%;
visibility: hidden;
}
.sq-content {
position: absolute;
z-index: 1;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
With this HTML:
<div class="square" style="width: 200px">
<img src="http://dummyimage.com/50x50/000/fff.gif&text=50x50" class="sq-setter-w"/>
<div class="sq-content">Here is content</div>
</div>
<div class="square" style="height: 100px">
<img src="http://dummyimage.com/50x50/000/fff.gif&text=50x50" class="sq-setter-h"/>
<div class="sq-content">Here is content</div>
</div>
<div class="extrawrapper">
<div class="square" style="width: 200px">
<img src="http://dummyimage.com/50x50/000/fff.gif&text=50x50" class="sq-setter-w"/>
<div class="sq-content">Here is content</div>
</div>
</div>
<div class="extrawrapper">
<div class="square" style="height: 100px">
<img src="http://dummyimage.com/50x50/000/fff.gif&text=50x50" class="sq-setter-h"/>
<div class="sq-content">Here is content</div>
</div>
</div>
You can get it to do what this fiddle shows.
The keys are:
- The image used needs to be a square image, as it is driving the proportional sizing (the
img
element is the only element that can do such proportional work, as it can base its size off the proportion of the image itself).
- You have to know if you are going to set the
width
or the height
so that you can set the image class correctly to size it. Optionally, set the width
or height
on the img
itself, then you don't need to worry about setting a class to the 100%
value. My demo was assuming that you set the size on the wrapper div (my .square
class).
- To get the
div
to collapse around the img
which is driving the proportional sizing you need to set display: inline-block
or a float
on the div
(as noted in the css above).
- Because of #3, if you want that
div
to act more "block-like" you need to give them an extra wrapper div
like the third and fourth ones show.
Obviously, there is a lot of extra mark-up involved in this solution. So in many ways it is better to say "just use javascript," but I did want to prove that it could be done (at least in some cases) purely with HTML and CSS.
Update: To Show Flexible Sizing Possibility
See this fiddle for percentages driving the size, with this html example (width
set to 30%
):
<div class="square" style="width: 30%">
<img src="http://dummyimage.com/50x50/000/fff.gif&text=50x50" class="sq-setter-w"/>
<div class="sq-content">Here is content</div>
</div>