Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center a (background) image within a div?

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?

like image 275
oompahloompah Avatar asked Oct 18 '22 03:10

oompahloompah


People also ask

How do I center a background image in a div?

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; .

How do you center the background of a picture?

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 .

How do I center an inside section of a div?

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.


2 Answers

#doit {
    background: url(url) no-repeat center;
}
like image 91
Lucas Avatar answered Oct 26 '22 20:10

Lucas


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);

like image 37
TimCodes.NET Avatar answered Oct 26 '22 18:10

TimCodes.NET