Home > Software design >  Why is it so difficult to style a div into a square regardless of view size?
Why is it so difficult to style a div into a square regardless of view size?

Time:04-26

I am trying to make a 100x100 'pixel' canvas similar to r/place that maintains its shape regardless of view size (ie looks good on mobile and desktop). I gave the div that houses the pixel a height and width of 90vw, and the 'pixels' a width and height of 1%. I created a little zoom feature that adjusts the size of the canvas by 10vw. Sometimes the pixels sit flush inside the canvas, but sometimes there is extra blank space left at the bottom of the canvas.

CodePudding user response:

Very big pain I recommend just using this site http://mattkersley.com/responsive/

and using @media(min-width: __px) { } to target the specific screen sizes and using a window function to resize when window size changes

CodePudding user response:

To set each pixel make sure you use vw for both the width and the height. That way it will always create a square on any screen.

The white space you see sometimes from the bottom or the right is just that one (half) pixel that just didn't fit. It's deppends on the browser you use. But you could create a border with the before styling and make sure there isn't a white space by making the border just 1px to tight.

Here a 25x25 example.

let canvas = document.querySelector('#canvas');
 
function randomRGB(){
  let red = Math.floor(Math.random() * 256);
  let green = Math.floor(Math.random() * 256);
  let blue = Math.floor(Math.random() * 256);
  return 'rgb('  red  ', '  green  ', '  blue  ')';
}

function createRow(){
  for(let i=0; i<25; i  ) {
    canvas.innerHTML  = '<div  style="background-color:'   randomRGB()   ';"></div>';
  }  
}


//It's a bit heavy with al these elements and the randomRGBs for JSFiddle so be patient.
function create25Rows() {
  for(let y=0; y<25; y  ){
    createRow();
  }
}

create25Rows();
#canvas {
  position: relative;
  display: flex;
  flex-flow: row wrap;
  align-content: flex-start;
  width: 25vw;
  height: 25vw;
  margin: 25px auto;
  transition: transform 1s;
}

/*Border both sides 10px so width should be 20px more, both cut 1px from both sides to make sure you don't have white spaces*/
#canvas::before {
  position: absolute;
  content: '';
  box-sizing: border-box;
  border: solid 10px black;
  width: calc(100%   18px);
  height: calc(100%   18px);
  top: -9px;
  left: -9px;
}

#canvas:hover {
    transform: scale(1.1);
}

.pixel{
  width: 1vw;
  height: 1vw;
}
<div id="canvas">
  <!-- Filled with JS in this example -->
</div>

  • Related