我想要一些< section>跨整个页面宽度不超过特定像素宽度(此处为300px).如果页面(即该部分)比页面宽,则内容应水平居中.
为此,我目前正在使用一个小助手< div>其中a)定义了内容的最大宽度,b)使用水平自动边距将内容水平居中:
section {
background-color: teal;
}
.content {
max-width: 300px;
margin: 0 auto;
}
<section>
<div class="content">
This text should be no wider than 300px.
</div>
</section>
这很好用,但是我一直在努力摆脱这种< div>仅用于布局的元素.理想情况下,我可以使用padding之类的东西:0 auto;在< section>上元件.
最佳答案
您可以如下控制填充:
原文链接:https://www.f2er.com/html/530503.htmlsection {
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>
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>