Search code examples
htmlgeometrycentermargin

How to center a triangle in the exact center of a div


I am trying to center a triangle in the exact center of a div, but i cant do it. It positions itself in the middle of the div but just on horizontal alignment not vertical .I made the margin: 0 auto; but still doesn't work.I have also tried display: table; margin: 0 auto; on the inner div giving a margin: 0 auto; to outside div ,yet nothing.I also tried with display: inline-block; and no result. And i don't know why! Does someone have any idea?

My simple code is : jsfiddle.net/


Solution

  • There are few options.

    My favourite is to give outer div an absolute position, give the inner one a relative position and then use top:50% to position vertically. You also need to add a negative margin of half the height of the triangle because top:50% will centre the top of the triangle not the middle of it.

    #main_content {
        width: 300px;
        height: 300px;
        background-color: red;
    
        position: absolute;
    }
    
    
    #container {
        width: 0px;
        height: 0px;
        border-style: solid;
        border-width: 25px 43.3px 25px 0;
        border-color: transparent #007bff transparent transparent;
    
        position: relative;
        top:50%;
        margin:  -21.65px auto; //Half the height of your triangle
    }