Zanic L3
Zanic L3

Reputation: 1088

Background image only on one column of a CSS grid?

div {
    display: grid;
    width: 100%;
    grid-template-columns: 60% 40%;
    border: 1px solid brown;
}
.gridItem {
    width: 100%;
    height: 50px;
    grid-column: 2/3;
    border: 1px solid orange
}
<div>
  <div class="gridItem"><p>Test 1</p></div>
  <div class="gridItem"><p>Test 2</p></div>
  <div class="gridItem"><p>Test 3</p></div>
</div>

How can I get that there's a background image set to the left of the Test 1, Test 2 and Test 3? So in the first 'brown' column? I cannot edit the HTML file sadly (its 'locked due to CMS)

Or should I use <table> for this matter?

Upvotes: 1

Views: 1365

Answers (1)

Temani Afif
Temani Afif

Reputation: 272947

Apply it to the whole grid and control its size

.box {
  display: grid;
  grid-template-columns: 60% 40%;
  border: 1px solid brown;
  background: 
    url(https://picsum.photos/id/104/800/800) 
    left/ /* on the left */
    60% auto  /* take only 60% of width */
    no-repeat; /* don't repeat */
}

.gridItem {
  width: 100%;
  height: 50px;
  grid-column: 2/3;
  border: 1px solid orange
}
<div class="box">
  <div class="gridItem">
    <p>Test 1</p>
  </div>
  <div class="gridItem">
    <p>Test 2</p>
  </div>
  <div class="gridItem">
    <p>Test 3</p>
  </div>
</div>

Or with a pseudo element to have more control over the position:

.box {
  display: grid;
  grid-template-columns: 60% 40%;
  border: 1px solid brown;
  position:relative;
}
.box:before {
  content:"";
  position:absolute;
  top:0;
  left:0;
  bottom:0;
  width:60%;
  background: url(https://picsum.photos/id/104/800/800) center/cover;
}

.gridItem {
  width: 100%;
  height: 50px;
  grid-column: 2/3;
  border: 1px solid orange
}
<div class="box">
  <div class="gridItem">
    <p>Test 1</p>
  </div>
  <div class="gridItem">
    <p>Test 2</p>
  </div>
  <div class="gridItem">
    <p>Test 3</p>
  </div>
</div>

Upvotes: 2

Related Questions