在网页中常用到的几种居中方法

时间:2022-07-26
本文章向大家介绍在网页中常用到的几种居中方法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1、行内元素水平居中,可以在父元素中使用text-align:center;垂直居中可以用,line-height:100px;例如:

<style type="text/css">
    div{<br />
        width:300px;<br />
        height:100px;<br />
        text-align:center;<br />
        line-height:100px;<br />
    }<br />
</style>
<div>文字居中</div>

2、块级元素水平居中,可以用margin:auto;代码如下:

<style type="text/css">
    div{<br />
        width:300px;<br />
        height:100px;<br />
        margin:0px auto;//上下边距为0,水平居中<br />
        background:#ccc;<br />
    }<br />
</style>
<div>文字居中</div>

3、元素绝对居中,利用定位position,代码如下:

<style type="text/css">
    div{<br />
        width:300px;<br />
        height:100px;<br />
        position:relative;<br />
    }<br />
    div p{<br />
        width:100px;<br />
        height:20px;<br />
        position:absolute;<br />
        margin:auto;<br />
        top:0;<br />
        bottom:0;<br />
        left:0;<br />
        right:0;<br />
    }<br />
</style>
<div>文字居中</div>

4、元素绝对居中的另一种方法,代码如下:

<style type="text/css">
    div{<br />
        width:300px;<br />
        height:100px;<br />
        position:relative;<br />
        background:#bbb;<br />
    }<br />
    div p{<br />
        width:100px;<br />
        height:20px;<br />
        position:absolute;<br />
        top:50%;<br />
        margin-top:-10px;<br />
        left:50%;<br />
        margin-left:-50px;<br />
    }<br />
</style>
<div>文字居中</div>