水平居中方法汇总

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了水平居中方法汇总相关的知识,希望对你有一定的参考价值。

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>

以上是关于水平居中方法汇总的主要内容,如果未能解决你的问题,请参考以下文章

CSS设置元素水平居中垂直居中方式汇总

css 单行图片文字水平垂直居中汇总

css 文本和div垂直居中方法汇总

Android--控件属性汇总

Python字符串解析方法汇总

Layui 使用问题汇总