无法将div的内容居中

时间:2017-12-04 09:04:38

标签: html css

我正在创建一个包含div的表格。我能够创建它,但是有一个实例,其中有一行我需要进行合并和居中。

这是我的代码。

.divTable {
  display: table;
  width: 100%;
}

.divTableRow {
  display: table-row;
}

.divTableCell {
  border: 1px solid #999999;
  display: table-cell;
  padding: 3px 10px;
}

.divTableBody {
  display: table-row-group;
}
<div class="divTable">
  <div class="divTableBody">
    <div class="divTableRow">
      <div class="divTableCell">$2</div>
      <div class="divTableCell">1</div>
    </div>
    <div class="divTableRow">
      <div class="divTableCell">&nbsp;6</div>
    </div>
  </div>
</div>

我希望6位于中心位置。我怎样才能做到这一点?

基本上如下表

<table border="1px solid black">
  <tr>
    <td>$2</td>
    <td>1</td>
  </tr>
  <tr>
    <td colspan="2" align="center">6</td>
  </tr>
</table>

3 个答案:

答案 0 :(得分:1)

如果这个单元格位于底部,那么你可以像这样使用表格标题

<div class="divTable">
  <div class="divTableBody">
    <div class="divTableRow">
      <div class="divTableCell">$2</div>
      <div class="divTableCell">1</div>
    </div>
  </div>
  <div class="divTableCaption">
    6
  </div>
</div>

CSS

.divTable {
  display: table;
  width: 100%;
}
.divTableRow {
  display: table-row;
}
.divTableCell {
  border: 1px solid #999999;
  display: table-cell;
  padding: 3px 10px;
}
.divTableBody {
  display: table-row-group;
}
.divTableCaption { /* <== Only added this */
  display: table-caption;
  text-align: center;
  border: 1px solid #999999;
  caption-side: bottom;
}

答案 1 :(得分:0)

CSS中有 colspan。 (html-colspan-in-css

解决方案

&#13;
&#13;
.tr {
  width: 100%;
}

.tr:after {
  content: " ";
  display: table;
  clear: both;
}

.td {
  border: 1px solid;
  float: left;
  box-sizing: border-box;
  padding: 3px 10px;
}

.col-6 {
  width: 50%;
}

.col-12 {
  width: 100%;
}

.text-center {
  text-align: center;
}
&#13;
<div class="table">
  <div class="tbody">
    <div class="tr">
      <div class="td col-6">$2</div>
      <div class="td col-6">1</div>
    </div>
    <div class="tr">
      <div class="td col-12 text-center">6</div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

Bootstraps' grid layout提供了这一点。

Bootstrap 解决方案

&#13;
&#13;
.bordered>div[class^=col-] {
  border: 1px solid;
}
&#13;
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="container">
  <div class="row bordered">
    <div class="col-xs-6">A</div>
    <div class="col-xs-6">B</div>
  </div>
  <div class="row bordered">
    <div class="col-xs-12 text-center">C</div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

试试这个

<!DOCTYPE html>
<html>
<body>

<form action="/action_page.php">
First name: <input type="text" name="FirstName"><br>
Last name: <input type="text" name="LastName"><br>
Email: <input type="text" name="email" value="Mouse"><br>
<input type="submit" value="Submit">
</form>

</body>
</html>