【问题标题】:font size relative to the size of parent相对于父级大小的字体大小
【发布时间】:2018-06-21 06:11:14
【问题描述】:

我有一个容器,它可以有不同的大小,具体取决于用户在屏幕上移动某些元素的方式。 在这个容器内有一个图像和一个文本。图像填充容器高度的 80%,文本应填充另外 20%。 虽然 height: 80% 适用于图像 font-size: 20% 不适用于文本。我不能使用 vm 或 vh,因为大小与屏幕大小无关。

【问题讨论】:

标签: html css font-size


【解决方案1】:

我发现这个链接应该会有所帮助:LINK

flexFont = function () {
    var divs = document.getElementsByClassName("flexFont");
    for(var i = 0; i < divs.length; i++) {
        var relFontsize = divs[i].offsetWidth*0.05;
        divs[i].style.fontSize = relFontsize+'px';
    }
};

window.onload = function(event) {
    flexFont();
};
window.onresize = function(event) {
    flexFont();
};
@font-face {
  font-family: "San Francisco";
  font-weight: 200;
  src: url("//applesocial.s3.amazonaws.com/assets/styles/fonts/sanfrancisco/sanfranciscodisplay-thin-webfont.woff2");
}

body, html {
    height:100%;
    width:100%;
    font-family: "San Francisco";
    font-weight: 200
}
.flexFont {
    height:8em;
    width:75%;
    background-color:#eeeeee;
    padding:1%;
    margin: 10px;
}

.smaller {
    font-size: 0.7em;
    background-color:red;
    width: 10em;
}
<div class="flexFont">
    <h2>This is FlexText:<br>Autoscaling by DIV width</h2>
    <div class='smaller'>... scaled by 0.7em</div>
</div>

<div class="flexFont">
    <p>Font size scales parallel to the container width.<br>Change window size to test.<p>
</div>

如果不使用 VM/VH,您需要结合使用 javascript 和 CSS 来实现此目的。上面的代码应该有助于您尝试实现的目标。

【讨论】:

  • 他说:“我不能使用 vm 或 vh,因为尺寸与屏幕尺寸无关。”
  • AH 错过了最后一行。
  • 在不使用 vh/vw 的情况下更新了答案
【解决方案2】:

font-size 使用百分比会根据文档的当前字体大小调整字体(它不会调整字体以占据容器的百分比)。查看CSS Font-Size: em vs px vs pt vs percent

例如:

/* current font-size for the document */ 
html {
  font-size: 20px;
}

/* results in 4px font-size for this div */
div {
  font-size: 20%;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多