html-如何在没有单独元素的情况下为全角内容设置最大宽度?

前端之家收集整理的这篇文章主要介绍了html-如何在没有单独元素的情况下为全角内容设置最大宽度? 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想要一些< section>跨整个页面宽度不超过特定像素宽度(此处为300px).如果页面(即该部分)比页面宽,则内容应水平居中.

为此,我目前正在使用一个小助手< div>其中a)定义了内容的最大宽度,b)使用水平自动边距将内容水平居中:

  1. section {
  2. background-color: teal;
  3. }
  4. .content {
  5. max-width: 300px;
  6. margin: 0 auto;
  7. }
  1. <section>
  2. <div class="content">
  3. This text should be no wider than 300px.
  4. </div>
  5. </section>

这很好用,但是我一直在努力摆脱这种< div>仅用于布局的元素.理想情况下,我可以使用padding之类的东西:0 auto;在< section>上元件.

是否可以在不需要额外的“内容”< div>的情况下达到相同的效果

最佳答案
您可以如下控制填充:

  1. section {
  2. background-color: teal;
  3. padding:0 calc((100% - 300px)/2)
  4. }
  1. <section>
  2. This text should be no wider than 300px.
  3. </section>
  4. <section>
  5. This very long long long text should be no wider than 300px.
  6. </section>

这是使用CSS网格的另一个想法:

  1. section {
  2. background-color: teal;
  3. display:grid;
  4. grid-template-columns:1fr minmax(auto,300px) 1fr;
  5. }
  6. /*to fill the 1fr (only the :before is mandatory) */
  7. section:before,section:after{
  8. content:"";
  9. }
  1. <section>
  2. This text should be no wider than 300px.
  3. </section>
  4. <section>
  5. This very long long long text should be no wider than 300px.
  6. </section>

这是使用flexBox的另一种方法

  1. section {
  2. background-color: teal;
  3. display:flex;
  4. }
  5. section:before,section:after{
  6. content:"";
  7. flex-basis:calc((100% - 300px)/2);
  8. flex-shrink:0;
  9. }
  1. <section>
  2. This text should be no wider than 300px.
  3. </section>
  4. <section>
  5. This very long long long text should be no wider than 300px.
  6. </section>

猜你在找的HTML相关文章