Reputation: 540
I'm using min-height
and min-width
on a div that will be filled dynamically. Is there a way to ensure that the width will always be the same as the height (square), using css?
Upvotes: 4
Views: 1357
Reputation: 105893
you can use vertical margin or padding with % values, it will takes parent width as reference.
basicly:<div id="ratio1-1"> <div>content</div></div>
and for CSS
#ratio1-1 {
width:80%;
}
#ratio1-1:before {
display:inline-block;
padding-top:100%;/* equals width of its tag parent */
content:'';
}
#ratio1-1 > div {
display:inline-block;
max-width:95%;/ preserve it to fall under pseudio-element */
}
You can even vertical-align pseudo-element
and div
to top, center, bottom
or whatever else value you want to play with.
here an example wih another ratio used to fit to image background ratio and content vertical aligned : http://codepen.io/gc-nomade/pen/letdh
root tag can be displayed as table and pseudo and child displayed as table-cell;, pseudo takes 0 for width.
Upvotes: 1
Reputation: 1023
It would help if you posted your code, but I think you're barking up the wrong tree with min-width and min-height. I see @GCyrillus has posted a similar solution, but here's another way to achieve this with css using percentages:
<div class="square"></div>
.square {
width: 75%;
height: 0;
padding-bottom: 75%;
outline: solid 1px red;
}
You might want to add overflow: hidden;
or visible
to suit. This will not adjust to fit content, just based on relative container size.
Upvotes: 0
Reputation: 12017
It would not be possible to assure this using CSS, but you can use JavaScript:
If you need the min-width
and min-height
in particular and want to make them the same, you can use:
var mheight = document.getElementById('divID').style.minHeight;
var mwidth = document.getElementById('divID').style.minWidth;
if (mheight !== mwidth) {
mheight = mwidth + 'px';
}
However, if you want to make sure that the width
is always equal to the height
, you should use offsetWidth
:
var height = document.getElementById('divID').offsetHeight;
var width = document.getElementById('divID').offsetWidth;
if (height !== width) {
document.getElementById('divID').style.height = width + 'px';
}
Upvotes: 0