我有这些屏幕:
全桌面屏幕。
小桌面屏幕。
手机屏幕。
HTML 是这样的:
html, body {
font-family: SFMono-Regular, Consolas, Liberation Mono, Menlo, Courier, monospace;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
position: relative;
}
body > section, body > header {
width: 100vw;
height: 100vh;
height: calc(var(--vh, 1vh) * 100);
}
header {
display: flex;
flex-direction: column;
}
header > section {
display: flex;
flex-direction: row;
flex: 1;
}
header > section > figure {
display: flex;
flex: 1;
justify-content: center;
align-items: center;
font-size: 300px;
}
header > h1 {
padding: 10px 20px;
font-size: 20px;
background: black;
color: white;
}
header > section > aside {
width: 300px;
display: flex;
background: red;
}
@media (orientation: portrait) {
header > h1 {
order: 1;
}
header > section {
order: 2;
}
header > section {
flex-direction: column;
}
header > section > aside {
width: auto;
height: 100px;
}
}
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<header>
<section>
<figure>ð</figure>
<aside></aside>
</section>
<h1>The letter ð</h1>
</header>
</body>
</html>
我希望左边的字母符合以下限制条件:
- 始终在其容器中居中。 (这部分正在运行)。
- 周围总是有一些填充物。我希望内边距至少为 20 像素,否则为某个百分比,例如 20%。
- 要解决填充问题,字体大小需要随着屏幕大小的调整而缩小/放大。
想知道我如何才能做到这一点。
请注意“小桌面屏幕”部分中的字母是如何被剪裁的,并且周围没有填充。在那种情况下,我希望字母更小,以便它周围至少有 20px 的填充。在“全桌面屏幕”部分,我希望字母稍微大一点,因此周围的填充大约为 20%。
如果可能的话,我希望不要有任何基于这张图片中字母宽度的硬编码显式大小(宽度/高度/填充等),因为我可能会使用不同的字体,所以它应该可以理想地处理任何字体。如果不可能,那么让这个示例正常工作就可以了。
如果 CSS 无法做到这一点,那么知道这一点将是一件好事,那么在这种情况下,JavaScript 解决方案听起来不错。但如果可能,最好只使用 CSS :)
最佳答案
这是我的解决方案,
我使用 vh
(视口(viewport)高度)作为字体大小的单位。这将根据屏幕的高度缩放您的字体大小
header>section>figure {
...
...
font-size: 75vh; /* Can be changed as per your design */
}
如果你愿意,你也可以尝试使用 vw(视口(viewport)宽度)单位作为字体大小
html,
body {
font-family: SFMono-Regular, Consolas, Liberation Mono, Menlo, Courier, monospace;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
position: relative;
}
body>section,
body>header {
width: 100vw;
height: 100vh;
height: calc(var(--vh, 1vh) * 100);
}
header {
display: flex;
flex-direction: column;
}
header>section {
display: flex;
flex-direction: row;
flex: 1;
}
header>section>figure {
display: flex;
flex: 1;
justify-content: center;
align-items: center;
font-size: 75vh; /* Can be changed as per your design */
}
header>h1 {
padding: 10px 20px;
font-size: 20px;
background: black;
color: white;
}
header>section>aside {
width: 300px;
display: flex;
background: red;
}
@media (orientation: portrait) {
header>h1 {
order: 1;
}
header>section {
order: 2;
}
header>section {
flex-direction: column;
}
header>section>aside {
width: auto;
height: 100px;
}
}
<header>
<section>
<figure>ð</figure>
<aside></aside>
</section>
<h1>The letter ð</h1>
</header>
关于javascript - 如何使字符居中并始终在其周围填充无论屏幕尺寸如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56015408/