方法一
.outer {
width: 500px; height: 200px; background-color: green; position: relative; } .inner {
width: 20px; height: 10px; background-color: wheat; position: absolute; } .center {
left: 50 %; top: 50 %; transform: translate(- 50 %, - 50 %);/*自己的50% */ }
html
<div class="outer"> <div class="inner center"></div> </div>
方法二
利用 margin: auto;要先设置定位
css
.outer {
width: 500px; height: 200px; background-color: green; position: relative; } .inner {
width: 20px; height: 10px; background-color: wheat; position: absolute; } .center {
left: 0; top: 0; right: 0; bottom: 0; margin: auto; }
html
<div class="outer"> <div class="inner center"></div> </div>
方法三
.flex{
display:flex; align-items: center; justify-content:center; width:500px; height:500px; border:10px solid; } .flex_son{
width:100px; height:100px; border:10px solid; }
html
<div class='flex'> <div class="flex_son"></div> </div>
方法四
div绝对定位水平垂直居中【margin 负间距】 这或许是当前最流行的使用方法。
.outer {
width: 500px; height: 500px; position: relative; background:red; } .center{
width:200px; height: 200px; background:green; position: absolute; left:50%; top:50%; margin-left:-100px;//要宽度的一半 margin-top:-100px; } <div class="outer"> <div class="center"></div> </div>
方法五
.Aa{
display: table-cell; text-align:center; vertical-align: middle; width: 500px; height: 500px; background:green; } .aa{
display: inline-block; background:red; width: 100px; height: 100px; } <div class="Aa"> <div class="aa"></div> </div>
方法六
利用父基线跟伪元素:before搭配vertical-align:middle实现对齐
<style type="text/css"> .parent {
display: inline-block; width: 300px; height: 300px; font-size: 0; background: #; text-align: center; } .parent:before {
display: inline-block; width: 20px; height: 100%; content: ''; background: #; vertical-align: middle; } .child {
display: inline-block; width: 50px; height: 50px; background: #19be6b; vertical-align: middle; } </style> <div class="parent"> <div class="child">child</div> </div>
方法(窗口居中)
#aa {
width: 50vw; height: 50vh; margin: 25vh auto; /*margin: 25vh 25vw; */ } <div id="aa"></div>
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/221950.html原文链接:https://javaforall.net
