【问题标题】:Make <div> with childs always fit in parent <div>使带有子元素的 <div> 始终适合父 <div>
【发布时间】:2021-12-30 05:39:51
【问题描述】:

我正在尝试制作一个包含一些子元素的 div,它始终适合覆盖整个页面的父 div。子 div 的宽度适合父 div 的宽度已经有效。但高度也应该适合父 div。我想避免使用overflow: auto,因为在某些情况下用户将不得不滚动。子 div(里面有子元素)应该始终适合父元素的高度和宽度。

如何在 CSS 中实现这一点?

<div class="parent">
    <div class="child">
        <button>Toggle</button>
        <img />
        <p>Some text here...</p>
    </div>
</div>

&lt;div class="parent"&gt; 覆盖整个页面。 &lt;div class="child"&gt; 应缩放到 &lt;div class="parent"&gt; 的宽度和高度。

【问题讨论】:

  • 如果孩子内部的内容太大而无法容纳在父母中,你想发生什么?你希望父母成长,还是??
  • @MTilsted 我希望内容始终按比例缩小以适合父级。
  • @RobertoZvjerković 我已经尝试过了,但它不起作用。子 div 与父 div 匹配,但高度大于屏幕。
  • 您的意思是希望字体变小以使文本适合设备窗口而不考虑屏幕大小?我只想用javascript来做到这一点。检查文本是否合适,如果不合适,缩小字体,检查是否合适,循环。

标签: html css scale


【解决方案1】:

你可以试试这个。您需要针对移动设备进行媒体查询,但我认为您的要求是……

<html>

<head>
  <style>
    body {
      font-weight: 400;
      background-color: black;
      color: white;
      font-family: sans-serif;
      margin: 0;
    }

    .grid {
      min-height: 100%;
      grid-column: 1 / -1;
      grid-gap: 0;
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(33%, 1fr));
    }

    .grid>span {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

    .image {
      background-image: url('https://live.staticflickr.com/7206/6859864719_5d68aedbd7.jpg');
      background: cover;
      background-position: center center;
      background-repeat: no-repeat;
    }

    .toggle {
      background: #4096C0;
      border-radius: 2px;
      padding: 12px 24px;
      color: white;
      width: auto;
      text-align: center;
      cursor: pointer;
    }

    .toggle:hover {
      background: #00537C;
    }


    .text {
      background: #40B6C0;
      padding: 72px;
      color: white;
    }

  </style>
</head>

<body>

  <div class="container">
    <div class="grid">

      <span class="toggle">TOGGLE</span>
      <span class="image"></span>
      <span class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu fermentum dolor. Cras aliquet tempus elit ut eleifend. In commodo malesuada nisi non vulputate.</span>

    </div>
  </div>
</body>

</html>

【讨论】:

    猜你喜欢
    • 2010-11-09
    • 2014-03-11
    • 1970-01-01
    • 2017-12-04
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多