1

如下图所示,我在 H1 文本的头部放置了一个箭头图像。我通过使用margin right 和top 来做到这一点。它正在工作,但问题是如果我修改 H1 文本,那么我将不得不再次使用边距。无论文本的宽度是多少,有没有办法将箭头放在 H1 文本的末尾?非常感谢,

在此处输入图像描述

<div class="block">
    <h1><span>H1 HEADER EN UIUIUIU MOTS</span> KKJKJJKJJKJKJdJKJJK</h1><img class="arrow" src="images/arrow-down.png" alt="arrow">
  </div>
  <div class="block clear fish shadow">
</div>

CSS:

.block {
    display: block;
    clear: both;
    box-sizing: border-box;
    padding-left: 20px;
    padding-right: 20px;
    width: 980px;   
}

.arrow{
margin-right: 290px;
float: right;
margin-top: -45px;

}
4

6 回答 6

5

由于您使用的图像看起来像是用于装饰目的,因此我会使用 a代替,将其background 放置在h1最右侧,然后使用padding-right将图像推离h1. 例如,尝试:

CSS:

h1 {
    background: url(images/arrow-down.png) no-repeat right center;
    padding-right: 40px; /* tweak this */
}

代码笔示例

至于那些建议使用:after伪选择器的人,我强烈建议不要这样做,因为 :after在较旧的 IE 浏览器上不是很好(另外,对于简单的任务来说,它是一个不必要的复杂解决方案)。

于 2013-09-25T20:28:27.697 回答
3

你不能把图像放在h1的背景中并使用背景位置将其对齐到右边吗?

代码笔示例

于 2013-09-25T20:27:24.177 回答
2

你也可以用一些 jquery 来解决这个问题。

$(document).ready(function(){

    arrowMargin();
    function arrowMargin() {
        $('.block img').css('margin-left', $('.block h1').width());
    }

    $(window).resize(function(){
        arrowMargin();
    });

});

你必须在 CSS 中删除你的 margin-right。

问候提摩太

于 2013-09-25T20:39:49.850 回答
2

您可以使用CSS伪元素:after (仅适用于 iE8 和 +)

HTML:

<h1>Hi there !</h1>

你的CSS代码(假设你的图像是50px * 50px):

h1 {
    background: #eee;
    height: 50px;
    line-height: 50px;
    padding-right: 50px;
    position: relative;
    width: 300px;
}

h1:after {
    background: url('images/arrow-down.png') bottom right no-repeat;
    content: '';
    display: block;
    height: 50px;
    position: absolute;
    top: 0;
    right: 0;
    width: 50px;
}

H1 padding-right必须等于你的形象CSS width

或者干脆使用:

 h1 {
        background: url('images/arrow-down.png') bottom right no-repeat;
        padding-right: 50px;
    }
于 2013-09-25T20:33:38.507 回答
1

作为替代方案,如果图像直接位于文本之后,则可以使用伪元素 (:after)

h1:after {
  position:absolute;
  content:"";
  width:50px;
  height: inherit;
   background-image: url(path_to/images/arrow-down.png);
  background-repeat:no-repeat;
  background-position:center;
  margin-left: 10px;
}

代码笔示例

于 2013-09-25T20:30:58.397 回答
-1

您可以给 H1 标签一个类并使用 css 'after' 选择器:

http://www.w3schools.com/cssref/sel_after.asp

于 2013-09-25T20:29:54.673 回答