I would like to right align an image in a cell AND still keep the text centered in the cell. I am using a float:right on the image which displays it correctly, however it pushes the text to the left the width of the image so it is no longer centered. Is there a way to keep the text centered?
<table>
<tr>
<td style="text-align:center" width:"100">text
<img src="~/images/pencil1.png" height="25" width="25" style="float: right;" />
</td>
</tr>
</table>
CodePudding user response:
You can add position relative to td and position absolute to image and then, set righ=0 in the image
<table style="width:100%">
<tr>
<td style="text-align:center;position:relative">
text
<img src="~/images/pencil1.png" height="25" width="25" style="position:absolute;right:0" />
</td>
</tr>
</table>
Also, if you want your table become 100%, you must set the style in the table, not in the cell.
Take in mind that your text may be under the image. You can put the text over the image if you want avoid this or use a semitransparent image.
CodePudding user response:
I would wrap your text and your image with a div which assigned flex. Then you can use flex-grow: 1;
.
td {
width:50%;
}
.tdflex {
display: flex;
}
.text {
flex-grow: 1;
text-align: center;
}
<table border>
<tr>
<td>
<div >
<div >text</div>
<div>
<img src="https://via.placeholder.com/500" height="25" width="25" />
</div>
</div>
</td>
</tr>
</table>
Update
td {
width:200px;
height: 50px;
}
.tdpos {
position: relative;
}
.tdpos img {
position: absolute;
top:0;
right:0;
}
.text {
margin-top: -24px;
background: gray;
text-align: center;
}
<table border>
<tr>
<td>
<div >
<div >text</div>
<img src="https://via.placeholder.com/500" height="50" width="50" />
</div>
</td>
</tr>
</table>