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

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

概述我想要一些< section>跨整个页面宽度不超过特定像素宽度(此处为300px).如果页面(即该部分)比页面宽,则内容应水平居中.为此,我目前正在使用一个小助手< div>其中a)定义了内容的最大宽度,b)使用水平自动边距将内容水平居中:section { background-color: teal; } .content { max-widt

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

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

section {  background-color: teal;}.content {  max-wIDth: 300px;  margin: 0 auto;}
<section>  <div >    This text should be no wIDer than 300px.  </div></section>

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

是否可以在不需要额外的“内容”< div>的情况下达到相同的效果?最佳答案您可以如下控制填充:

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

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

section {  background-color: teal;  display:grID;  grID-template-columns:1fr minmax(auto,300px) 1fr;}/*to fill the 1fr (only the :before is mandatory) */section:before,section:after{  content:"";}
<section>    This text should be no wIDer than 300px.</section><section>    This very long long long text should be no wIDer than 300px.</section>

这是使用flexBox的另一种方法:

section {  background-color: teal;  display:flex;}section:before,section:after{  content:"";  flex-basis:calc((100% - 300px)/2);  flex-shrink:0;}
<section>    This text should be no wIDer than 300px.</section><section>    This very long long long text should be no wIDer than 300px.</section>
总结

以上是内存溢出为你收集整理的html-如何在没有单独元素的情况下为全角内容设置最大宽度? 全部内容,希望文章能够帮你解决html-如何在没有单独元素的情况下为全角内容设置最大宽度? 所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1105547.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存