有没有一种方法可以使用变换比例使内容自动适合父div?

时间:2020-05-19 15:55:40

标签: css

考虑一下:

enter image description here

有了用于缩放内容的确切数字( override fun onActivityResult( requestCode: Int, resultCode: Int, data: Intent? ) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == SMS_REQUEST_CODE && resultCode == Activity.RESULT_OK) { val otp = data?.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE) ?: "" et_otp?.let { it.setText(otp) adjustOtpSelection(it) } } ),我们可以实现以下目标:

enter image description here

是否可以在不使用精确数字的情况下实现这种缩放?内容将是可变的,因此它必须适用于任何内容。

CodePen

transform: scale(0.62);
.container {
  width: 200px;
  height: 200px;
  background: yellow;
}

/*
.content {
  transform: scale(0.62);
  transform-origin: 0 0;
}
*/

2 个答案:

答案 0 :(得分:0)

这也需要Javascript的帮助。在Javascript中获取容器 div和 content div的宽度和高度。然后,以下技巧可能会有所帮助:

scale = min( 
  availableWidth / contentWidth, 
  availableHeight / contentHeight 
);

答案 1 :(得分:0)

不幸的是,只有清晰的CSS是不可能的。为您制作了比例脚本。

$(document).ready(function() {

  let containerW = $('.container').outerWidth(),
      containerH = $('.container').outerHeight(),
      contentW = $('.content').outerWidth(),
      contentH = $('.content').outerHeight();
  
    if ((containerW - contentW) < (containerH - contentH)) {
      let ratio = containerW / contentW;
      $('.content').css({'transform' : 'scale('+ratio+')'});

    }  else {
      let ratio = containerH / contentH;
      $('.content').css({'transform' : 'scale('+ratio+')'});

    } 
  
});
.container {
  width: 200px;
  height: 200px;
  background: yellow;
  position: relative;
}

.content {
  transform-origin: 0 0;
  position: absolute;
  left: 0;
  top: 0;
  white-space: pre;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="content">
    sdfdsfsdfsdfdsfsdsdfdsfsdfsdfasdfsdfasdasdasdasd
    sdfdsfsdfsdfdsfsdsdfdsfsdfsdfasdfsdfasdasdasdasd
    sdfdsfsdfsdfdsfsdsdfdsfsdfsdfasdfsdfasdasdasdasd
    sdfdsfsdfsdfdsfsdsdfdsfsdfsdfasdfsdfasdasda
    sdfdsfsdfsdfdsfsdsdfdsfsdfsdfasdfsdfasdasdasdasd
    sdfdsfsdfsdfdsfsdsdfdsfs
    sdfdsfsdfsdfdsfsdsdfdsfsdfsdfasdfsdfasdasdasdasd
    sdfdsfsdfsdfdsfsdsdfdsfsdfsdfasdfsdfasdasdas
    sdfdsfsdfsdfdsfsdsdfdsfsdfsdfasdfsdfasdasdasdasd
    sdfdsfsdfsdfdsfsdsdfdsfsdfsdfasdfsdfasdasdasdasd
    sdfdsfsdfsdfdsfsdsdfdsfsdfsdfasdfsdfasdasdas
    sdfdsfsdfsdfdsfsdsdfdsfsdfsdfasdfsdfasdasdasdas
    sdfdsfsdfsdfdsfsdsdfdsfsdfsdfasdfsdfasdasdas
    sdfdsfsdfsdfdsfsdsdfdsfsdfsdfasdfsdfasdasdasdas
  </div>
</div>