clement
clement

Reputation: 4266

center a div with background in CSS

I'm trying to center a text and a icon, but the icon is set in a background.

How to do to center the text and set the icon just on the left of the text.

Here is the fiddle and the code: jsfiddle

<div class="error divError" style="text-align: center">
            <p class="errorplaceholder">Error Text</p>
        </div>


.divError {
    background: url("https://www2.eiffel.com/download/images/warning_icon.png") no-repeat scroll left center rgba(0, 0, 0, 0);
    color: #FF0000;
    font-weight: bold;
    margin: auto;
    padding: 5px 10px 5px 25px;
}

Thanks in advance

Upvotes: 1

Views: 113

Answers (6)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

Set the image as a content of before pseudoelement of your paragraph.
Doing so you don't need to know in advance the width of your icon and set padding or make assumptions with percentages

.divError  {
    color: #FF0000;
    font-weight: bold;
    margin: auto;
    padding: 5px 10px 5px 25px;
}

.divError p:before {
     content: url("https://www2.eiffel.com/download/images/warning_icon.png");
}

example fiddle http://jsfiddle.net/8RQfX/6/
Example with some extra code for a proper vertical-alignment): http://jsfiddle.net/8RQfX/6/

Upvotes: 2

Ashish Kumar
Ashish Kumar

Reputation: 3039

You can use calc property of css:

background-position:calc(50% - 40px) center;

jsfiddle: http://jsfiddle.net/8RQfX/7/

Upvotes: 0

sivakdeva
sivakdeva

Reputation: 16

you can use position percentages in the background-position attribute to get this done , if you insist that the icon should be as background image.

  background: url("https://www2.eiffel.com/download/images/warning_icon.png") no-repeat scroll 40% 50% rgba(0, 0, 0, 0);

those values should do for you .

But I feel , it would be better if the icon is placed in a separate span.

Upvotes: 0

winnyboy5
winnyboy5

Reputation: 1516

Hope this helps

.divError {
background: url("https://www2.eiffel.com/download/images/warning_icon.png") no-repeat          scroll rgba(0, 0, 0, 0);
background-position:45% 50%;
color: #FF0000;
font-weight: bold;
margin: auto;
padding: 5px 10px 5px 25px;
}

Upvotes: 0

Jacek Kowalewski
Jacek Kowalewski

Reputation: 2851

Make the p:

display: inline-block; 
padding: 0 0 0 'your_image_width'; 
background: url('you_image_url') left center no-repeat;

And the div:

text-align: center;

I think this should to the trick. If not, the idea is clear :).

Upvotes: 2

deW1
deW1

Reputation: 5660

fixed

HTML:

<body>
    <div class="error divError" style="text-align: center">
        <p class="errorplaceholder">
            <img src="https://www2.eiffel.com/download/images/warning_icon.png" alt="1" /> <span>Error Text</span>
        </p>
    </div>
</body>

CSS:

.divError {
    color: #FF0000;
    font-weight: bold;
    margin: auto;
    padding: 5px 10px 5px 25px;
}

Upvotes: 0

Related Questions