如何在图像的中心点定位文字?

时间:2017-06-10 14:03:13

标签: html css angularjs

我想将文字放在图像的中心点上。我试过这个:

<span ng-repeat="image in post.postImages" ng-init="image.showDeleteIcon= false" ng-style="{ 'display' : ($index > 3) ? 'none' :'inlne'}" ng-mouseover="image.showDeleteIcon=true" ng-mouseleave="image.showDeleteIcon=false">
  <a id="{{$parent.$index}}{{$index}}" onclick="SetDataGallery(this.id)" ng-href="../upload/post-photos/{{image.attachmentURL}}">
    <img class="img-responsive feed-photo" ng-src="../upload/post-photos/{{image.attachmentURL}}" alt="Photo" style="display:inline;" ng-style="{ 'opacity' : ($index == 3 && post.postImages.length > 4) ? '0.5' : '1' }">
    <a href="#" class="imgDelete" ng-if="post.timelineStrore.hasControl" ng-show="image.showDeleteIcon" title="Delete Photo" ng-click="DeletePostAttachment(post.timelineStrore.id, image.postAttachmentId,'image')">
      <i class="fa fa-close"></i>
    </a>
    <i class ="imgcounter" style="color: #23527c;cursor: pointer !important;font-family:Times, Times New Roman;font-style:normal;font-size:50px;" ng-if="post.postImages.length - 4 > 0 && $index == 3" id="{{$parent.$parent.$index}}{{$index}}" onclick="$('#' + this.id).click();"> + {{post.postImages.length - 4}}</i>
  </a>
</span>

和我的css:

.imgcounter {
  z-index: 500;
  text-align: center;
  margin-top: 45 px;
  position: absolute;
  color: tomato;
  cursor: pointer !important;
  margin-left: -120 px;
}

它有效,但不适用于不同大小的图像,如下所示:

1st image 2nd pic

正在显示文字,但根据图片尺寸,文字未正确定位。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

显然,像你一样对特定值进行硬编码并不能适用于任意大小。

垂直居中元素有lots and lots of techniques(水平是微不足道的)。这是一个简单的问题:

&#13;
&#13;
List<JsonErrorMessage> jsonErrorMessages = new ArrayList<>();
            int i = 0;
            for (ProcessingMessage message : report) {
                i++;
                jsonErrorMessage.setErrorNumber(i);
                jsonErrorMessage.setMessage(message.asJson());
                jsonErrorMessages.add(jsonErrorMessage);
            }

            return (new ResponseEntity(jsonErrorMessages, headers, HttpStatus.BAD_REQUEST));
&#13;
span {
  display:inline-block;
  position:relative;
}

.imgcounter {
  font-size: 40px;
  color:#FFF;
  
  z-index:2;
  position: absolute;
  transform: translate(-50%,-50%); /* <-- here 50% refers to the size of .imgcounter */
  top:50%; left:50%; /* <-- here the 50% measures the containing span */
}
&#13;
&#13;
&#13;

顺便提一下,您的代码存在许多其他问题,最突出的是,您可以将<span> <img src="http://placekitten.com/350/150"> <i class="imgcounter">X</i> </span> <span> <img src="http://placekitten.com/150/350"> <i class="imgcounter">TEXT</i> </span> <span> <img src="http://placekitten.com/250/350"> <i class="imgcounter">23%</i> </span>标记嵌套在彼此之内,就像您正在做的那样,您应该下定决心是否要把你的CSS内联或放在.css文件中。 (把它放在.css文件中。)