I need to center the <div>
in <td>
because now (with my code) I see the div at right but I want to see the div in the center of <td>
. This is my code:
<table width="100%">
<tbody>
<tr>
<td>
<div>
<label>Start date</label>
<br/>
<input type="date" name="start_date">
</div>
</td>
<td>
<div>
<label>End date</label>
<br/>
<input type="date" name="end_date">
</div>
</td>
</tr>
</tbody>
</table>
Anyone can help me? I don' know how I can do this.
If you do not force the width set for div
, changes in alignment for td
do nothing because div
takes 100% of the width td
. Then you need to provide alignment for the div
NOT using text-align:
div {
text-align: center;
}
let div
leveled at you and its width is less than the width so on. then use margin
:
div {
margin: 0 auto;
}
Is better use flex:
td {
display: flex;
align-items: center;
align-content: center;
}
You can only center the div
(not the text!) without using javascript by adding a width
to the elements. Then you can use margin: auto;
.
div {
width: 150px;
margin: auto;
}
<table width="100%">
<tbody>
<tr>
<td>
<div>
<label>Start date</label><br/>
<input type="date" name="start_date">
</div>
</td>
<td>
<div>
<label>End date</label><br/>
<input type="date" name="end_date">
</div>
</td>
</tr>
</tbody>
</table>
Another way would be to use jQuery. This can even work with dynamic width.
$(window).resize(function() {
$("td div").each(function() {
var element = $(this),
elementWidth = element.width(),
parentWidth = element.parent().width();
element.css("margin-left", ((parentWidth - elementWidth) / 2) + "px");
});
}).resize();
div {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="100%">
<tbody>
<tr>
<td>
<div>
<label>Start date</label><br/>
<input type="date" name="start_date">
</div>
</td>
<td>
<div>
<label>End date</label><br/>
<input type="date" name="end_date">
</div>
</td>
</tr>
</tbody>
</table>
Use align
in td
<td align='center'>
Live Demo
Add style="text-align: center;"
in the table tag. Here is the JSFiddle
<table width="100%" style="text-align: center;">
<tbody>
<tr>
<td>
<div>
<label>Start date</label><br/>
<input type="date" name="start_date">
</div>
</td>
<td>
<div>
<label>End date</label><br/>
<input type="date" name="end_date">
</div>
</td>
</tr>
</tbody>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With