remove link underline from image only if the anchor tag contains an img

后端 未结 5 2036
灰色年华
灰色年华 2020-12-19 13:28

        
    

for the above html code I am using the fol

相关标签:
5条回答
  • 2020-12-19 13:49

    You could use CSS Descendent Selector

    So, in your case:

    a > img { text-decoration: none; }
    

    However, the above rule will add the style to the image (that is the descendent) and not the parent, so it might not be what you're looking for. Unfortunately, there is no CSS rule that applies styling to the parent in case of a descendent.

    0 讨论(0)
  • 2020-12-19 13:50

    If you can't set a class for each link that has an image inside of it, you prolly must use javascript. You could simply add something like this:

    jQuery(document).ready(function($) {
        var a_with_img = $('a').children()
        $(a_with_img).parent().css('text-decoration', 'none');
    });
    

    This should work, however it's never a good idea to target all the 'a' selectors with js, it's pretty heavy on the load. Might cause slowdowns to your overall pageload.

    0 讨论(0)
  • 2020-12-19 13:51

    The underline is caused by the text decoration on the a. So just apply text-decoration:none to the a.

    Edit: there is currently no CSS-only way to apply a style to "any a that has an img as its child". CSS does not have selectors for that. So you'll either have to make these as unique by giving them classes (or other attributes) and apply the CSS to those classes, or run some script that tests for imgs in as and gives those as the desired style.

    0 讨论(0)
  • 2020-12-19 13:52

    I've solved this using jquery just link the jquery.js in the head and put this in the body:

        <script type="text/javascript">
    
            $("body").ready(function () {
    
                    $("a").has("img").addClass("imglink");
    
            });
    </script>
    

    Then style the class a.imglink

    0 讨论(0)
  • 2020-12-19 14:04

    After a lot of Googling I finally found a neat trick that worked for me:

    a img { border:none; vertical-align:top; }
    

    Why this works?

    By default both anchors and images are inline elements and by applying vertical-align:top; to an image inside an anchor, we move the anchor to the top of the image. For some reason images have higher z-index than anchors.

    Source: Remove Border from Image Links

    By the way, it would work great with a parent selector like a < img ... unfortunately this isn't implemented yet, but is in the workings. Take a look here: https://stackoverflow.com/a/45530/114029

    0 讨论(0)
提交回复
热议问题