Snackoverflow
Snackoverflow

Reputation: 828

Image url in css based on html title value

I'm trying to generate multiple hexagons with background images, using a php for loop:

<?php
        $dir    = 'resources/images/logos';
        $images = scandir($dir);
        for($i = 2; $i < count($images); $i++) {
            $title = explode('.', $images[$i])[0];
            ?>
                <div class="hexagon_loc<?= $i ?>">
                    <div class="hexagon image" title="<?= $title ?>"></div>
                </div>
    <?php } ?>

This works fine, I make a div, with a different class name every time and with the correct title (based of on the filename of the image). Now I want to have a for loop in scss which draws the hexagons, I also want to define the background-images there. But since I can't pass any kind of variables from html/php to css/sass and the fact that the attr() function is widely unsupported I have no way of dynamically doing this, which would result in the titles possibly being mismatched with the images. Is there anyway to do this anyways? Or do I have to use a different approach entirely?

Example sass where I want to define the image:

.hexagon_loc {
$image: '../../resources/images/bill.jpeg';
@include hexagon($image);
margin-left: 100px;
}

Using vanilla JavaScript to solve this would also be a possibility

Thanks

Upvotes: 0

Views: 165

Answers (1)

Jax-p
Jax-p

Reputation: 8531

In this situation, I would use <img> HTML element.

There is a CSS solution but it is not supported in many browsers.

div { background-image : attr(data-image); }

Upvotes: 1

Related Questions