如何将包裹div内的标签居中?

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

我有一个包含柱状数据的长div:

A very
Big chicken
Comes to
Dine with us
Every day

我使用了以下风格

<div style="flex: 1; width: 180px; height: 100%;">
    <div style="height: 100%; display: flex; flex-wrap: wrap; flex-direction: column;">
        <div>A very</div>
        <div>Big chicken</div>
        <div>Comes to</div>
        <div>Dine with us</div>
        <div>Every day</div>
    </div>
</div>

使它包装数据,以便我有很多列

A very         Dine with us
Big chicken    Every day
Comes to   

我试图在整个事物的下方添加一个标签,但是由于我将div宽度设置为某个值,因此居中显示它会向左移动,因为它不会考虑整个div的大小。

A very         Dine with us
Big chicken    Every day
Comes to   

   LABEL

我怎样才能实现我想要的目标,即:

A very         Dine with us
Big chicken    Every day
Comes to   

            LABEL
html css flexbox
2个回答
0
投票

你想要的是一张桌子。然后一个div拿着标签和一些CSS,这样你就可以控制它的位置了。这是一个关于codepen https://codepen.io/anon/pen/WPmOWR的工作示例

<div style="flex: 1; width: 280px; height: 100%;">
 <table style="width:100%">
    <tr>
      <th>A Very</th>
      <th>Dine With us</th> 
    </tr>
    <tr>
      <td>Big Chicken</td>
      <td>Every Day</td> 
    </tr>
  <tr>
<td>Comes to</td>  
</tr>
</table>
    <div class="label"> LABEL</div>
</div>

CSS

.label{
     width: 100%;
     margin: 0 auto;
     text-align: center;
     background: red;
     }

0
投票

为了使标签文本相对居中,您需要将其放在容器内,该容器的宽度与包含数据的容器的宽度相同。

我修改了你的代码而没有改变你的思路。

.wrapper {
  width: auto;
  margin: 0 auto;
}

.container {
  background-color: #edc3c3;
  width: 400px;
  height: 50px;
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
}

.container div {
  width: auto;
}

.container-label {
  background-color: #e1edc3;
  text-align: center;
}

.container-label h1 {
  display: block;
}
<div class="wrapper">
  <div class="container">
    <div>A very</div>
    <div>Big chicken</div>
    <div>Comes to</div>
    <div>Dine with us</div>
    <div>Every day</div>
  </div>
  <div class="container-label">
    <h1>my label</h1>
  </div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.