垂直对齐 div 中的跨度

问题描述 投票:0回答:2
html css twitter-bootstrap bootstrap-4
2个回答
16
投票

display: flex; justify-content: center; align-items: center;
设置为col-sm text-center,或者将
display: flex; justify-content: center;
设置为
col-sm text-center
,将
align-self: center;
设置为
<span>

.col-sm.text-center {
    display: flex;
    justify-content: center;
    align-items: center;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
<style>

</style>
<div class="row">
  <div class="col-sm text-right" style="line-height: 20px; height: 20px; color:#004990; text-decoration:none; font-family:Helvetica, Arial, sans-serif; font-size:10px;">
      Your Account
  </div>
</div>
<div class="row">
  <div class="col-sm text-center" style="background-color:#0471AF; height:100px;">
    <span class="align-middle">ABC Company</span>
  </div>
</div>


0
投票

我尝试使用 CSS flex 来做到这一点,但如果它超出了块(使用“overflow:auto”),它会截断对象

通过实验,我发现如果使用Grid,可以很容易地将任何对象(线或块)居中。

我真的很喜欢这个解决方案,所以我在 CMS Effcore 中实现了它。

这是一个代码示例:

<head>
    <style>
        [data-id^='example-'] {
          max-width: 800px;
          height: 200px;
          margin: 20px auto;
          background: gray;
        }
        [data-id^='example-'] img {
          width: 50px;
          height: 50px;
          border: 1px solid black;
          background: gray;
        }
    </style>
</head>
<body>
    <div data-id="example-1">
        <img src="gallery/pictures/thumbnail-01.png">
    </div>
    <div data-id="example-2">
        <img src="gallery/pictures/thumbnail-01.png">
    </div>
</body>
</html>

网格示例:

/*
┌─────┬───────────────────────┬─────┐
│ 1fr │          1fr          │ 1fr │
├─────┼───────────────────────┼─────┤
│     │  ▲                    │     │
│     │ ◀┼──────────────────▶ │     │
│ 1fr │  │ 1px|max-content    │ 1fr │
│     │  │                    │     │
│     │  ▼                    │     │
├─────┼───────────────────────┼─────┤
│ 1fr │          1fr          │ 1fr │
└─────┴───────────────────────┴─────┘
*/

[data-id='example-1'] {
  display: grid;
  grid-template-columns: 1fr minmax(1px, max-content) 1fr;
  grid-template-rows   : 1fr minmax(1px, max-content) 1fr;
}

[data-id='example-1'] img {
  grid-column-start: 2;
  grid-row-start:    2;
}

通过“垂直对齐”示例。

[data-id='example-2'] {
  text-align: center;
  white-space: nowrap;
}

[data-id='example-2']:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

[data-id='example-2'] img {
  vertical-align: middle;
}

可以在此处找到实时代码示例:https://developer.mozilla.org/ru/play?id=Eyc%2BipG68bj%2FU6aDy%2Bk%2BrSo4K0qhZCU6X%2Fk6GwIGyoh5qd88KqDrGBU%2FI%2FwLKPa4%2BnJLhAb%2BA2AjMCFy

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