栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在CSS容器中将多个div居中

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在CSS容器中将多个div居中

我之前的答案显示了一种坦率地说已经过时的方法(它仍然有效,只有更好的方法可以实现此目的)。因此,我正在对其进行更新,以包括一个更现代的flexbox解决方案。

在这里查看支持;在大多数环境中,使用安全。

这利用了:

  • display: flex
    :以flexbox行为显示此元素
  • justify-content: center
    将内部元素沿容器的主轴中心对齐
  • flex-wrap: wrap
    确保内部元素自动包裹在容器中(不要脱离容器)

注意:与HTML和CSS一样,这只是获得所需结果的 多种 方法之一。在选择适合 您的 规格的方法之前,请彻底研究。

.container {    display: flex;    justify-content: center;    flex-wrap: wrap;    width: 70%;    background: #eee;    margin: 10px auto;    position: relative;    text-align:center;}.block {    background: green;    height: 100px;    width: 100px;    margin: 10px;}<div >    <div >1. name of the company</div>    <div >2. name of the company</div>    <div >3. name of the company</div>    <div >4. name of the company</div>    <div >5. name of the company</div>    <div >6. name of the company</div>    <div >7. name of the company</div>    <div >8. name of the company</div></div>

原始答案

您可以将样式

text-align:center;
应用于容器,并将
.block
s 显示为内联块元素:

.container {  width: 70%;  background: #eee;  margin: 10px auto;  position: relative;  text-align:center;}.block {  background: green;  height: 100px;  width: 100px;  display:inline-block;  margin: 10px;}<div >        <div >1. name of the company</div><!--     --><div >2. name of the company</div><!--     --><div >3. name of the company</div><!--     --><div >4. name of the company</div><!--     --><div >5. name of the company</div><!--     --><div >6. name of the company</div><!--     --><div >7. name of the company</div><!--     --><div >8. name of the company</div></div>

请注意,我已注释掉

<div>
s 之间的空白。由于元素现在已内联显示,因此将确认您的空格。这是“战斗空间” [的许多方法之一]。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465048.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号