【问题标题】:Flex box alignment of left and centre elements [duplicate]左侧和中心元素的弹性框对齐[重复]
【发布时间】:2023-03-08 07:58:01
【问题描述】:

   #xxx {
      position:relative;
      display:flex;
      height:32px;
      width:150px;
      background-color:black;
      color:white;
      font-family: Helvetica, Arial, sans-serif; 
      justify-content: center;
      margin-left:10px;
   }
   #xxx > span {
      align-self: center;
   }
   #xxx > img{
      margin-right:auto;
   }
   <body>
      <div id="xxx"><img src="xxx.png" height="32" width="32"/><span>hello</span></div>
   </body>

我一直在尝试使以下内容正确对齐。我试图让图像左对齐并且跨度内的文本居中。起初我试图用绝对定位跨度并设置 left:0;但这搞砸了。然后我尝试了 margin:auto 但这搞砸了居中对齐的元素。

<!DOCTYPE HTML>
<html>
   <style>
   #xxx {
      position:relative;
      display:flex;
      height:32px;
      width:150px;
      background-color:black;
      color:white;
      font-family: Helvetica, Arial, sans-serif; 
      justify-content: center;
      margin-left:10px;
   }
   #xxx > span {
      align-self: center;
   }
   #xxx > img{
      margin-right:auto;
   }

   </style>
   <body>
      <div id="xxx"><img src="xxx.png" height="32" width="32"/><span>hello</span></div>
   </body>
</html>

【问题讨论】:

  • paulie 我不喜欢这个问题的答案,你已将其标记为重复,我不清楚
  • 感谢 link2pk,这是迄今为止最好的。你能提供一个答案吗?
  • @MarMan29,参见this post,以及this post 中的框#66。
  • 哈哈谢谢 Michael_B 是的,你是对的 ;) 感谢您的回复,是的,我已经抵消了左边距以抵消绝对不占用空间。干杯伙伴。

标签: css flexbox


【解决方案1】:

#xxx {
      position:relative;
      display:flex;
      height:32px;
      width:150px;
      background-color:black;
      color:white;
      font-family: Helvetica, Arial, sans-serif; 
      margin-left:20px;
   }
    span {
      align-self: center;
      margin-left:25%;


   }
  img{
  position:relative;
  }
<!DOCTYPE HTML>
<html>
     <body>
      <div id="xxx"><img src="http://www.imagenspng.com.br/wp-content/uploads/2015/02/yoshi-super-mario-01.png" height="32" width="32"/>
        <span>hello</span>
       </div>
   </body>
</html>

【讨论】:

  • 谢谢 Gowtham,但不是你的答案中的左边距做了对齐吗?
  • Ya Marman 我尝试了不同的方法,但这个成功了,因为我给出了百分比,它不会影响响应
  • 是的,但这似乎是一个黑客解决方案,没有任何冒犯。拥有 justify-content: center; 有什么意义?如果我们只是使用边距来抵消?
  • 对不起,这是一个拼写错误,我已将其删除,请查看。
  • 问题是如果宽度或图像尺寸发生变化,需要重新计算边距设置,因为它不再正确......
猜你喜欢
  • 2016-04-05
  • 2022-08-23
  • 2016-07-21
  • 2019-08-21
  • 2021-04-09
  • 2018-07-11
  • 1970-01-01
  • 2018-01-26
  • 1970-01-01
相关资源
最近更新 更多