Home › Forums › JavaScript › Help using jQuery to center an element horizontally and vertically over varying image dimensions.
- This topic is empty.
-
AuthorPosts
-
October 28, 2010 at 12:08 am #30666
Historical Forums User
ParticipantHello, I’m creating an image gallery consisting of thumbnails with varying dimensions. I have created a hover effect that does a fadeIn so that a magnifying glass appears above the image indicating the image is enlargeable (in a modal window). However, I would like this magnifying icon to be positioned directly in the center of whatever image it is on. Lets take a look at my code….
Markup (first ‘<' removed): ul class=”thumbnails”>
li>
a href=”#”>
img src=”#” width: “150px” height:”200px”>
/a>
/li>li>
a href=”#”>
img src=”#” width: “320px” height:”200px”>
/a>
/li>
/ul>Script:
CSS:
ul.thumbnails {
width:100%;
margin-top: 20px;
overflow:hidden;
}ul.thumbnails a span {
display:none;
background-image:url(../images_layout/magnifyingglass.png);
background-repeat:no-repeat;
width:50px;
height:50px;
position:absolute;
}Could anyone help me out? I’m inexperienced with Jquery and don’t know what I’m doing wrong!
October 28, 2010 at 5:35 pm #79440akeenlabs
ParticipantIt looks like the styling for the magnifier is based on a “span” tag but the span tag never gets created. In my tests, elem.append(“”) does not generate a span tag. Try this instead elem.append($(“<span />”)).
Also, your “a” tags will probably need the “position: relative” style for their absolutely positioned children (i.e., the new span) to display correctly.
Also, when calculating the left and top styles for the magnifier, you need to take into account the actual height and width of the magnifier. For example, left should be something like (this.outerWidth()/2)-(span.width()/2) and that value doesn’t need to be negative.
Warning: I haven’t tested this all the way, so I hope it helps.
October 28, 2010 at 8:07 pm #79027Historical Forums User
Participant@akeenlabs – thanks for the comment. I was typing a response when I suddenly figured this out in css through good-ole’ firebug. I’m still using jQuery to append the tags and for the animations, but adjusted my css as follows;
ul.thumbnails a span {
display: none;
background-image:url(../images_layout/magnifyingglass.png);
background-repeat: no-repeat;
width: 50px;
height: 50px;
position: absolute;
margin-left: -25px; /* negative half of width to adjust for left 50% attribute*/
left: 50%;
margin-top: -25px; /* same idea as above */
top: 50%;
}Boy do I feel silly… over-complicating things once again.
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.