网页元素居中攻略记_(2)元素垂直居中

单行内元素垂直居中

方案

设置行内元素的行高等于父元素的高度或者包裹块的高度即可实现垂直居中,具体看代码效果

代码实现

index.html

<!DOCTYPE html>
<html lang="zh">

  <head>
    <meta charset="UTF-8">
    <title>单行内元素垂直居中</title>
    <style> div { width: 200px; height: 200px; background: rgb(30, 186, 250); } /*设置父块大小及颜色*/ div a { text-decoration: none; font-size: 25px; color: rgb(254, 7, 183); font-weight: 700; line-height: 200px; } /*设置内联元素的行高等于父块高度的行高即可实现垂直居中*/ span { display: inline-block; width: 150px; height: 150px; font-size: 35px; line-height: 150px; background: rgb(97, 71, 130); } /*原理同上,行高等于块的高度即可实现内容垂直居中*/ </style>
  </head>

  <body>
    <div><a href="#">测试链接</a></div>
    <span>测试文字</span>
  </body>

</html>

多行的行内元素垂直居中

方案

让包裹块模拟表格单元,然后用vertical-align进行控制位置(支持英文单词位置也支持百分比调整)

代码实现

index.html

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>多行的行内元素垂直居中</title>
  <style> .wrap{ height:700px; width:700px; background: rgb(1, 244, 68); display: table-cell; vertical-align: middle; } /*让包裹块模拟表格效果,产生垂直居中效果*/ </style>
</head>
<body>
    <div class="wrap"><span>
        <span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex facere repellendus, porro velit, modi culpa, tempora totam dolore quaerat natus vel fugiat non voluptas unde quod fuga, iusto cumque rem.</span>
        <span>Beatae natus obcaecati error fugiat harum consequatur possimus modi tempore aut tenetur nostrum illo maxime consequuntur, nulla, blanditiis alias voluptas voluptates neque minus accusamus cumque rem inventore. Eligendi, tempora, impedit.</span>
        <span>Optio delectus, aliquid pariatur fugit eveniet accusantium eius et veritatis blanditiis temporibus, sed reiciendis sunt quae quam obcaecati labore quia sit debitis recusandae alias rerum! Libero adipisci sed velit facere.</span>
        <span>Laudantium, adipisci in nulla atque aut similique voluptatum maxime corrupti nobis, consequatur impedit ipsa reprehenderit voluptates quo, inventore tempora tenetur quibusdam deserunt! Animi impedit, earum dolore. Inventore sequi nemo saepe.</span>
        <span>Eligendi, porro voluptas molestiae, corrupti atque ad dolor cupiditate tempore adipisci similique. Dolorum voluptates id nam, non ipsum optio, incidunt culpa quia fuga vitae qui suscipit consectetur ipsa nesciunt aut.</span>
      </span></div>
</body>
</html>

块状元素垂直居中(已知高度)

方案

使用绝对定位,把元素直接定到页面的一半,然后把元素拉回其大小的一半,即可实现垂直居中

Tips
用了absolute元素的父元素若是使用position任意属性,那子元素的absolute是无法脱离父元素的

代码实现

index.html

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>块状元素垂直居中(已知高度)</title>
  <style> *{margin: 0;padding: 0;} .testDiv{ width: 100px; height: 100px; background: rgb(20, 77, 221); position: absolute; top:50%; margin-top:-50px; } /* 定位到页面的一般,拉回该元素大小的一半,使其居中 */ </style>
</head>
<body>
      <div class="testDiv">

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

你可能感兴趣的:(元素垂直居中,行内元素居中,块元素居中)