Center the background image of the enter button

This may seem like a simple fix, but let me explain it in detail.

I have a <input type="submit"/> button, and I'm trying to align the arrow to the right of the button text (which is already centered).

Here's the fiddle: http://jsfiddle.net/s6rrzsa4/4/ submit button

Now come to the problems:

  • I cannot change the <input> to <button> , as it comes from CMS).
  • The button text can be anything, which means that I can not crop the arrow image with an offset (equal to the width of the text) and use the background position :. center
  • I can’t add: after the pseudo-element of the parent div, as it makes the arrow area inaccessible.
  • As I said, the button text may change. Therefore, I cannot use percentages for the background position.
  • The button has a fixed width (sorry, forgot to add this point).
+7
jquery css
source share
4 answers

@Felix's solution is good. But in order to calculate the width of the text, it has the minus of adding a span element to the body. We can use the canvas to calculate the width of the text, but it will not be added to the DOM.

http://jsfiddle.net/s6rrzsa4/16/

 var elem = $('input'), cs = window.getComputedStyle(elem[0]), context = document.createElement("canvas").getContext("2d"), metrics, pos; context.font = cs.fontSize + " " + cs.fontFamily; metrics = context.measureText(elem[0].value.toUpperCase()), pos = (elem.width() - metrics.width)/2 + 20; elem.css('background-position','calc(100% - '+pos+'px) center'); 
+3
source share

To find the length of the text, a span dummy is used and some javascript is used to calculate background-position-x .

 var a = $("input").outerWidth(); var s = $('<span class="dummy" />').html($("input").attr('value')); s.appendTo('body'); var b = s.outerWidth(); var pos = b + (ab)/2; $("input").css({ 'background-position': pos +'px center' }); s.remove(); 

Please check the script - http://jsfiddle.net/afelixj/s6rrzsa4/9/

+4
source share

1) you can use: after a pseudo style pointer-events: none; but not supported in IE http://caniuse.com/#feat=pointer-events

2) put the > character at the end of the line

0
source share

It seems you are pretty limited in choosing β€œgood” solutions.

The easiest way I can do to do this in your situation is to get a list of all the possible text options that might be for your button and target the CSS with a value:

 div input[value="Anything"] { background-position: 200px 30px; } 

Here is your updated Fiddle: http://jsfiddle.net/s6rrzsa4/8/

0
source share

All Articles