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

走远了吗. 提交于 2019-12-10 14:47:26

问题


<a href="#">
        <img width="103" height="100"  src="img source">
    </a>

for the above html code I am using the following css

a {
    border-bottom-style: dotted;
    border-bottom-width: 1px;
}

a img {
    border: 0 none;
}

Basically what I am trying to achieve here to underline the text links while keeping img links without any underline. however I guess by styling the text links I am also styling image links, I want any image in a link should not be underlined.

Can any one suggest work around for this?


回答1:


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.




回答2:


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




回答3:


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.




回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/9060763/remove-link-underline-from-image-only-if-the-anchor-tag-contains-an-img

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!