Raven
Raven

Reputation: 345

Automatically get image width and adjust CSS

I added a small "bar" at the bottom of my image: http://jsfiddle.net/mown4v50/

The problem is that the box is way to big and I know that i have set the box width to 500px but can I make it automatically get the image's width and adjust it by it self? Of course can I set all images to have the same width so i don't need to mess with the box width but what's the fun with that.

CSS:

a.hovertext {
                position: relative;
                width: 500px;
                text-decoration: none !important;
                text-align: center;
            }
            a.hovertext:after {
                content: attr(title);
                position: absolute;
                left: 0;
                bottom: 0;
                padding: 0.5em 20px;
                width: 460px;
                background: rgba(0, 0, 0, 0.8);
                text-decoration: none !important;
                color: #fff;
                opacity: 0;
                -webkit-transition: 0.5s;
                -moz-transition: 0.5s;
                -o-transition: 0.5s;
                -ms-transition: 0.5s;
            }
            a.hovertext:hover:after, a.hovertext:focus:after {
                opacity: 1.0;
            }

HTML:

<body>
    <center>
        <p><a class="hovertext" href="#" title="Tomb Raider - 2013"><img src="http://tombraiders.net/stella/images/TR9/large/box-art/TR-box-art-PC.jpg" width="320" height="451" border="0" alt="Tomb Raider"></a>
        </p>
    </center>
</body>

Upvotes: 1

Views: 48

Answers (1)

GolezTrol
GolezTrol

Reputation: 116140

You can use display: inline-block on the p element to make it fit around the image. Then you can position the link by giving it left, bottom and right properties instead of a width.

p {
  display: inline-block;
}
a.hovertext {
  position: relative;
  text-decoration: none !important;
  text-align: center;
}
a.hovertext:after {
  content: attr(title);
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  padding: 0.5em 20px;
  background: rgba(0, 0, 0, 0.8);
  text-decoration: none !important;
  color: #fff;
  opacity: 0;
  -webkit-transition: 0.5s;
  -moz-transition: 0.5s;
  -o-transition: 0.5s;
  -ms-transition: 0.5s;
}
a.hovertext:hover:after,
a.hovertext:focus:after {
  opacity: 1.0;
}
<body>
  <center>
    <p>
      <a class="hovertext" href="#" title="Tomb Raider - 2013">
        <img src="http://tombraiders.net/stella/images/TR9/large/box-art/TR-box-art-PC.jpg" width="320" height="451" border="0" alt="Tomb Raider">
      </a>
    </p>
  </center>
</body>

Update fiddle

Upvotes: 2

Related Questions