Home > front end >  Center html body tag horizontally based on width percent of image
Center html body tag horizontally based on width percent of image

Time:02-27

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 ><div >nov. 01 2020 05:50 PM - From: John ( xxxxx123456)</div><div >Hello, please see the attached image.</div></div>
<div ><div >nov. 01 2020 05:51 PM - From: John ( xxxxx123456)</div><div ><br/><div ><a href="files/image.jpg"><img src="files/image.jpg"></a></div></div></div>
<div ><div >nov. 01 2020 05:53 PM - To: John ( xxxxx123456)</div><div >Hello, well received.</div></div>
</body>
</html>

Any idea how to do this ? Thank you.

CodePudding user response:

body {
text-allign: center;
  }

Add this to your css

CodePudding user response:

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>

  • Related