Search code examples
htmlcsstextwebcenter

How to center an element where the width is not 100%


I created a title and I made the width: 30% so that I could create a box around it, but now it isn't centered. I have tried many different things to get it centered, but none have worked. I am able to center it myself by adding left: 35%. But that isn't perfectly centered. Any ideas on how I can perfectly center my title, while the width is not at 100%?


Solution

  • You can use left and right margin's set to auto to achieve this.

    margin: 0 auto;

    h1{
    	width: 30%;
    	border: 2px solid black;
    	margin: 0 auto;
    }
    <h1>Title</h1>