Reputation: 11
I am writing a web-app using React.js. I have come to the point where I need to control the position of a note on a bar. I intend having two buttons (one for up, one for down) and have the bar and note be two separate .svg image files that I will somehow draw ontop of each other. Like this: SVG note ontop of SVG bar
So my question is: How can I draw an SVG ontop of another SVG and control its position (dynamic position)? I have tried using
style={{position:'fixed'}}
for the note but the formatting gets all messed up.
Edit: .svg image files.
Upvotes: 1
Views: 2480
Reputation: 835
A page element with relative positioning gives you the control to absolutely position children elements inside of it.
If you give the note position: absolute
, you'll be able to position it wherever you want, relative to the parent.
.parent {
position: relative;
}
.note {
positition: absolute;
/* place note in the top left */
left: 0px;
top: 0px;
}
See here for more on this technique.
Here's a snippet using <div>
s instead of SVGs, run it for an example:
function moveUp() {
document.getElementById("note").style.top = "0.5rem";
}
function moveDown() {
document.getElementById("note").style.top = "2.5rem";
}
.container {
position: relative;
}
.bar {
width: 15rem;
height: 4rem;
background-color: lightblue;
}
.note {
position: absolute;
top: 1.5rem;
left: 1rem;
width: 1rem;
height: 1rem;
border-radius: 1rem;
background-color: red;
}
<div class="container">
<div class="bar"></div>
<div class="note" id="note"></div>
</div>
<div class="buttons">
<button onclick="moveUp()">up</button>
<button onclick="moveDown()">down</button>
</div>
Upvotes: 1
Reputation: 21811
position:absolute
will give you the freedom to position the <img>
tag freely - in relation to the next parent element with a position:relative
property. For example like this:
<div style={{position: 'relative'}}>
<img src="bar.svg"></img>
<img src="note.svg" style={{
position: 'absolute',
left: x,
top: y
}}></img>
Upvotes: 0