gpt4 book ai didi

html - 为什么一个表格单元格中元素的大小会影响另一个表格单元格中元素的对齐方式?

转载 作者:行者123 更新时间:2023-11-28 17:48:36 26 4
gpt4 key购买 nike

我有一个关于以下 HTML 的问题(我添加了红色边框以帮助您看到问题):

<div style="display: table; border: 1px solid red">
<div style="display: table-row; border: 1px solid red">
<div style="display: table-cell; border: 1px solid red">
<div>1</div>
<div>2</div>
</div>
<div style="display: table-cell; border: 1px solid red">
<div>
<canvas style="border: 1px solid red"></canvas>
</div>
</div>
</div>
</div>

当我在我的桌面浏览器上运行它时,它看起来像“1”出现在它自己的列中,但在高度方面它似乎与 Canvas 的底部对齐。

所以这是我的问题:

  1. 为什么“1”与 Canvas 出现在同一行,而“2”出现在不同的行? “1”和“2”假设从左侧单元格的顶部开始彼此出现, Canvas 出现在另一个不相关的单元格中。
  2. 您建议如何针对大多数浏览器解决此问题,以便编号的元素显示在 Canvas 旁边而不是 Canvas 下方?

附言将它插入 jsfiddle 在我的 android 手机浏览器中看起来不错

先谢谢你!

最佳答案

Demo Fiddle

Why does "1" appear on the same line as the canvas and "2" on a separate line? "1" and "2" are suppose to appear one the each other starting from the top of the left cell, and the canvas in another unrelated cell.

div 是 block 级元素,要让它们显示在同一行,您需要将它们设置为例如显示:内联 block ;

How do you propose to fix this for most browsers so that the numbered items appear next to the canvas and not below it?

vertical-align:top; 添加到父 div


因此,修改后的代码如下所示:

<div style="display: table; border: 1px solid red;">
<div style="display: table-row; border: 1px solid red;">
<div style="display: table-cell; vertical-align:top;border: 1px solid red;">
<div style="display:inline-block;">1</div>
<div style="display:inline-block;">2</div>
</div>
<div style="display: table-cell; border: 1px solid red;">
<div style="display: inline-block">
<canvas style="border: 1px solid red;"></canvas>
</div>
</div>
</div>
</div>

考虑到这一点,通常最好的做法是将样式与内容分开,并且不要依赖内联 CSS,例如:

Demo Fiddle

HTML

<div class='table'>
<div class='row'>
<div class='cell'>
<div>1</div>
<div>2</div>
</div>
<div class='cell'>
<div>
<canvas></canvas>
</div>
</div>
</div>
</div>

CSS

.table {
display:table;
}
.row {
display:table-row;
}
.cell {
display:table-cell;
vertical-align:top;
}
.cell div {
display:inline-block;
}
.table, .row, .cell, canvas {
border:1px solid red;
}

关于html - 为什么一个表格单元格中元素的大小会影响另一个表格单元格中元素的对齐方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22766055/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com