css经典面试题 --- div不设高度完全居中

栏目: CSS · 发布时间: 5年前

要求

  1. body下div垂直居中
  2. div内文字垂直居中
  3. div宽度和高度均为body宽度的一半

分析

  • div居中不难,考虑 margin 或者 left/top 配合 translate 属性实现
  • 关键点在于div高度等于body一半,由于body没有高度,设置div height: 50%; 得到的结果是div的高度为0
  • 即使通过对body进行绝对定位的手段使得body高度为100vh,div高度设置50%也只能是body高度的一半,而不是宽度的一半
  • 此时要借助于 padding ,因为padding设置百分比时,参考便是父容器的宽度

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        body{
            padding: 0;
            margin: 0;
        }
        #box{
            width: 50%;
            /* div处置居中 */
            position: relative;
            transform: translate(50%, 25%);
            /*  */
            /* 此处解决div高度为body宽度的一半,并且文字垂直居中 */
            padding-top: 25%;
            padding-bottom: 25%;
            line-height: 0;
            text-align: center;
            /* */
            background-color: #111;
            color: #fff;
        }
    </style>
</head>
<body>
    
    <div id="box">
        box123
    </div>
</body>
</html>

效果

css经典面试题 --- div不设高度完全居中


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

New Dark Age

New Dark Age

James Bridle / Verso Books / 2018-7-17 / GBP 16.99

As the world around us increases in technological complexity, our understanding of it diminishes. Underlying this trend is a single idea: the belief that our existence is understandable through comput......一起来看看 《New Dark Age》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具