CSS 响应式边距顶部

新手上路,请多包涵

我想将 <div class="container"></div> 放置在屏幕中间,以便它能够响应任何屏幕尺寸。屏幕截图上的红色标记区域应始终出现在屏幕中间。

怎么定位呢?目前我正在使用 margin-top:85px 当我挤压浏览器时,红色标记区域和导航栏之间的距离也应该减少。

在此处输入图像描述

原文由 Noob Coder 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 352
2 个回答

您是否尝试过绝对居中?您需要添加一个相对于父容器的位置…您还需要在容器元素上声明一个高度…

 .parent-container {
    position: relative;
}

.container {
    width: 50%;
    height: 50%;
    overflow: auto;
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
}

我希望这有帮助…

原文由 steffcarrington 发布,翻译遵循 CC BY-SA 3.0 许可协议

添加了工作代码片段。此代码将使您的 div 在任何屏幕尺寸下水平和垂直居中。

为容器的父级设置 css 属性 position:relative

 .container {
  width: 400px;
  height: 300px;
  background-color: #ccc;
  position: absolute;
  /*it can be fixed too*/
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  /*this to solve "the content will not be cut when the window is smaller than the content": */
  max-width: 100%;
  max-height: 100%;
  overflow: auto;
}
 <div class="container">
</div>

原文由 Sooraj 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题