我想在桌面和移动设备上使用类似于 stackoverflow 的居中单列 HTML/CSS 布局,即截然不同的屏幕宽度和分辨率。 我想避免必须使用代码(客户端或服务器)以不同方式检测和处理设备(即提供不同的布局/样式)。
布局
- 应该居中(目前使用居中的 div,对左右边距使用 auto 属性 - 这需要固定宽度)
- 宽度应根据设备屏幕宽度而变化,即在桌面计算机上舒适的列宽,但在移动设备上为全宽
- 将有一个视觉上延伸到窗口边缘的标题栏(与 stackoverflow 的相同)和一个应该位于页面底部的页脚,即使内容不多(为此,CSS Single-column layout centered fixed-width 100% height w header and footer 可能有答案)
这可以基于一个简单的居中 div 来实现吗?或者最先进的是什么?以下内容在 Firefox for Android 上呈现得很小:
#center {
margin: 0 auto 0 auto;
width: 10em;
background-color: gray;
}
<div id="center">
Content div<br/>
<ul>
<li>should be centered</li>
<li>should be variable width depending on device screen width, i.e. a comfortable column width on desktop computer but full width on mobile</li>
<li>will have header bar that visually extends to the window edges and a have footer that should be at the bottom of the page, even if there's not much content (for this, https://stackoverflow.com/questions/23651942/ may have an answer)</li>
</ul>
</div>
请注意,我使用 10em 作为宽度(以使其适合代码段编辑器预览)- 是否有更合适的单位或“绝对”大小的其他属性以确保在所有屏幕上的可读性(和大小调整)?
桌面:
手机:
最佳答案
您找到的 awswer 已经给出了您应该为此使用什么的重要提示,即 display: flex;
。建立在那里提供的 fiddle 之上,你可以做这样的事情:
这为主要内容列提供了 100% 的宽度值以及最大宽度,比如说 768 像素。在此示例中,flex-grow:1;
用于完全填充高度,但对于您的元素而言可能不是必需的。
html,
body {
height:100%;
padding:0;
margin:0;
width:100%;
}
body {
display:flex;
flex-direction:column;
}
#main {
flex-grow:1;
background:#f3f3f3;
max-width: 768px;
width:100%;
margin:auto;
}
header {min-height:50px; background:green;}
footer {min-height:50px; background:blue;}
<header>header</header>
<div id="main" role="main">content</div>
<footer>footer</footer>
关于html - 可读单列布局的设备无关宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59283038/