css之居中布局的实现的几种方式

方式一:margin:0 auto实现div水平垂直居中;

示例:

.wrap{
  margin:0 auto;
}
<div class="wrap">w3cschool</div>

方式二:利用line-height和height为同一高度可实现文字的水平居中;

示例:

.wrap{
  line-height: 200px;/*垂直居中关键*/
  text-align:center;
  height: 200px;
  font-size: 36px;
  background-color: #ccc;
}
<div class="wrap">w3cschool</div>

方式三:利用padding和background-clip配合实现div的水平垂直居中;

示例:

<div class="parent"> <div class="children"></div></div>
.parent{
margin:0 auto;
width:200px;
height:200px;
background-color:red;
}
.children {
width: 100px;
height: 100px;
padding: 50px;
background-color: black;
background-clip:content-box;/*居中的关键*/

方式四:对于不定高和宽的div,可以用绝对定位和translate(-50%,-50%) 实现div水平垂直居中

示例:

<style>
#ex3_container{
width:200px;
height:200px;
background-color:yellow;
position:relative;
}
#ex3_content{
position:absolute;
left:50%; 
top:50%; 
transform:translate(-50%,-50%);
-webkit-transform:translate(-50%,-50%);
background-color:gray; 
color:white; 
}
</style>
<div id="ex3_container"><div id="ex3_content">Hello World</div></div>

方式五:绝对定位居中加margin: auto实现子div在父div中居中

示例:

    <style>
    .ex3_container{
        width: 200px;
        height: 200px;
        background-color: pink;
        position: relative
    }
    .Absolute-Center {
        background-color: red;
        position: absolute;
        width: 50%;
        height: 50%;
        overflow: auto;
        margin: auto;
        top: 0; left: 0; bottom: 0; right: 0;
    }
    </style>
 <div class="ex3_container"><div class="Absolute-Center">Hello World</div></div>

方式六:用css3的flex实现水平垂直居中

示例:

<div class="parent">
  <div class="children">我是通过flex的水平垂直居中噢!</div>
</div>
html,body{
 width: 100%;
 height: 200px;
}
.parent {
 display:flex;
 align-items: center;/*垂直居中*/
 justify-content: center;/*水平居中*/
 width:100%;
 height:100%;
 background-color:red;
}
.children {
 background-color:blue;
}

方式七:vertical-align 属性设置元素的垂直对齐方式。

说明:
该属性定义行内元素的基线相对于该元素所在行的基线的垂直对齐。允许指定负长度值和百分比值。这会使元素降低而不是升高。在表单元格中,这个属性会设置单元格框中的单元格内容的对齐方式。

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容