Nic*_*eda 5 css centering flexbox responsive-design
注意:我正在使用 Flexbox
当屏幕大小调整时,我使用“display:none”来删除一些随着尺寸缩小而不再适合的元素,但是一旦删除它们,仍然显示的元素将不再在其列中水平居中。
例如:(这不是代码,只是一个简单的说明)
|-------------------------------|
| | | | |
| 1 2 | 1 2 | 1 2 | 1 2 |
|-------|-------|-------|-------|
Run Code Online (Sandbox Code Playgroud)
例如:现在,在“2”元素具有属性“display:none”之后,剩下的内容不再水平居中。
|-------------------------------|
| | | | |
| 1 | 1 | 1 | 1 |
|-------|-------|-------|-------|
Run Code Online (Sandbox Code Playgroud)
当我缩小并删除元素“2”时,保持水平居中的正确方法是什么?
要将项目在 Flexbox 中居中并保持居中,您可以使用justify-content和align-items属性。
超文本标记语言
<article id="container">
<section class="box>
<span class="one">1</span>
<span class="two">2</span>
</section>
<section class="box>
<span class="one">1</span>
<span class="two">2</span>
</section>
<section class="box>
<span class="one">1</span>
<span class="two">2</span>
</section>
</article>
Run Code Online (Sandbox Code Playgroud)
CSS
#container {
display: flex;
justify-content: center; /* align flex items horizontally (in this case) */
align-items: center; /* align flex items vertically (in this case) */
height: 50px;
background-color: lightgray;
border: 2px dashed black;
}
section {
display: flex;
justify-content: center;
align-items: center;
width: 50px;
padding: 5px;
margin: 5px;
font-size: 1.2em;
border: 1px solid red;
}
@media screen and (max-width: 500px) {
span.two { display: none; }
}
Run Code Online (Sandbox Code Playgroud)
DEMO(调整窗口大小以获得效果)
保持内容居中的另一种方法是text-align: center在父级上。
HTML(同上)
CSS
#container {
display: flex;
justify-content: center; /* align flex items horizontally (in this case) */
align-items: center; /* align flex items vertically (in this case) */
height: 50px;
background-color: lightgray;
border: 2px dashed black;
}
section {
width: 50px;
padding: 5px;
margin: 5px;
font-size: 1.2em;
border: 1px solid red;
text-align: center;
}
@media screen and (max-width: 500px) {
span.two { display: none; }
}
Run Code Online (Sandbox Code Playgroud)