【问题标题】:Absolute div centered and responsive? [duplicate]绝对 div 居中和响应? [复制]
【发布时间】:2017-10-04 23:42:08
【问题描述】:

我有一个需要居中和宽度响应(流畅)的弹出 div,但我使用的是左侧 50% 和左侧负边距的通用代码

width: 960px;
margin-left: -480px;    
position: absolute;
top: 20px;
left: 50%;
z-index: 999;

但是我可以让它响应吗,说如果我想拥有

max-width: 960px 

而不是绝对值?

更新:也许我不清楚,但我看不出与“在 div 中垂直和水平居中文本”问题有任何关系

【问题讨论】:

  • 与对齐文本原理相同
  • 你试过了吗?发生了什么?

标签: css


【解决方案1】:

在绝对元素上,你可以使用

left: 0
right: 0
margin: 0 auto

希望这会有所帮助!

【讨论】:

  • 啊,我按错了-1!你的答案很完美!!!!谢谢!!!编辑你的答案,这样我就可以给你 +1
  • 刚刚做了,谢谢你告诉我:)
【解决方案2】:

.popupContainer{
  width:100%;
  height:100%;
  position:absolute;
  left:0;
  top:0;
  display:flex;
  align-items:center;
  justify-content:center;
  z-index:999;
}
.popup{
  background-color:#ccc;
  width:300px;
  height:300px;
}
<div class="popupContainer">
  <div class="popup">

  </div>
</div>

您可以为此使用flexbox,例如这个codepen:https://codepen.io/andrasadam93/pen/YrrORq

.popupContainer{
  width:100%;
  height:100%;
  position:absolute;
  left:0;
  top:0;
  display:flex;
  align-items:center;
  justify-content:center;
  z-index:999;
}
.popup{
  background-color:#ccc;
  width:300px;
  height:300px;
}

<div class="popupContainer">
  <div class="popup">

  </div>
</div>

【讨论】:

    【解决方案3】:

    你可以试试这个:

    使用变换:翻译

    CSS

    width: 960px;  
    position: absolute;
    top: 20px;
    left: 50%;
    transform:translateX{-50%}
    z-index: 999
    

    【讨论】:

    • Webkit 浏览器永远不需要前缀。
    • @rob 他们在移动设备上需要(safari,chrome).. 他们在过去几个月里做出了改变吗? -stackoverflow.com/questions/31247808/… 如果是这样,谢谢你的好消息;)
    • caniuse 显示在 2D 上根本不需要它,或者 3D 转换至少在 Safari 上回到版本 4,现在是版本 9。
    猜你喜欢
    • 1970-01-01
    • 2014-09-10
    • 2023-03-03
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 2012-12-30
    • 2013-05-02
    相关资源
    最近更新 更多