Is it possible to center a background image in a div? I have tried just about everything - but no success:
<div id="doit">
Lorem Ipsum ...
</div>
//CSS
#doit { background-image: url(images/pic.png); background-repeat: none; text-align: center; }
Is this possible?
For center or positioning the background image you should use background-position property . The background-position property sets the starting position of a background image from top and left sides of the element . The CSS Syntax is background-position : xvalue yvalue; .
First, set a background image using the background-image property. Next, set the background-repeat property to no-repeat . Then, write the fixed option for the background-attachment property. After that, apply the background-position property to the center center option and the background-size property to cover .
You can do this by setting the display property to “flex.” Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.
#doit {
background: url(url) no-repeat center;
}
try background-position:center;
EDIT: since this question is getting lots of views, its worth adding some extra info:
text-align: center
will not work because the background image is not part of the document and is therefore not part of the flow.
background-position:center
is shorthand for background-position: center center
; (background-position: horizontal vertical
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With