Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting left, top, width and height parameters using .css() and pixel values works, but using percentage values doesn't?

Tags:

html

jquery

css

In this bit of jQuery, I am drawing a square onto the canvas div like this:

$(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});        
});

This works fine. But I need to use percentages rather than px values for the left, top, width and height parameters. I've tried this, but it doesn't 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.

like image 849
ben Avatar asked Jan 24 '26 06:01

ben


1 Answers

They need to be strings: '1%' not just 1%. Javascript can't understand the % symbol 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%'});        
});
like image 153
Nathan MacInnes Avatar answered Jan 26 '26 18:01

Nathan MacInnes