行内元素

行内元素:(img、span、文字等行内元素),通过在父级元素设置 text-align:center 使元素水平居中。

块级元素

块级元素:(div、p、h1...h6、ul、li等块级元素),通过在要居中元素设置 margin:0 auto(上、右、下、左),这里表示上下0 左右自适应,达到元素水平居中。

垂直居中

行内元素

行内元素:(img、span、文字等行内元素),通过在父级元素设置display: table-cell;vertical-align: middle; 使元素垂直居中,如果是单行文字或者其他 可以设置line-height:容器高;

块级元素

高度固定通常是使用

  • 绝对定位与负边距
  • 绝对定位与margin
  • display table-cell

高度不固定

  • display table-cell  
  • translate 
  • flex 布局

还是上代码比较实在

行内元素水平、垂直居中

文字、图片水平、垂直居中

主要是利用

  1. text-align: center; //水平对齐方式
  2. display: table-cell;//以td形式渲染
  3. vertical-align: middle;//垂直对齐方式
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<style>
    * {
        padding: 0;
        margin: 10px 0 0 0;
    }

    div {
        width: 200px;
        height: 200px;
        border: solid 1px red;
    }

    img {
        width: 100px;
        height: 100px;
        border: 0px;
    }

    span {
        border: solid 1px blue
    }

    .div1 {
        text-align: center;
        display: table-cell;
        vertical-align: middle;
    }

    .div2 {
        line-height: 200px;
        text-align: center;
        margin: 0 auto;
    }
</style>
<body>

<p>文字</p>
<div class="div1" title="行内元素水平垂直居中">
    文字水平垂直居中1
</div>

<p>文字</p>
<div class="div2" title="行内元素水平垂直居中">
    文字水平垂直居中2
</div>

<p>图片水平垂直居中</p>
<div class="div1" title="行内元素水平垂直居中">
    <img src="images/pro_1.jpg">
</div>

<p>span水平垂直居中</p>
<div class="div1" title="行内元素水平垂直居中">
    <span>this is span</span>
</div>
</body>
</html>
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-20
猜你喜欢
  • 2021-08-31
  • 2021-11-27
  • 2021-12-05
  • 2021-12-13
  • 2021-11-23
相关资源
相似解决方案