How can I control the placement of my Chart.JS pie chart's legend, as well as its appearance?

前端 未结 3 1127
眼角桃花
眼角桃花 2021-02-05 07:01

I am able to create a pie chart using Chart.JS with this code:

HTML

3条回答
  •  萌比男神i
    2021-02-05 07:28

    I think this what you want: DEMO

    First, you need to make canvas responsive by overriding fixed width and height and wrap it in additional div that can be used for positioning. I used display: table for centering elements but setting inner divs to inline-block also works if you wish for chart and legend to take different amount of space than 50:50.

    HTML:

    CSS:

    canvas {
        width: 100% !important;
        height: auto !important;
    }
    
    .table {
        border: 1px solid red;
        display: table;
        width: 100%;
        table-layout: fixed;
    }
    
    .cell {
        display: table-cell;
        vertical-align: middle;
    }
    

    UPDATE: Did some adjustment based on additional information by OP NEW DEMO

    HTML:

    Top 10 Items


    CSS:

        .topleft {
            margin-top: -4px;
            margin-left: 16px;
            margin-bottom: 16px;
            padding: 16px;
            border: 1px solid black;
        }
    
    canvas {
        width: 100% !important;
        height: auto !important;
        margin-left: -25%;
    }
    
    .chart {
        border: 1px solid forestgreen;
        width: 100%;
        overflow: hidden;
        position: relative;
    }
    
    .pie {
        position: relative;
        padding: 10px 0;
        // adjust as necessary
        padding-left: 10px;
        padding-right: 0;
    }
    
    .legend {
        position: absolute;
        right: 10px;
        top: 10px;
        height: 100%;
        // adjust as necessary:
        width: 48%;
    }
    
    @media (max-width: 480px) {
        .legend {
            position: relative;
            width: 100%;
        }
        .pie {
            margin: 0;
        }
    }
    
    .pie-legend ul {
        list-style: none;
        margin: 0;
        padding: 0;
        width: 300px;
    }
    
    .pie-legend span {
        display: inline-block;
        width: 14px;
        height: 12px;
        border-radius: 100%;
        margin-right: 4px;
        margin-bottom: -2px;
    }
    
    .pie-legend li {
        margin-bottom: 4px;
        display: inline-block;
        margin-right: 4px;
    }
    

提交回复
热议问题