一,水平居中
水平居中可分为行内元素水平居中和块级元素水平居中
1.行内元素水平居中
定义:行内元素是指文本text、图像img、超链接等,只需给父元素设置text-align:center即可实现。
.box {
text-align:center;
}
<div class="box">水平居中</div>
2,块元素水平居中
2.1 给块元素设置宽 ,只需给需要居中的块级元素加margin:0 auto即可。
.box{
width:200px;
margin:0 auto;
}
<div class="box">网蒂娜</div>
2.2 不给块元素设置宽
方法一:给所需元素居中的元素设置 display:table,然后设置margin:0 auto来实现
<style>
.box {
display: table;
margin: 0 auto;
border: 1px solid red;
}
</style>
</head>
<body>
<div class="box">帮后分视。</div>
</body>
方法二:通过给子元素设置inline-block,然后再给父元素设置text-align:center
<style>
.box1 {
text-align: center;
}
.box1{
display: inline-block;
}
</style>
</head>
<body>
<div class="box">
<div class="box1">1</div>
<div class="box1">2</div>
</div>
</body>
方法三:给有需要的的块状元素的父元素设置display:flex,justify-content:center;
<style>
.box {
display: flex;
justify-content: center;
}
</style>
</head>
<body>
<div class="box">
<div class="box1">量千韩。</div>
<div class="box1">量千韩。</div>
</div>
</body>
二,垂直居中
方法一:固定高宽div垂直居中(使用绝对定位和负外边距)
position: absolute;
left: 50%;
top: 50%;
width:200px;
height:100px;
margin-left:-100px;
margin-top:-50px;
方法二:伪元素和inline-block、vertical-align
<style>
.box {
height: 300px;
text-align: center;
background-color: blue;
}
.box:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em;
}
.box1 {
display: inline-block;
vertical-align: middle;
width: 50%;
background-color: aqua;
}
</style>
</head>
<body>
<div class="box">
<div class="box1">
<h1>远你憾。</h1>
<p>守磊拢。</p>
</div>
</div>
</body>
方法三:table-cell实现水平垂直居中: table-cell middle center组合使用
<style>
.table-cell {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 240px;
height: 180px;
border: 1px solid #666;
}
</style>
</head>
<body>
<div class="table-cell">
<p>我爱你中国</p>
</div>
</body>
此文章仅供参考。