I try to make via css the same (a priori unknow) Width and Height.
There are multiple ways of doing it (1, 2) but any didn’t work in my case:
.cont{height: 150px; width: 300px; background: lightgray;} /*size is unknow*/
.cont>div:nth-child(odd){background:pink;}
.cont>div:nth-child(even){background:green;}
.bordered{border:1px solid red;}
.square{
position: relative;
width: auto; /* desired width */
}
.square:before{
content: "";
display: block;
padding-top: 100%; /* initial ratio of 1:1*/
}
.square>div{
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="cont">
<div class="col-xs-4">a
<div class="square"><div class="bordered"><img src="http://lorempixel.com/125/100">red bordered SQUARE auto width does not work, content size is unknow!</div>
</div>
</div>
<div class="col-xs-4">b
</div>
<div class="col-xs-4">c
</div>
</div>
Preconditions:
- The parents of the square or their dimensions are unknown.
- The content of the square or its dimensions are unknown(I put an image with some text inside just to give to the container some heterogeneous content).
- So I can’t control any of these(parents or children), nor modify its properties.
- The only thing I can control is the
.square
element or/and its immediate(and unique) child.
Question: How to achieve having a CSS square(red bordered) in that case, without having to specify the width in pixels (keep it “auto” by content)?
2
Answers
I’ve called on the img inside of the squared class to match the dimensions of it’s container. Just two adjustments, one with the css for the img element:
and I adjusted the height of the lorempixel image you’re requesting.
Check out this jsfiddle
try making the class of the
<img>
tag bordered:I also changed the size of the
.cont
div so the image will fit.