【发布时间】:2017-07-10 01:09:34
【问题描述】:
我只是好奇在另一个 div 中居中(垂直和水平)对齐 div 的最佳方法是什么。这个例子有一个红色的 div,我想用背景图片在 div 内垂直和水平居中。
这样做的最佳方法是什么,以便在调整浏览器窗口大小和在手机上显示时自动适应?
以下方法失败:
- 位置:相对; & 最高:50%; - 只有最顶部的 div 是集中的,而不是其余的。添加负边距顶部失败,因为它将其应用于父元素
- 保证金:25% 自动;
- 垂直对齐:中间;
- 对齐内容:居中; - 大概只适用于弹性盒
代码如下:
body{
background: yellow;
margin: 0 auto;
}
#first{
width:100%;
height:550px;
background: url('https://static.pexels.com/photos/30627/pexels-photo-30627.jpg');
background-size: cover;
}
#central{
width:200px;
height:100px;
background: red;
margin: 0 auto;
/*
Why DO THESE FAIL:
position:relative; & top: 50%;
margin: 25% auto;
vertical-align: middle;
justify-content: center; - presumably only applies to flexboxes
*/
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css.css">
<title>title</title>
</head>
<body>
<div id="first">
<div id="central"></div>
</div>
</body>
</html>
感谢您的帮助。
【问题讨论】:
-
将
position: relative添加到#first 并将top:50%; left:50%; transform:translate( -50%, -50%); position:absolute;添加到#central FiddleHere