css - 灵活的文本容器,可根据内容自动调整大小

标签 css

我想在这里创建一个横幅,要求带有 bannerText 类的标题 div 应该始终出现在中心,并且必须出现在中心,白色背景在文本和白色背景边框之间保持 30px 的填充。我想要最大宽度为 900 像素的横幅文本。

因此,如果单词很少,则不能固定在 900px 上,它必须分解为具有 30px 填充和白色背景的内容。

但是一旦标题变长,它就会换行到下一行而不会超过 900 像素。

文本应该始终水平和垂直对齐,我已经做到了。但我的问题是柔性容器。

enter image description here

#banner {
  position: relative;
  -webkit-font-smoothing: anti-aliasing;
  text-rendering: optimizelegibility;
  max-height: 422px;
  overflow: hidden;
}
#banner img {
  height: auto;
  width: 100%;
}
.bannerText {
  text-align: center;
  position: absolute;
  top: 50%;
  width: 100%;
  font-weight: 700;
  font-size: 2em;
  margin-top: -40px;
  color: #D87A00;
}
#bannerTitle {
  width: 911px;
  color: #0e2bff;
}
<section id="banner">
  <section class="bannerImage">
    <img src="picture.png" class="img-responsive">
  </section>
  <div class="bannerText">
    <section id="bannerTitle">Demo banner title reset</section>
  </div>
</section>

最佳答案

* {
  box-sizing: border-box;
}

#banner {
  position: relative;
  -webkit-font-smoothing: anti-aliasing;
  text-rendering: optimizelegibility;
  max-height: 422px;
  overflow: hidden;
}

#bannerImage {
  height: 422px;
  background: orange;
}

.bannerText {
  text-align: center;
  position: absolute;
  top: 50%;
  left: 50%;
  max-width: 900px;
  transform:translate(-50%,-50%);
  font-weight: 700;
  font-size: 2em;
  background: white;
}

#bannerTitle {
  padding: 30px;
  color: #0e2bff;
}
<section id="banner">
  <section id="bannerImage">
  </section>
  <div class="bannerText">
    <section id="bannerTitle">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus adipisci !</section>
  </div>
</section>

Codepen Demo

关于css - 灵活的文本容器,可根据内容自动调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32564683/

相关文章:

javascript - 使用 jquery 改变背景位置时的抖动

javascript - D3 map - 将两个不相交的 svg 多边形路径合并为一个路径

html - 如何设置元素的顺序 HTML CSS

css - "Card flip"不暴露背面的复选框

jquery - position absolute 跳转到jquery动画时的位置

html - 滚动条未出现在 SVG 元素中

javascript - 如果类存在则加载标记

css - 左边的 div 填充剩余的水平空间?

html - CSS下拉列表中元素的对齐

javascript - AngularJS + CSS : best practice for a live preview?