提问者:小点点

将HTML元素缩放到父级宽度


我试图创建一个工作在HTML应用程序内部的A4文档的幻觉,并希望只使用CSS将我的A4页面缩放到它们的父元素大小。 当父元素变小时,因为(例如)浏览器是缩放的,我希望内容保持相同的比例,但更小,缩放以适应父元素。

纯粹的CSS解决方案是我的首选,但是如果没有其他方法,我不介意使用JavaScript来测量父级的尺寸并缩放子级以适应。

JS中的示例代码:

    var page = document.getElementsByClassName("page")[0];
    var scaleX = page.parentElement.clientWidth / page.clientWidth;
    
    if (scaleX < 1) {
      page.setAttribute("style", `transform:scale(${scaleX});`);
    }

我目前的造型如下:

  .page-container {
    height: 7cm;
    width: 6cm;
    border: 1px solid black;
    overflow-x: hidden;
    overflow-y: auto;
    padding: 1rem;
    background: orange;
    display: flex;
    flex-direction: column;
    resize: both;
    align-items: center;
    justify-content: flex-start;
    align-content: flex-start;
  }
  .page {
    min-height: 29.7cm !important;
    max-height: 29.7cm !important;
    height: 29.7cm !important;
    width: 21cm !important;
    background: white;
    padding: 21mm;
    border: 1px solid gray;
  }

这里可以找到一个JS版本的例子(包括一些神奇的空格):

JSbin


共1个答案

匿名用户

听起来你需要一个可伸缩的矩形,保持它的纵横比:这里有一个例子说明如何在纯CSS中做到这一点。 您可以使用填充顶部,以计算高度-因为它是基于宽度。

null

#wrapper {
  width:100%;
  height:100%;
}

.paper {
  width:50%; /* This is how wide the paper should be in the page */
  background:#ccc;
  position:relative;
  margin:0 0 15px;
}

.paper:before {
  content:"";
  padding:141% 0 0 0; /* This percent creates the aspect ratio. So the height of the page will be 141% of the width */
  display:block;
}

.papercontent {
  position:absolute;
  top:0;
  left:0;
}
<div id='wrapper'>
  <div class='paper'>
    <div class='papercontent'>I write all my content in here</div>
  </div>
  <div class='paper'>
    <div class='papercontent'>I write all my content in here</div>
  </div>
</div>

相关问题