0

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.

kvanbere
  • 3,289
  • 3
  • 27
  • 52

2 Answers2

3

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.

Andy G
  • 19,232
  • 5
  • 47
  • 69
0

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.

Community
  • 1
  • 1