'Center html body tag horizontally based on width percent of image
I would like the body to be centered horizontally based on the percentage width of my image (when there is one) instead of text. But I have to keep the width of the body to 50% because it may happen that I have only text in my HTML page. Also, I can't give a fixed dimension to my image because its size can vary from one to another.
An image is better than text : https://i.stack.imgur.com/KZTRj.jpg
Here is my code :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body{width:50%;margin:auto;}
img{width:70%;}
.container{page-break-inside:avoid;margin-bottom:30px;}
.sender{color:#008040;font-size:16px;}
.recipient{color:#0000FF;font-size:16px;}
.msg{font-size:16px;text-align:justify;}
</style>
</head>
<body>
<div class="container"><div class="sender">nov. 01 2020 05:50 PM - From: John (+xxxxx123456)</div><div class="message">Hello, please see the attached image.</div></div>
<div class="container"><div class="sender">nov. 01 2020 05:51 PM - From: John (+xxxxx123456)</div><div class="message"><br/><div class="attachment"><a href="files/image.jpg"><img src="files/image.jpg"></a></div></div></div>
<div class="container"><div class="recipient">nov. 01 2020 05:53 PM - To: John (+xxxxx123456)</div><div class="message">Hello, well received.</div></div>
</body>
</html>
Any idea how to do this ? Thank you.
Solution 1:[1]
use flex.
#container{
display:flex;
align-items:center;
flex-direction:column;
}
img, p{
width:50%;
text-align:center;
border:solid 2px red;
}
<div id='container'>
<p> some text</p>
<img src = "https://picsum.photos/200/150">
<p>more text</p>
</div>
Solution 2:[2]
body {
text-align: center;
}
Add this to your css
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DCR |
| Solution 2 | marc_s |
