css 居中

1、把margin 设为atuo

  margin :简写属性在一个声明中设置所有外边距属性。该属性可以有 1 到 4 个值。

  具体来说就是把要居中的元素的margin-left和margin-right都设为auto,此方法只能进行水平的居中且对浮动元素或绝对定位元素无效

<!DOCTYPE html>
<html>
<head>
   <title>margin 居中</title>
   <meta charset="utf-8">

<style type="text/css">
#test{
   width:50px;
   height: 50px;
   background-color: blue;
   margin: auto;
}

</style>
</head>
<body>

<div id="test">

</div>
</body>
</html>

结果:

2、text-align 居中

  text-align 属性规定元素中的文本(只能对图片,按钮,文字等行内元素(display为inline或inline-block等))的水平对齐方式。

  该属性通过指定行框与哪个点对齐,从而设置块级元素内文本的水平对齐方式。通过允许用户代理调整行内容中字母和字之间的间隔,可以支持值 justify;不同用户代理可能会得到不同的结果。

<!DOCTYPE html>
<html>
<head>
   <title>margin 居中</title>
   <meta charset="utf-8">

<style type="text/css">
#test{
   text-align: center
}

div{
    width: 100px;
    background-color: rgb(12,110,221);
    margin-bottom: 20px;
}

</style>
</head>
<body>

<div id="test">
    测试
</div>

<div >
    测试
</div>

</body>
</html>

   结果如下:

  解析:测试1的div 添加了text-align:center 的属性,故文字居中, 测试2所在div没有加text-align:center,故默认居左。 但是这里只是div中的文字居中。

3、使用绝对定位来居中(水平垂直居中)

  这种方式只适用于那些我们已经知道它们的宽度和高度的元素。

  原理:通过把这个绝对定位元素的left或top的属性设为50%,这个时候元素并不是居中的,而是比居中的位置向右或向左偏了这个元素宽度或高度的一半的距离,所以需要使用一个负的margin-left或margin-top的值来把它拉回到居中的位置,这个的margin值就取元素宽度或高度的一半。

<!DOCTYPE html>
<html>
<head>
   <title>绝对定位 居中</title>
   <meta charset="utf-8">

<style type="text/css">
body{
    margin: 0;
    padding: 0;
}

#test{
   width:50px;
   height: 50px;
   background-color: blue;
   
   position: absolute;
   left : 50%;  
   top:50%;
   margin-left: -25px;    /* 宽度的一半 */
   margin-top: -25px;     /* 高度的一半 */
}

</style>
</head>
<body>

<div id="test">

</div>

</body>
</html>

  结果如下:

 4、另外的绝对定位方式(水平垂直居中)

  只适用于知道高度和宽度的元素。

  只支持IE9+,谷歌,火狐等符合w3c标准的现代浏览器。

demo:

<!DOCTYPE html>
<html>
<head>
   <title>绝对定位 居中</title>
   <meta charset="utf-8">

<style type="text/css">
body{
    margin: 0;
    padding: 0;
}


#test{
   width:50px;
   height: 50px;   /* 高度和宽度必须固定 */
   background-color: blue;
   position: absolute;
   left : 0;  
   top:0;
   right: 0;
   bottom:0;
   margin: auto;
}

</style>
</head>
<body>

<div id="test">

</div>
</body>
</html>

  结果如下:

源码:http://pan.baidu.com/s/1kTRJjvT

   致谢:感谢您的阅读!

原文地址:https://www.cnblogs.com/0201zcr/p/5280083.html