首页 > 代码库 > 水平居中方法汇总

水平居中方法汇总

1. inline-block+ text-align

eg:

<head>
<meta charset="UTF-8">
<title>Document</title>
<style>

.parent{text-align:center; background-color:red;}
.child{ display:inline-block; background-color:green;}

</style>
</head>
<body>

<div class="parent">
<div class="child"> DEMO</div>
</div>
</body>

 

2.table+margin

eg:

<head>
<meta charset="UTF-8">
<title>Document</title>
<style>

.parent{ background-color:red;}
.child{ display:table; margin:0 auto; background-color:green;}

</style>
</head>
<body>

<div class="parent">
<div class="child"> DEMO</div>
</div>
</body>

 

 

3.absolute+transform

eg:

<head>
<meta charset="UTF-8">
<title>Document</title>
<style>

.parent{ position:relative; }
.child{ position:absolute; left:50%; width:500px; transform:translatex(-50%); background-color:gray;}

</style>
</head>
<body>

<div class="parent">
<div class="child"> DEMO</div>
</div>
</body>

 

 

 

4.Flex+justify-content/margin

eg1:

 

<head>
<meta charset="UTF-8">
<title>Document</title>
<style>

.parent{ display:flex; justify-content:center;}
.child{ background-color:gray;}

 

</style>
</head>
<body>

<div class="parent">
<div class="child"> DEMO</div>
</div>
</body>

 

 

eg2:

<head>
<meta charset="UTF-8">
<title>Document</title>
<style>

.parent{display:flex; background-color:red;}
.child{ margin:0 auto; background-color:green; }

</style>
</head>
<body>

<div class="parent">
<div class="child"> DEMO</div>
</div>
</body>

水平居中方法汇总