缩放 div 而不改变其子元素的大小和位置 [英] Scale a div without changing the size and position of its child elements

查看:32
本文介绍了缩放 div 而不改变其子元素的大小和位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 div,其中包含一些元素,例如 hp 标签.如何仅缩放包装器 div 而不是内部元素?

 

<h2>标题</h2><p>描述</p>

解决方案

如果在 wrapper 上应用 transform,则无法阻止缩放子元素.

⋅⋅⋅

但是您可以使用 CSS 变量来存储您的比例因子,然后使用 calc 进行计算(比手动进行更好)并为子元素应用逆比例:

.wrapper {填充:0 20px;变换:比例(var(--scale));背景:#ddd;}.wrapper >* {变换:比例(计算(1/var(--比例)));}

<h2>标题</h2><p>描述</p>

<div class="wrapper" style="--scale: 1.2"><h2>标题</h2><p>描述</p>

<div class="wrapper" style="--scale: 0.8"><h2>标题</h2><p>描述</p>

⋅⋅⋅

另一种方法是将包装器的样式设置为伪元素并将其缩放.这样,伪元素中就没有元素,所以没有任何缩放:

.wrapper {位置:相对;填充:0 20px;}.wrapper::before {内容: "";z-索引:-1;位置:绝对;顶部:0;底部:0;左:0;右:0;变换:比例(var(--scale));背景:#ddd;}

<h2>标题</h2><p>描述</p>

<div class="wrapper" style="--scale: 1.2"><h2>标题</h2><p>描述</p>

<div class="wrapper" style="--scale: 0.8"><h2>标题</h2><p>描述</p>

I have a div that contains some elements like h and p tags. How can I scale just the wrapper div, not inner elements?

 <div class="wrapper" style="padding:50px; transform:scale(1.1)">
      <h2>title</h2>
      <p>description</p>
 </div>

解决方案

You can't prevent the child elements to be scaled if you apply the transform on your wrapper.

⋅ ⋅ ⋅

But you can use a CSS variable to store your scale factor, and then use calc to calculate (better than doing it manually) and apply the inverse scale for the child elements:

.wrapper {
  padding: 0 20px;
  transform: scale(var(--scale));
  background: #ddd;
}

.wrapper > * {
  transform: scale(calc(1/var(--scale)));
}

<div class="wrapper" style="--scale: 1">
  <h2>title</h2>
  <p>description</p>
</div>

<div class="wrapper" style="--scale: 1.2">
  <h2>title</h2>
  <p>description</p>
</div>

<div class="wrapper" style="--scale: 0.8">
  <h2>title</h2>
  <p>description</p>
</div>

⋅ ⋅ ⋅

Another way of doing it would be to style and scale your wrapper as a pseudo-element. That way, there is no element inside the pseudo-element, so nothing scales:

.wrapper {
  position: relative;
  padding: 0 20px;
}

.wrapper::before {
  content: "";
  z-index: -1;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  transform: scale(var(--scale));
  background: #ddd;
}

<div class="wrapper" style="--scale: 1">
  <h2>title</h2>
  <p>description</p>
</div>

<div class="wrapper" style="--scale: 1.2">
  <h2>title</h2>
  <p>description</p>
</div>

<div class="wrapper" style="--scale: 0.8">
  <h2>title</h2>
  <p>description</p>
</div>

这篇关于缩放 div 而不改变其子元素的大小和位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆