kvanbere
kvanbere

Reputation: 3352

Programatically positioning things inside a parent element by percentage

I was wondering what the correct way of programatically setting an elements position inside a parent element (as a percentage) from javascript would be.

In CSS you can do something like:

left: 25%;

There are two things I would like to avoid: jQuery, and calculating an absolute position based on the current size of the parent element.

Upvotes: 0

Views: 56

Answers (2)

Nikolaos Kakouros
Nikolaos Kakouros

Reputation: 552

You could add padding to the parent element:

parent = document.getelementById("id").parentNode;
parent.style.paddingLeft = "25%";

If you want to do it on the element itself is more difficult. See this stackoverflow question for more details.

Upvotes: 0

Andy G
Andy G

Reputation: 19367

Your question is a little vague, but to change a css property programmatically you can access it using the element's style property. An example:

<div id="thisdiv"><span id="thisspan">Hello</span></div>

<script>
document.getElementById('thisspan').style.marginLeft = "25%";
</script>

The css property margin-left becomes marginLeft in JavaScript. The percentage is measured with respect to the element's parent container-element, so doesn't need to be calculated.

Alternatively, define css-styles and change the element's className.

Upvotes: 3

Related Questions