KEKUATAN
KEKUATAN

Reputation: 948

Css input HTML, why absolute position changing when updating width

Why position of the input element changging on keyup, in my css I already set the div to position:absolute and only change the width on the keyup function, I want only the width of the input that change not include the position

$('.test').keydown(function(){
 var contents = $(this).val();
 var charlength = contents.length;
 newwidth =  charlength*9;
 $(this).css({width:newwidth});
});
#parent {
    position: relative;
    width: 400px;
}
  #parent div {
      position: absolute;
      left: 5px;
      right: 5px;
    top:300px;
  }
    #parent div input {
        position: relative;
  /* Safari */
  -webkit-transform: rotate(-90deg);
  /* Firefox */
  -moz-transform: rotate(-90deg);
  /* IE */
  -ms-transform: rotate(-90deg);
  /* Opera */
  -o-transform: rotate(-90deg);
  /* Internet Explorer */
  filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
        width: 100%;
    }
<!DOCTYPE html>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div id="parent">
    <div class='yyy'><input class='test' type="text" value='jjjj'></div>
</div>
</body>
</html>

Upvotes: 0

Views: 111

Answers (1)

Ilya Streltsyn
Ilya Streltsyn

Reputation: 13536

It's because the transform: rotate(...) property by default rotates the element around its center. Changing the width of the element makes its center move, so the transformed element appears to change the position. To prevent it, change the transform-origin of the element, e.g. to its left top corner (0 0):

$('.test').keydown(function(){
 var contents = $(this).val();
 var charlength = contents.length;
 newwidth =  charlength*9;
 $(this).css({width:newwidth});
});
#parent {
    position: relative;
    width: 400px;
}
  #parent div {
      position: absolute;
      left: 5px;
      right: 5px;
    top:300px;
  }
    #parent div input {
        position: relative;
  /* and please use the standard CSS instead of old prefixed junk! */
        transform: rotate(-90deg);
        transform-origin: 0 0;
        width: 100%;
    }
<!DOCTYPE html>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div id="parent">
    <div class='yyy'><input class='test' type="text" value='jjjj'></div>
</div>
</body>
</html>

P.S. Please use standard unprefixed CSS properties (transform etc.) and not their ancient experimental prefixed versions! Browsers that don't support the standard syntax are practically extinct for years. If you really need to, you can use automatic tools like Autoprefixer to generate only prefixes that your audience really needs.

Upvotes: 1

Related Questions