我有一个格式如下的html
<body>
<section></section>
<section></section>
<section></section>
</body>
正文是整个页面,我希望每个部分在正文中水平居中。
最佳答案
它们默认居中(宽度为 100%)。如果您指定的宽度 < 100%,请使用 auto
的左/右边距将它们水平居中。
body {
border: 1px solid black;
padding: 1em;
}
section {
width: 80%;
margin: auto;
border: 1px solid red;
height: 1em;
}
<body>
<section></section>
<section></section>
<section></section>
</body>
你也可以使用display: flex;对齐元素:居中; flex-direction: column;
在父级上以水平居中各部分。
body {
border: 1px solid black;
padding: 1em;
display: flex;
align-items: center;
flex-direction: column;
}
section {
width: 80%;
border: 1px solid red;
height: 1em;
}
<body>
<section></section>
<section></section>
<section></section>
</body>
关于html - 主体中的居中部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42941249/