我想将 <div class="container"></div>
放置在屏幕中间,以便它能够响应任何屏幕尺寸。屏幕截图上的红色标记区域应始终出现在屏幕中间。
怎么定位呢?目前我正在使用 margin-top:85px
当我挤压浏览器时,红色标记区域和导航栏之间的距离也应该减少。
原文由 Noob Coder 发布,翻译遵循 CC BY-SA 4.0 许可协议
我想将 <div class="container"></div>
放置在屏幕中间,以便它能够响应任何屏幕尺寸。屏幕截图上的红色标记区域应始终出现在屏幕中间。
怎么定位呢?目前我正在使用 margin-top:85px
当我挤压浏览器时,红色标记区域和导航栏之间的距离也应该减少。
原文由 Noob Coder 发布,翻译遵循 CC BY-SA 4.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 许可协议
2 回答909 阅读✓ 已解决
3 回答800 阅读✓ 已解决
4 回答1.2k 阅读✓ 已解决
2 回答1.5k 阅读✓ 已解决
2 回答1.3k 阅读✓ 已解决
2 回答877 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
您是否尝试过绝对居中?您需要添加一个相对于父容器的位置…您还需要在容器元素上声明一个高度…
我希望这有帮助…