在CSS中,无论其他兄弟元素如何,我 如何将元素相对于包含元素居中? [重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

我有一个有三个孩子的内部div;一个按钮,一些文本和一个按钮组。

我使用flex来集中所有内容,但问题是文本实际上并不是相对于包含元素居中。而是将文本居中在按钮和按钮组的近边界之间。 css-not-centered

文本不在黄色框内居中。我希望文本在黄色框中居中。

有没有办法说“从外部元素的边缘测量并忽略兄弟姐妹的内缘”?

.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>
html css flexbox centering
2个回答
0
投票

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>

-1
投票

如果您希望将文本置于span元素中心,则可以直接更改元素对齐。

    .inner-box span {
    align-self: center; 
}
© www.soinside.com 2019 - 2024. All rights reserved.