Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Changing border-width without moving surrounding elements.

Tags:

html

jquery

css

I have the following HTML:

<div style="float:left;">
  <h2>Hover:</h2><br />
  <div class="Size" id="160x600" style="margin:10px;float:left;height:600px; width:160px;border:1px solid #90A4AF;text-align:center;position:relative">
    <div style="position:absolute;top:50%;text-align:center"> Text</div>
  </div>

  <div class="Size" id="336x280" style="margin:10px;float:left;height:280px; width:336px;border:1px solid #90A4AF;text-align:center;position:relative">
    <div style="position:absolute;top:50%;text-align:center">Text</div>
  </div>

  <div class="clear">&nbsp;</div>

  <div class="Size" id="728x90" style="margin:10px;height:90px; width:728px;border:1px solid #90A4AF;text-align:center;position:relative">
    <div style="position:absolute;top:50%;text-align:center">Text</div>
  </div>

</div>

And the following JS that changes border size on hover:

  $('.Size').hover(
  function() {
    $(this).css('borderWidth', '5px');
  },
  function() {
    $(this).css('borderWidth', '1px');
  });

The problem is that it's moving elements around it by adding the border-width to the total width of the element. Any suggestions around this?

like image 923
David Ryder Avatar asked Nov 10 '10 23:11

David Ryder


4 Answers

When I do this and I want that same +border -movement result, I like to do this:

function() { 
    $(this).css('borderWidth', '7px');
    $(this).css('margin', '-7px');
});

The negative margin brings everything back in.

You can also condense the styles into an object and pass them in one .css() call:

$(this).css( {borderWidth: '7px', margin: '-7px'} );
like image 126
Surreal Dreams Avatar answered Nov 18 '22 10:11

Surreal Dreams


Change the width and height of the element by twice the amount of the border-width change (live demo):

$('.Size').hover(
  function() {
    $(this).css('borderWidth', '5px');
    $(this).css('width', parseFloat($(this).css('width')) - 8 + 'px');
    $(this).css('height', parseFloat($(this).css('height')) - 8 + 'px');
  },
  function() {
    $(this).css('borderWidth', '1px');
    $(this).css('width', parseFloat($(this).css('width')) + 8 + 'px');
    $(this).css('height', parseFloat($(this).css('height')) + 8 + 'px');
  });

Note: This will only work if the border-width, width, and height use the same unit of length. If using a unit other than 'px', change that accordingly.

like image 34
PleaseStand Avatar answered Nov 18 '22 10:11

PleaseStand


You can use "outline" instead of border is browser support is OK with you.

like image 3
Rimantas Avatar answered Nov 18 '22 12:11

Rimantas


You could add to the padding if you subtract from the border and vice versa.

like image 2
Aaron Hathaway Avatar answered Nov 18 '22 11:11

Aaron Hathaway