在 HTML/CSS 中使最大的方块成为可能

  • 本文关键字:方块 HTML CSS html css
  • 更新时间 :
  • 英文 :


我有一个大小未知的父<div>,我想创建一个最大正方形大小的子<div>,该子正方形可以包含在父方中,并将该正方形居中在父方的中间。HTMLCSS有可能吗?

我知道max-widthmax-height但不知道如何确保纵横比。

我希望能够做这样的事情:

.frame {
height: 80%;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.square {
width: 750px;
height: 750px;
display: flex;
justify-content: center;
align-items: center;
position: relative;
}
.back {
width: 100%;
}
.front {
width: 70.5%;
top: 23.965%;
position: absolute;
}
<div class="frame">
<div class="square">
<img class="back" src="back.png">
<img class="front" src="front.png">
</div>
</div>

但是在square中,我希望根据其父frame设置宽度和高度,如前所述。父frame可以是横向或纵向。

这在很长一段时间内都是不可能的;因为padding-top:100%aspect-ratio:1/1仅限于容器的宽度(而不是高度)。

但是现在有可能;继续阅读...

问题所在

███ <- square fills the width correctly
███ 
░░░ <- outer box (portrait)
░░░
███████████ 
███████████  } <- outer box (landscape) stops here
███████████ /     but square overfloweth
███████████
███████████
███████████

"解决方案">

从技术上讲,纵横比不会填充宽度,而是"块方向",在西方语言中始终是宽度......

但是,我们可以更改writing-mode属性以使块方向为高度,如下所示:

writing-mode: vertical-lr

███░░░ <- outer box (landscape)
███░░░
^- square fills the height correctly
███████ 
███████ 
███████
███████
^---^
`---- outer box (portrait) stops here, but square overfloweth

所以现在我们遇到了相反的问题,它适用于横向而不是纵向。

魔术

使用正确的媒体查询组合,应该可以在从纵向切换到横向的确切尺寸上切换写入模式。

html, body {
margin: 0;
}
*, *:before, *:after {
box-sizing: border-box;
}
.bounds-outer {
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
}
.bounds-inner {
writing-mode: vertical-rl;
width: 100%;
max-width: 90%;
height: 100vh;
border: 1px dashed black;
display: flex;
align-items: center;
}
.a {
position: relative;
flex: 1 0 1px;
background: red;
padding-block-start: 100%;
}
.b {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
color: white;
writing-mode: horizontal-tb;
}
/* this media query depends on layout */
@media (max-aspect-ratio: 10/9)  {
.bounds-inner {
writing-mode: horizontal-tb;
}
}
<div class="bounds-outer">
<div class="bounds-inner">
<div class="a">
<div class="b">
Hi
</div>
</div>
</div>
</div>

注意:您的媒体查询将取决于框的大小。在Chrome,Firefox和Safari中验证。

最新更新