html - 居中位置 : absolute div in relative container in desktop and mobile

标签 html css responsive-design

<分区>

我有一个 div(子),它在父容器中绝对定位(相对定位)。我希望这个子 div 在桌面和移动设备上都在其容器内垂直和水平居中,但是子 div 会根据窗口的大小移动定位。如何跨设备应用一致的居中定位?

HTML

<div class="container">
  <div class="child">
  </div>
  <div class="child-2">
  </div>
</div>

CSS

.container {
  width: 300px;
  height: 300px;
  border: solid 1px blue;
  position: relative;
}

.child {
  position: absolute;
  width: 50px;
  height: 50px;
  background-color: red;
  position: absolute;
  right: 50%;
  left: 50%;
  top: 50%;
  border-radius: 100%;
}

.child-2 {
  border-bottom: solid 1px blue;
  width: 300px;
  height: 150px;
}

例如 JSFiddle - http://jsfiddle.net/hfndkywe/8/

最佳答案

使用transform使元素居中总是安全的,看下面代码

 .child {
  position: absolute;
  width: 50px;
  height: 50px;
  background-color: red;
  left: 50%;
  top: 50%;
  border-radius: 100%;
  transform: translate(-50%,-50%);
}

当你使用左右定位时,它总是从侧面而不是中心插入 div,所以为了准确地在中心变换是很容易的解决办法。

关于html - 居中位置 : absolute div in relative container in desktop and mobile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51212630/

上一篇:html - 与 Wordpress 中的自定义 CSS 和重力形式对齐

下一篇:html - 在 div 之间添加链接时的 css 垂直空白

相关文章:

html - 将单个图像缩放为网格正方形?

css - css中如何不继承宽度?

php - 网站的维基百科模板

ios - Div 仅在 iphone 上有右边距

Javascript:列出文件和文件夹结构

html - FontAwesome 从 4 升级到 5 (Tumblr)

javascript - 一页中的多个表单-reactjs

javascript - 垃圾邮件链接插入到我的 GitHub 页面网站

css - 当窗口大小减小到 500px 时, slider 向左拉

html - 根据浏览器宽度使用子主题