美文网首页程序员
【HTML中垂直居中】【容器】使用绝对定位

【HTML中垂直居中】【容器】使用绝对定位

作者: fanlehai | 来源:发表于2018-11-02 13:59 被阅读5次

【方法一】


  • top 设置为:50%;
  • margin-top 设置为: -(content高度/2);
  • 设置content高度
<html>

<head>
    <style type="text/css">
        .content {
            background-color: rgb(87, 87, 92);
            position: absolute;
            top: 50%;
            height: 240px;
            margin-top: -120px;
            /* negative half of the height */
        }
    </style>
</head>

<body>
    <div class="content">Content goes here</div>
</body>

</html>
  • 优点:
    适用于所有浏览器不需要嵌套标签;

  • 缺点:
    没有足够空间时,content 会消失(类似div 在 body 内,当用户缩小浏览器窗口,滚动条不出现的情况)

【方法二】


  • 适用有固定高度和宽度的div;
  • position:absolute;
  • top,bottom,left,right都是为0;
  • margin:auto;
<html>

<head>
    <style type="text/css">
        #content {
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;
            height: 240px;
            width: 70%;
            background-color: rgb(87, 87, 92);
        }
    </style>
</head>

<body>


    <div id="content"> Content here</div>

</body>

</html>
  • 优点:
    简单
  • 缺点:
    IE(IE8 beta)中无效
    无足够空间时,content 被截断,但是不会有滚动条出现

参考链接:

相关文章

  • 【HTML中垂直居中】【容器】使用绝对定位

    【方法一】 top 设置为:50%; margin-top 设置为: -(content高度/2); 设置cont...

  • CSS综合

    编码规范 设置上下padding垂直居中 使用绝对定位垂直居中 使用vertical-align垂直居中 使用ta...

  • 页面中垂直居中的几种实现方法

    页面中垂直居中的几种方法: 1. 通过使用absolute定位来实现垂直居中 HTML: CSS: 2. 使用t...

  • 垂直居中的多种写法

    1、垂直居中 2、水平居中 3、垂直水平居中 方法1:使用绝对定位 方法二:使用display:flex 扩展1:...

  • CSS垂直居中

    CSS垂直居中方法 上下padding相等适用于容器高度没有设定,高度可变的情况 绝对定位实现垂直居中适用于需要定...

  • css div垂直居中

    方案一:div绝对定位水平垂直居中【margin:auto实现绝对定位元素的居中】, 方案二:div绝对定位水平垂...

  • day05

    今天学到的 相对定位,绝对定位 垂直水平居中 banner

  • CSS实现水平垂直居中

    负边距+定位:水平垂直居中(Negative Margin)使用绝对定位将content的定点定位到body的中心...

  • HTML 水平居中和垂直居中

    水平居中 文字居中 图片居中 绝对定位元素 居中 相对定位 负边距居中 垂直居中 文字设置line-height ...

  • 实现垂直居中

    原文 博客原文 大纲 前言1、使用绝对定位和负外边距对块级元素进行垂直居中2、使用绝对定位和transform3、...

网友评论

    本文标题:【HTML中垂直居中】【容器】使用绝对定位

    本文链接:https://www.haomeiwen.com/subject/hstcxqtx.html