<!DOCTYPE html>
<html>

<head>
   <meta charset="utf-8" />
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <title>Test</title>
   <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
   <div class="container">
      <div class="carousel"></div>
      <div class="content"></div>
      <div class="content"></div>
   </div>
   <style>
      .container{
         max-width: 480px;
         margin: 0 auto;
      }

      .container .carousel{
         background-color: lightsalmon;
         height: 400px;
         width: 100%;
         /* Make the carousel's width fill the viewport */
      }

      .container .content{
         margin: 10px 0px;
         background-color: steelblue;
         height: 200px;
         width: 100%;
      }
   </style>
</body>

</html>


我有这种问题。

我需要让旋转木马水平填充整个视口(viewport)。

我不想使用 position: absolute 因为它会丢失其他元素的高度信息,所以我需要向容器添加更多的 css,如果我需要更改轮播的高度,我需要修改两个地方。而且我也不想将它从容器中分离出来,因为它假设在容器内。

那么有没有更好的方法,我只需要向 .carousel 添加一些 css 来实现这一点?

最佳答案

<!DOCTYPE html>
<html>

<head>
   <meta charset="utf-8" />
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <title>Test</title>
   <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
   <div class="container">
      <div class="carousel"></div>
      <div class="content"></div>
      <div class="content"></div>
   </div>
   <style>
       .container{
     width: 100%;
     margin: 0 auto;
  }

  .container .carousel{
     background-color: lightsalmon;
     height: 400px;
     width: 100%;
     margin-bottom: .5em;

     /* Make the carousel's width fill the viewport */
  }

  .container .content{
     margin: 10px 0px;
     background-color: steelblue;
     height: 200px;
     width: 100%;
    max-width: 30%;
    margin: 0 auto;
    margin-bottom: .5em;
  }
   </style>
</body>

</html>


我希望这就是你要找的!
此外,如果您希望内容元素填充整个视口(viewport),则不应将容器限制为特定宽度,而是根据需要调整元素大小。

已经创建了一个新的 codepen 示例。检查行、容器流体和容器 here 类。

关于html - 如何使 div 填充视口(viewport)的宽度而不是其父级?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52549361/

10-12 12:54
查看更多