什么是确保网页的方形内容“竖直”显示的正确方法?例如,如果您的电话或显示器处于纵向模式,则内容将采用全角宽度;但是如果处于横向模式,则内容的侧面将带有侧边栏,因此主体为正方形,填满整个高度。
我已经使用JavaScript做到了这一点,方法是处理resize事件并检查容器的高度和宽度,并手动计算宽度和边距。但是我敢肯定,有更好的方法,甚至是纯CSS3解决方案。
看Google's responsive guide,我想也许是自定义样式表可以做到,但我不知道如何始终使内容始终填满高度或宽度。
所以这是在纵向和横向模式下的样子,其中红色部分是主体,蓝色是多余的填充空间:
我目前正在尝试Angular Material,因此,如果有针对该框架的解决方案,那也可以。
这是体内的布局-Angular材质网格块都是正方形,因此网格是2x2,具有4个相等大小的正方形,这意味着整个主体将是一个正方形-我希望2x2网格成为尽可能大而不滚动:
<body>
<!-- if necessary -->
<div id="left-side"></div>
<div id="main-container">
<mat-grid-list cols="2" rowHeight="1:1">
<mat-grid-tile>First square</mat-grid-tile>
<mat-grid-tile>Second square</mat-grid-tile>
<mat-grid-tile>Third square</mat-grid-tile>
<mat-grid-tile>Fourth square</mat-grid-tile>
</mat-grid-list>
</div>
<!-- if necessary -->
<div id="right-side"></div>
</body>
答案 0 :(得分:2)
您可以使用以下CSS:
body {
margin: 0;
background-color: blue;
}
#wrapper {
margin: 0 auto;
max-width: 100vh;
background-color: red;
}
<div id="wrapper">Content</div>
在纵向模式下,包装纸的宽度为100%,在横向模式下,包装纸的宽度与屏幕高度相同。
为完整起见,下面是一个与OP中的屏幕截图匹配的示例:
body {
margin: 0;
background-color: blue;
}
#wrapper {
margin: 0 auto;
max-width: 100vh;
background-color: red;
}
/* landscape mode: the wrapper is full height */
@media screen and (orientation: landscape) {
#wrapper {
min-height: 100vh;
}
}
/* portrait mode: the wrapper is same height as width */
@media screen and (orientation: portrait) {
#wrapper {
min-height: 100vw;
}
}
<div id="wrapper">Content</div>
答案 1 :(得分:1)
您可以在vh
单元中使用某些CSS网格默认值,并且非常接近此布局。制作一个2x2的网格,将网格子级设置为50vh
高度,将网格容器居中。
之所以有效,是因为vh
会自动调整为视口高度,而display:grid
会接管水平位置并使布局自动响应。
(注意:我在容器上放了max-width
,在height
上放了高<main>
,以显示正在发生的事情,但是您不一定需要这些。)
HTML:
<main>
<section class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</section>
</main>
CSS:
main {
height: 500vh;
}
.container {
display: grid;
grid-template-columns: 1fr 1fr;
margin: 0 auto;
max-width: 800px;
width: 100%;
}
.item {
background-color: lightblue;
border: 1px solid black;
height: 50vh;
}
答案 2 :(得分:1)
像这样吗?
body {
margin: 0;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: flex-start;
background: blue;
}
mat\-grid\-list {
display: grid;
grid: repeat(2, 1fr)/repeat(2, 1fr);
width: 100vmin;
height: 100vmin;
background: red;
grid-gap: 2px;
}
mat\-grid\-tile {
border: 1px solid #888;
}
<body>
<div id="main-container">
<mat-grid-list cols="2" rowHeight="1:1">
<mat-grid-tile>First square</mat-grid-tile>
<mat-grid-tile>Second square</mat-grid-tile>
<mat-grid-tile>Third square</mat-grid-tile>
<mat-grid-tile>Fourth square</mat-grid-tile>
</mat-grid-list>
</div>
</body>