I need to make a 'div' tag with left and right margin in percentage. For example, left margin is 25% of parent element's width, right margin is 50% of parent element's with (right margin is distance from left-most side of parent element to right-most side of 'div'). I have tried this code: <div id="parent"> <div id="cover" style="width: 50%"> <div id="target" style="margin-left: 25%"> </div> </div> Code (markup): However, 'margin-left' of 'target' div is 25% of 'cover' div's width instead of 'parent' div's width. How can I solve this problem?
is this what you're trying to do? if yes, just remove the parent width and border, and target background color.
No. Right margin is distance from left-most of 'parent' element to right-most of 'target' element. Margins are in percentage of width of 'parent' element. My code works with margins in pixel but not in percentage.
understand that the styles would only affect the element it is being attached to, so you can't set a margin for a child based on its parent's values. you can, however, give the parent a padding, which would have the same effect. something like <div id= parent style="padding:0% 25% 0% 50%"> or the like, and remove the margin from the child.
Thanks for your suggest but using padding make new problem: width of parent element is expanded. For example, if 'width' is 100px, 'padding-left' is 20px, then actually element's width is 120px.
hmm does it really do that? i guess you would have to reduce the parent's width to compensate for it, or do something silly like set the child's margin via javascript like <div id=child onload="this.style.marginleft=this.parentNode.style.width*0.25"></div>. note this won't work, not exactly, because this.parentNode.style.width will give a string like 1000px, so you have to parse it into an int, multiply it, than add px to the int and set it to the margin. its sort of confusing, if you really want to do this and still need help, just let me know, but i would suggest playing around with padding, i did not padding increased the width?