Setting parameters on the left, top, width and height using .css () and pixel values ​​works, but using percentage values, no?

In this jQuery bit , I draw a square on a div canvas as follows:

$(document).ready(function() {
    var canvas = $('#canvas');
    canvas.append('<div id="1"></div>');
    $('#1').addClass('ui-boxer')
                .css({ border: '1px solid white',
                       background: 'orange',
                       padding: '0.5em',
                       position: 'relative',
                       'z-index': 100,
                       left: 1, top: 1,
                       width: 50, height: 50});        
});

It works great. But I need to use percentages, not px values ​​for the parameters on the left, top, width and height. I tried this , but it does not work:

$(document).ready(function() {
    var canvas = $('#canvas');
    canvas.append('<div id="1"></div>');
    $('#1').addClass('ui-boxer')
                .css({ border: '1px solid white',
                       background: 'orange',
                       padding: '0.5em',
                       position: 'relative',
                       'z-index': 100,
                       left: 1%, top: 1%,
                       width: 50%, height: 50%});        
});

What am I doing wrong here? Thanks for reading.

+3
source share
2 answers

They should be strings: "1%" is not only 1%. Javascript cannot understand the% character on its own.

So:

$(document).ready(function() {
    var canvas = $('#canvas');
    canvas.append('<div id="1"></div>');
    $('#1').addClass('ui-boxer')
                .css({ border: '1px solid white',
                       background: 'orange',
                       padding: '0.5em',
                       position: 'relative',
                       'z-index': 100,
                       left: '1%', top: '1%',
                       width: '50%', height: '50%'});        
});
+7
source

you need to specify the percentage:

width: '50%'
+2

Source: https://habr.com/ru/post/1774473/


All Articles