这个问题在这里已有答案:
我有一个有三个孩子的内部div;一个按钮,一些文本和一个按钮组。
我使用flex
来集中所有内容,但问题是文本实际上并不是相对于包含元素居中。而是将文本居中在按钮和按钮组的近边界之间。
文本不在黄色框内居中。我希望文本在黄色框中居中。
有没有办法说“从外部元素的边缘测量并忽略兄弟姐妹的内缘”?
.outer-box {
width: 100%;
display: flex;
justify-content: center;
}
.inner-box {
width: 500px;
height: 60px;
background-color: yellow;
display: flex;
justify-content: space-between;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
</br>
<div class="outer-box">
<div class="inner-box">
<button class="btn">My Button</button>
<span>My text here</span>
<div class="btn-group">
<button class="btn">My Button1</button>
<button class="btn">My Button2</button>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
Flex正在将.inner-box
的孩子们视为专栏。
如果你想让文本只是黄色框的中心,你可以absolute
将文本relative
定位到黄色框,如下所示:
.outer-box {
width: 100%;
display: flex;
justify-content: center;
}
.inner-box {
width: 500px;
height: 60px;
background-color: yellow;
display: flex;
justify-content: space-between;
position: relative;
}
.text {
position: absolute;
left: 50%;
transform: translate(-50%, 0);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
</br>
<div class="outer-box">
<div class="inner-box">
<button class="btn">My Button</button>
<span class="text">My text here</span>
<div class="btn-group">
<button class="btn">My Button1</button>
<button class="btn">My Button2</button>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
如果您希望将文本置于span元素中心,则可以直接更改元素对齐。
.inner-box span {
align-self: center;
}