MariaZ MariaZ - 3 months ago 17
Less Question

create a div square, and center it accordingly the view port using less

I am trying to create a square(or div) in the browser according the size of the screen, so I am using percentage, i want the square to be 40% of the height of the screen, and get the amount of this percentage in pixels and use it for the width in order to get a square. And also use these values to center it. I know that with javascript should be easy, but i am new to less and I am wondering how this can be done. I tried the following and doesnt work:

@base:calc(40% * 1px);

#mytransform {
background-color:#ccc;
height:@base;
width:@base;
position:absolute;
top:50%;
left:50%;
margin-top:-(@base/2);
margin-left:-(@base/2);

}


how can i transform percentage to pixels?

Answer

You Cannot Do What You Desire With Precompiled LESS

LESS is a CSS preprocessor. That means it processes the code to form it into CSS before the browser ever sees it; and as far as LESS is concerned, the browser does not exist. What that means is, 40% of the height of the browser window is totally unknown to LESS. All that it knows is 40%, having no idea what that will actually translate into for pixels at a later time.

You will either want to stick to javascript, or use extra html mark-up to get the squaring effect.

Client-Side Compiling (NOT Recommend for Production)

I need to stress the fact that client-side compiling is recommended only for development. If someone has javascript turned off, then they will get NO styling. And those that have it turned on are going to experience a slowdown in page loading.

Now, the reason you get an invalid type error is because the returned value needs to be made into a number that LESS understands (I think it is treating the returned value as a string). This can be easily done like so (see the changes to the @base assignment):

@base: (0.4 * unit(`window.innerHeight`, px));

#mytransform { 
   background-color:#ccc;
   height:@base;
   width:@base;
   position:absolute;
   top:50%;
   left:50%;
   margin-top:-(@base/2);
   margin-left:-(@base/2);
 }

My CSS Output On One Run At less2css.org

#mytransform {
  background-color: #ccc;
  height: 243.60000000000002px;
  width: 243.60000000000002px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -121.80000000000001px;
  margin-left: -121.80000000000001px;
}