Centre a div over an img
I hav开发者_运维知识库e a gallery of images, all 210px width, but with various heights.
I want to place over each image a div box that contains the words "coming soon", has a solid background colour, is 30px high, width would be unknown. the div box needs to be centred vertically and horizontally.
How do i go about this in CSS?
I've googled, tried everything i can think of, haven't found a solution at all..
Instead of using image tags, could you perhaps use a bunch of DIVs with the gallery images as a background image? Then inside that DIV, just put your text and style it however you need.
You could make a CSS class with the text styling, width, etc. Then just use the style attribute in the DIV to set the background-image and height.
The answer by Patrick is certainly a good way to go, saving on some markup.
But if you can't or prefer not to make the images a background of a container, you could instead use some positioning options. For instance, if you can live with a fixed width on the "coming soon" part, you could do something like this:
ul {
list-style: none;
margin: 0 0 0 -2em;
padding: 0;
}
li {
position: relative; /* this makes it a containing block */
float: left;
margin: 0 2em 2em 0;
padding: 0;
}
.msg {
position: absolute;
top: 50%;
left: 50%;
margin-top: -15px; /* assuming it's 30 pixels high, half */
margin-left: -75px; /* assuming it's 150 pixels wide, half */
width: 150px;
height: 30px;
line-height: 30px;
color: #fff;
text-align: center;
background: rgba(0,0,0,.8); /* almost black, f**k old browsers */
}
HTML
<ul>
<li>
<img src="/images/meep.png" alt="" />
<div class="msg">Coming soon.</div>
</li>
</ul>
Note that the line-height: 30px is so the text will be vertically centered in the container, and this is actually bad if the message needs to go down to a second line. In that case, you need to ditch the fixed height of the container, maybe add some padding, and then use a more traditional line height like 1.2em. In that case though, you'll need some jQuery or something to calculate the height of the parent container in order to get the right "top: px" height.
精彩评论