-1

I want to have a button image centred in a div of fixed size both horizontally and vertically.

<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
            div#fixed-size {
                width: 800px;
                height: 600px;
                border: 1px solid red;
                display: block;
            }

            button {
                padding: 0;
                margin: auto;
                display: block;
                width: 256px;
                height: 256px;
                position: absolute;
                top: 0;
                bottom: 0;
                left: 0;
                right: 0;
            }
        </style>
    </head>
    <body>
        <div id="fixed-size">
            <button>
                <img src="aqua.png">
            </button>
        </div>
    </body>
</html>

What should I write instead of button { /* ... */ } for the button to be centered in a div and not in a whole page?

qubix00n
  • 107
  • 8

1 Answers1

1

ive changed your code to where the button is relative and the parent makes sure the button inside is centered, using flexbox styling

justify-content: center and align-items: center

make sure that all the children of the display flex parent are aligned in the middle both horizontally and vertically.

if you want to learn more about it, check this website: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
            div#fixed-size {
                width: 800px;
                height: 600px;
                border: 1px solid red;
                display: flex;/* changed */
                justify-content: center;/* added */
                align-items: center;/* added */
            }

            button {
                padding: 0;
                margin: auto;
                display: block;
                width: 256px;
                height: 256px;
                position: relative;/* changed */
                top: 0;
                bottom: 0;
                left: 0;
                right: 0;
            }
        </style>
    </head>
    <body>
        <div id="fixed-size">
            <button>
                <img src="aqua.png">
            </button>
        </div>
    </body>
</html>
Ramon de Vries
  • 1,148
  • 4
  • 18
  • 1
    if this solved your problem, please accept this as the correct answer :), this way other people can see your problem is solved – Ramon de Vries Jun 05 '20 at 14:13
  • This works and is also the solution I go for when centering elements. In case you're adding multiple elements inside one container, make sure to add " flex-direction: column; " to the container. This will stack the nested elements below eachother. – Rico Jun 05 '20 at 14:20