Vertically align two side by side elements to each other

寵の児 提交于 2020-01-17 12:37:06

问题


I have two elements side by side: a chart and a DataTable. The DataTable can change size from interacting with the page and the chart should change size when the window is resized. I want the shorter one to always centre itself with the taller one i.e. the current height of their containing div. I'd like it to be done in CSS only, if possible. This answer doesn't seem to work for me: CSS - vertically align two or more (side by side) elements in a div;

I have the following:

<div id="container">
    <svg id="chart"></svg>
    <div id="dataTable"></div>
</div>

CSS:

#container {
    height: 50%;
    width: 80%;
    margin: 0 auto;
}

#chart {
    overflow: hidden;
    float: left;
    width: 50%;
    display: inline-block;
}

#dataTable {
    overflow: hidden;
    float: left;
    width: 50%;
    display: inline-block;
}

回答1:


You can't use float and inline block at the same time. I'd try removing the floats.

Then it's a matter of reseting the whitespace between the inline block elements.

* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
#container {
  width: 80%;
  margin: 0 auto;
  border: 1px solid green;
  font-size: 0;
  /* whitespace fix */
}
#container > * {
  font-size: 1em;
  /* reset font-size */
}
#chart {
  width: 50%;
  display: inline-block;
  vertical-align: middle;
  background: red;
  height: 50px;
}
#dataTable {
  width: 50%;
  display: inline-block;
  vertical-align: middle;
  height: 150px;
  background: blue;
}
<div id="container">
  <svg id="chart"></svg>
  <div id="dataTable"></div>
</div>



回答2:


You can try using Flexbox for this. Align items will ensure the items stay centered.

fiddle: https://jsfiddle.net/yftaLtxr/

HTML

<div id="container">
    <svg id="chart">a</svg>
    <div id="dataTable">b</div>
</div>

CSS

#container {
    height: 50%;
    width: 80%;
    margin: 0 auto;
    display:flex;
    align-items:center;
}

#chart {
    height:50vh;
    overflow: hidden;
    float: left;
    width: 50%;
    display: inline-block;
    background-color:#f00;
}

#dataTable {
    overflow: hidden;
    float: left;
    width: 50%;
    display: inline-block;
}


来源:https://stackoverflow.com/questions/33305961/vertically-align-two-side-by-side-elements-to-each-other

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!