基于父div居中子div

问题描述 投票:0回答:3

我有一个父 div 和一个子 div。例如,我想知道是否可以将子 div 的宽度和高度表示为父 div 的百分比

<!doctype html>
<head>
<meta charset='utf-8' />
<title>Horizontal center a  div</title>
<style type='text/css'>
.one{
width:800px;
height:100px;
background-color:grey;
}
.two{
margin-top:30px;
margin-bottom:30px;
min-height:40px;
margin-left:30px;
width:90px;
background-color:pink;
display:inline-block;
}
</style>
</head>
<body>
<div class="one">
<div class="two">lorem ipsum</p>
</div>
</body>
</html>

查看实际效果 http://jsfiddle.net/thiswolf/3qRgH/

外部div(父级)有一个

height of 100px
,我的子div有一个
height of 40px
。我想将我的孩子放在父主题内居中,所以,
100px - 40px = 60px
,我将60px划分两次并分配子div
margin-top:30px
margin-bottom:30px;
。但是,我想以百分比形式表示边距。我如何以 % 表示边距。

css
3个回答
0
投票

您可以通过这种方式将 div 居中(已编辑):

<!doctype html>
<head>
<meta charset='utf-8' />
<title>Horizontal center a  div</title>
<style type='text/css'>
.one{
width: 800px;
background-color: grey;
}
.two{
min-height: 40px;
margin: 30% 355px;
width: 90px;
background-color: pink;
display: inline-block;
}
</style>
</head>
<body>
<div class="one">
<div class="two">lorem ipsum</div>
</div>
</body>
</html>

参见http://jsfiddle.net/3qRgH/2/

你问的是这个吗?


0
投票

http://jsfiddle.net/thiswolf/5AZJD/

这似乎有效,但我还没有证明它

<!doctype html>
<head>
<meta charset='utf-8' />
<title>Horizontal center a  div</title>
<style type='text/css'>
.one{
position:relative;
width:800px;
height:100px;
background-color:grey;
}
.two{
position:absolute;
top:30%;
bottom:30%;
min-height:40px;
margin-left:30px;
width:90px;
background-color:pink;
display:inline-block;
}
</style>
</head>
<body>
<div class="one">
<div class="two">lorem ipsum</p>
</div>
</body>
</html>

0
投票
.parent {
  background: gray;
  height: 300px;
  width: 300px;
  position: relative;
}

.child {
  background: orange;
  width: 100px;
  height: 100px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -50px 0 0 -50px;
}

<div class="parent">
   <div class="child"></div>
</div>

到目前为止,我还没有找到一种通过仅自定义父级来使子级div居中的方法

© www.soinside.com 2019 - 2024. All rights reserved.