Css-Only Square Div Fitting Inside Rectangle Div

CSS-only square div fitting inside rectangle div

You can:

  • Place a replaced element with a 1:1 ratio inside the square.

    For example, it can be a 1px × 1px squared image, or a canvas.

    Style this replaced with height: 100%, so that it spans the entire square vertically.

    Let it have the default width: auto, so that its width respects the 1:1 aspect ratio.

    Style it with display: block to avoid the extra space below image problem.

  • Make the square use the shrink-to-fit width algorithm to calculate its width, so that it will have a 1:1 ratio too.

    You can achieve this by floating it or with display: inline-block.

  • If you want the square to have contents, place them in an absolutely positioned wrapper in order to prevent them from altering the sizes of the square.

    Make that wrapper as big as the square with top:0; right:0; bottom:0; left:0, and make the square its relative container.

This should work. However, for some reason browsers do not seem to update the width when the window is resized, so it only works initially. Forcing a rerender with JS solves this problem.

var s = document.getElementById('square'),    p = s.parentNode,    n = s.nextSibling;window.addEventListener('resize', function() {  // Force a rerender  p.removeChild(s);  p.insertBefore(s, n);});
html, body, #square, canvas {  height: 100%;  margin: 0;  display: block;}#square {  float: left;  position: relative;  background: red;}#contents {  overflow: auto;  position: absolute;  top: 0;  right: 0;  bottom: 0;  left: 0;}
<div id="square">  <canvas height="1" width="1"></canvas>  <div id="contents">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor. Pellentesque auctor nisi id magna consequat sagittis. Curabitur dapibus enim sit amet elit pharetra tincidunt feugiat nisl imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros. Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.</div></div>

How to style a div to be a responsive square?

Works on almost all browsers.

You can try giving padding-bottom as a percentage.

<div style="height:0;width:20%;padding-bottom:20%;background-color:red">
<div>
Content goes here
</div>
</div>

The outer div is making a square and inner div contains the content. This solution worked for me many times.

Here's a jsfiddle

CSS - How do I place a rectangle in the middle of 2 squares

Instead of putting four rectangles along each border, create two per box with ::before and ::after, and push them to the border of their respective box:

html,body{margin:0}*{box-sizing:border-box;}
.grid{ display: inline-grid; grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr; height: 48vw; width: 48vw;}
.grid:nth-child(2){ float:left;}
.item{ border: solid 2px orange; position: relative; display: flex; align-items: center; justify-content: center;}
.item::before,.item::after{ content: ""; position: absolute; background-color: #000;}
.item::before{ width: 65%; height: 8%;}
.item::after{ width: 8%; height: 65%;}
.item:nth-child(1)::before,.item:nth-child(2)::before{ bottom: -3px;}
.item:nth-child(1)::after,.item:nth-child(3)::after{ right: -3px;}
.item:nth-child(2)::after,.item:nth-child(4)::after{ left: -3px;}
.item:nth-child(3)::before,.item:nth-child(4)::before{ top: -3px;}
<div class="grid">    <div class="item"></div>    <div class="item"></div>    <div class="item"></div>    <div  class="item"></div></div><div class="grid">    <div class="item"></div>    <div class="item"></div>    <div class="item"></div>    <div  class="item"></div></div>

Is there a CSS method of guaranteeing a square that fits in the window without scrolling?

I suggest using the vmin unit.

Source

From the viewport-percentage lengths documentation on MDN:

Viewport-percentage lengths define the value relative to the size of the viewport, i.e., the visible portion of the document. Viewport lengths are invalid in @page declaration blocks.

vmin

Equal to the smaller of vw and vh.

Example

Use the full page link to test it with the example in your browser.

body {
/* So the whole viewport can be used by the square. */
margin: 0;
}

#sqr {
/* Uses the 'outer' (i.e. border-box) size when setting width and height. */
box-sizing: border-box;
width: 100vmin;
height: 100vmin;
background-color: red;
border: yellow 10px solid;
}
<div id="sqr"><div>

Why are many small square divs rendered differently?

This is due to the antialiasing optimizations of the browser in conjunction with the non-integer value of your div's width and height. Try to use a size such as 5px or 6px - that should fix it.

Make a div square when there is a dynamically changing width based on percentage

This is un-tested, I do not know of how to do this in CSS only, I would use jQuery.

$('div').height($('div').width());

Place an image into a square div that handled with css pseudo element

from comment:

.left {width: 60%;} is that 60% of the screen (60vw X 60vw will do)? On a desktop, that square is hudge ... do you need to shrink img / .left to be set to a max-width too ? absolute does the job as is https://jsfiddle.net/jLzhbu4q/

with the help of object-fit and border-box, you can add paddings and keep your image ratio.

* {
box-sizing: border-box;
}

.container {
display: flex;
}

.left {
width: 60%;
background:green;
padding:2em;
box-sizing:border-box;
}

.right {
width: 40%;
padding-left: 15px;
}

.box {
width: 100%;
background-color: red;
display: flex;
align-items:center;
justify-content:center;
text-align: center;
position:relative;
}

.box img {
box-sizing:border-box;
padding:5em;
/*width: 100%;
max-height: 100%;*/
width: auto; /* op's choice */
max-width: 100%; /* op's choice */
max-height: 100%;/* op's choice */
margin: auto;
position:absolute;
top:0;
bottom:0;
right:0;
left:0;
object-fit:contain;

}

.box::before {
padding-top: 100%;
content: "";
float: left;
}
<div class="container">
<div class="left">
<div class="box">
<img src="//via.placeholder.com/800x1000" />
</div>
</div>

<div class="right">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div>

How to make square div fit into parent div

Add a mediaquery to limit width and height of the element if you are looking at the viewport in landscape mode

@media all and (orientation: landscape) {
div.stretchy-wrapper {
width: calc(100vh - 20px);
height: calc(100vh - 20px);
padding-bottom: 0;
}
}

In other words: if the width of the viewport is height, to ensure a 1:1 aspect ratio you could set the width equal to 100vh (minus some padding, if you need to) and the height should be equal to the width. Also the padding-bottom is no longer necessary when this condition occurres.

Jsfiddle fork


After your edit

Since your outercontainer is fixed in height, if the viewport width is ≥ 200px then set a fixed width and a fixed height both to 200px. otherwise use a psuedoelement to preserve the 1:1 aspect ratio:

    div.stretchy-wrapper::before {      display: block;      content: "";      padding-bottom: 100%;    }
@media all and (min-width: 200px) { div.stretchy-wrapper { width: 200px; height: 200px; } div.stretchy-wrapper::before { display: none; } } .outercontainer { max-width: 400px; height: 200px; border: 1px #9cb dashed; } .stretchy-wrapper { background: #9bc; }
<div class="outercontainer">  <div class="stretchy-wrapper"></div></div>


Related Topics



Leave a reply



Submit