前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >关于margin-top的百分比值

关于margin-top的百分比值

作者头像
练小习
发布2017-12-29 11:00:33
1.2K0
发布2017-12-29 11:00:33
举报
文章被收录于专栏:练小习的专栏

周末朋友发出江湖救急的消息,说他有个莫名其妙的bug搞不定了,于是我让他把bug的代码发过来看看。

他的需求是绝对居中,代码是这样的

  1. width:100px;
  2. height:100px;
  3. position:relative;
  4. margin-top:50%;
  5. margin-left:50%;
  6. top:-50px;
  7. left:-50px;

如果你已经看出问题了,那么这篇文章就可以不用看了。如果你觉得这段代码没问题,那么可以继续探讨。

大多数时候我们做一个块的居中,写法都是这样的

  1. width:100px;
  2. height:100px;
  3. position:relative;
  4. top:50%;
  5. left:50%;
  6. margin-top:-50px;
  7. margin-left:-50px;

看出区别了吧,区别就在于,margin是负的具体像素,定位是百分比。而出bug的写法刚好相反。乍一看这是没啥区别的,甚至我也曾经想当然的认为这两种写法是一样的。

这就是典型的知其然不知其所以然。

我们看一下W3.org上关于margin-top的说明:

  1. 'margin-top', 'margin-bottom'
  2. Value: <margin-width> | inherit
  3. Initial: 0
  4. Applies to: all elements except elements with table display types other than table-caption, table and inline-table
  5. Inherited: no
  6. Percentages: refer to width of containing block
  7. Media: visual
  8. Computed value: the percentage as specified or the absolute length
  9. These properties have no effect on non-replaced inline elements.

关键就是这里

  1. Percentages: refer to width of containing block

也就是说,只要margin的值是百分比,那么,他的基数就只会是父容器的宽度,比如父容器宽100PX,那么margin-top:50% 就是50px,无论父容器高是多少,都跟’margin-top’, ‘margin-bottom’的百分比值无关。

来个demo,这个是有问题的写法

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>无标题文档</title>

<style type="text/css">

.wrap{

width:300px;

height:1000px;

margin:20px auto;

border:#f1f1f1 1px solid;

}

.box{

width:100px;

height:100px;

background:#ff6600;

position:relative;

top:-50px;

left:-50px;

margin-top:50%;

margin-left:50%;

}

</style>

</head>

<body>

<div class="wrap">

<div class="box"></div>

</div>

</body>

</html>

提示:你可以先修改部分代码再运行。

然后来个正确的写法

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>无标题文档</title>

<style type="text/css">

.wrap{

width:300px;

height:1000px;

margin:20px auto;

border:#f1f1f1 1px solid;

}

.box{

width:100px;

height:100px;

background:#ff6600;

position:relative;

top:50%;

left:50%;

margin-top:-50px;

margin-left:-50px;

}

</style>

</head>

<body>

<div class="wrap">

<div class="box"></div>

</div>

</body>

</html>

提示:你可以先修改部分代码再运行。

需要注意的是,绝对定位的元素margin-top的百分比值低版本webkit下和其他浏览器表现不一,这个可以自己写几个demo试试看吧……..

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档