Sarah Jean
Sarah Jean

Reputation: 648

Apply CSS Class to Image in asp:Hyperlink?

I'm using asp:Hyperlink to render linked images dynamically based on parameters in the URL. I need to be able to add a CSS class to the rendered img, and can't figure out how to do that.

I know I can add "CssClass="blah"" to the asp:Hyperlink, but in the rendered HTML, only the a receives the css class. Like this:

<a href="assets/images/blah.jpg" class="blah" id="ctl00_LeftContent_alternateImage4">
<img style="border-width: 0px;" src="assets/images/blahThumbnail.jpg"/>
</a>

I've found another question that allows me to add inline style to a control, but I want to add a class to the img that asp:Hyperlink generates.

Is it possible to do something similar to this answer:

myControl.Attributes.Add("style", "color:red");

Like, maybe?:

myControl.img.Attributes.Add("class", "blah");

Upvotes: 9

Views: 16756

Answers (4)

InteXX
InteXX

Reputation: 6367

You might try something similar to this:

HyperLink1.Attributes("onmouseover") = "this.firstChild.src='Images/MouseOver.jpg'"

Upvotes: 0

Morpheus
Morpheus

Reputation: 9055

Extending @jrummell answer:

If your image is added dynamically in code behind, you can achieve the same doing the following:

<% (lnkImage.Controls[0] as Image).CssClass = "some-class"; %>

Upvotes: 0

jrummell
jrummell

Reputation: 43067

It looks like you're using the ImageUrl property of HyperLink. I would recommend creating the inner image control explicitly:

<asp:HyperLink runat="server" CssClass="linkclass" NavigateUrl="http://example.com">
   <asp:Image runat="server" CssClass="imgClass" ImageUrl="yourimage.jpg" />
</asp:HyperLink>

Upvotes: 13

Joel Coehoorn
Joel Coehoorn

Reputation: 415600

Just use the CssClass="blah" code like you were trying, but then in your css file:

.blah img {border-width: 0px;}

That targets img tags inside of elements with the .blah class.

Upvotes: 3

Related Questions