问题:
I have a canvas and a table next to each other using display: flex; flex-direction: row; in a div that encompasses both elements. My problem is that when I add rows to the...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I have a canvas and a table next to each other using display: flex; flex-direction: row;
in a div that encompasses both elements. My problem is that when I add rows to the table and the height of the table exceeds the height of the canvas the canvas's height changes to match the table. Is there any way to have the canvas next to the table without the table's height affecting the canvas's height?
Here is an example of what is happening and the code. https://jsfiddle.net/u4qjwxaf/
回答1:
The align-items
property that determines the alignment on the cross axis is set to stretch
by default. This means any children will stretch to take up remaining space.
You'll just need to change align-items
to another value depending on where you'd like the canvas to sit. e.g. center
will align it to the center, flex-start
will align it to the top and flex-end
will align it to the bottom.
div.set {
display: flex;
flex-direction: row;
align-items: center;
}
You can also set it individually with align-self
:
canvas {
align-self: flex-start;
}
https://developer.mozilla.org/en-US/docs/Web/CSS/align-items
回答2:
You have attributes on the canvas for both "width" and "height". These figures control the number of pixels that the canvas contains. What you also need to do is control the appearance of the canvas. For that, you should use a style rule.
Consider the following instead:
<canvas id="myCanvas" width="400" height="400"></canvas>
<style>
#myCanvas
{
width: 400px;
height: 400px;
border: solid 1px #000;
};
</style>
Naturally, you may elect to make these styles inline as you had initially.
回答3:
You just need to contain canvas
and table
to different div
. See: fork
Or snippet:
var row = {};
var table = document.getElementById("myTable");
var rowNumber = 1;
function addRow() {
row = table.insertRow(rowNumber);
Cell1 = row.insertCell(0);
Cell1.innerHTML = "stuff";
rowNumber++;
}
div.set {
display: flex;
flex-direction: row;
}
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
font-family: arial;
}
th,
td {
padding: 0px 10px 0px 0px;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="set">
<div> <!-- notice this -->
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #000000;"></canvas>
</div> <!-- notice this -->
<div> <!-- notice this -->
<table id="myTable" style="margin-left:50px;">
<tr>
<th>column</th>
</tr>
</table>
</div> <!-- notice this -->
</div>
<br/><br/>
<button onclick="addRow()">add row</button>
</body>
</html>