如何根据div大小缩放字体大小?

时间:2016-05-17 20:05:53

标签: html css

如何根据字符数和font-size大小增长/缩小panel-default?例如,很多字符意味着font-size会更小,或者更小的屏幕也意味着更小的font-sizefont-size应符合div。

CSS

*,
*:before,
*:after {
  box-sizing: border-box;
}

body {
  margin: 0
}

.testing-here {
  font-size: 0;
}

.panel-default {
  box-sizing: border-box;
  border-style: none;
  position: relative;
  width: 50%;
  padding-bottom: 40%;
  overflow: hidden;
  background-color: #446CB3;
  border-radius: 0;
  display: inline-block;
  margin-bottom: 0px;
  border: 2.5px white solid;
}

.panel-body {
  color: white;
  text-align: center;
  position:absolute;
  font-size: 16px;
}

HTML

<div class="testing-here">
  <div class="panel panel-default">
    <div class="panel-body">
      Basic panel example
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-body">
      Basic panel example
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-body">
      Basic panel example
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-body">
      Basic panel example
    </div>
  </div>
</div>

有没有办法在没有javascript的情况下执行此操作?

1 个答案:

答案 0 :(得分:1)

如果你的面板的大小来自窗口的width,你可以使用vw个单位(所有麻烦都会出现:太大或太小而无法阅读)

您可以添加媒体查询以将font-size保持在最小和最大尺寸内。

*,
*:before,
*:after {
  box-sizing: border-box;
}
body {
  margin: 0
}
.testing-here {
  font-size: 0;
}
.panel-default {
  box-sizing: border-box;
  border-style: none;
  position: relative;
  width: 50%;
  padding-bottom: 40%;
  overflow: hidden;
  background-color: #446CB3;
  border-radius: 0;
  display: inline-block;
  margin-bottom: 0px;
  border: 2.5px white solid;
}
.panel-body {
  color: white;
  width: 100%;
  height: 100%;
  text-align: center;
  position: absolute;
  font-size: 5vw;
  /* will be 5% of window's width so 10% of panel's width */
}
@media (min-width: 1000px) {
  .panel-body {
    font-size: 50px;
  }
}
@media (max-width: 320px) {
  .panel-body {
    font-size: 16px;
  }
}
<div class="testing-here">
  <div class="panel panel-default">
    <div class="panel-body">
      Basic panel example show me full page & resize window
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-body">
      Basic panel example font-size kept in between 16 and 50px max
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-body">
      Basic panel example
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-body">
      Basic panel example
    </div>
  </div>
</div>

您也可以使用媒体查询来保持字体可读或仅在不同的断点处进行媒体查询