Is there a way I can appropriately display an image in a specific size box?

Check out the code snippet I wrote below:

import React from 'react'

function OurCourse() {
  return (
    <div className='w-full '>
        <div className='w-full h-[390px]' style={{
            backgroundImage:'url(https://images.unsplash.com/photo-1532012197267-da84d127e765?ixlib=rb-
            4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=387&q=80)',
            backgroundSize:'contain',
            backgroundRepeat:'no-repeat',
        }}>

        </div>
    </div>
  )
}

export default OurCourse 

The issue is that the background image doesn't adjust according to the size of its div as expected after running the code.

https://i.stack.imgur.com/veHFw.png

I'm aiming for a result similar to this:

https://i.stack.imgur.com/omedP.png

I have been able to modify the text, but the background image isn't displaying correctly.

Answer №1

You have the ability to easily set the URL with any desired value in TailwindCSS, eliminating the need for a combination of style objects and classes. To achieve your goal, it is recommended to utilize the background-size property set to cover.

function OurCourse() {
  return (
    <div className="h-[390px] bg-cover bg-center bg-[url('https://images.unsplash.com/photo-1532012197267-da84d127e765?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=600&q=90')] grid place-content-center"> 
      <h1 className="text-white font-serif text-2xl">Our Courses</h1>
    </div>
  )
}

ReactDOM.createRoot(document.getElementById('root')).render(<OurCourse />);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
<script src="https://cdn.tailwindcss.com"></script>

<div id="root"></div>

Avoid using w-full or width: 100%. By default, block elements in HTML fill the available space by 100%, making it unnecessary most of the time.

Answer №2

Follow these CSS instructions to ensure the center portion of the background image is displayed:

{background-position:center;background-size:cover}

Example Code

.h-390 {
  color: #fff;
  position: relative;
  width: 80%;
  display: inline-block;
  height: 180px;
  background-image: url(https://images.unsplash.com/photo-1532012197267-da84d127e765?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=387&q=80);
  background-size: cover !important;
  background-repeat: no-repeat;
  background-position: center;
}

.text {
  top: 46%;
  left: 30px;
  position: absolute;
}
<div class='w-full h-390'>
  <div class="text">Our courses</div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display the background-image of the <body> element only when the image has finished loading

I have a webpage where I want to delay showing a large image until it has finished downloading. Instead, I would like to display a background with a fading effect while the image loads. The challenge is that the background image must be set within the bod ...

What is the method to customize the color of the Stepper component in React Material UI?

The image shows my attempt to modify the step color based on its status: green for correct, yellow for in-progress, and red for incorrect. Can anyone guide me on how to achieve this? ...

Image renders only on a single page in Express.js

I am facing an issue while attempting to display an image on multiple pages using Pug and Express. The image should be visible on the routes '/', 'data', and 'update'. While it is successfully displayed on the root '/&ap ...

Implementing a stylish gradient background with HTML 5 progress bar tag

I am trying to customize an HTML5 progress bar tag in a unique way: The background of the bar should have a gradient with a fixed width of 100%, but I want the gradient to only be visible where the value of the bar is... progress[value]::-webkit-progres ...

How can I pass a value from JavaScript back to the .blade file in Laravel using DataTables?

I have some rows that are being displayed: The DataTable plugin within app.js is responsible for outputting each row. My goal is to target a specific value, ${row.category_id} let TABLE = $('#categoryList').DataTable({ { data: &ap ...

Issues with the Dropdown Menu

I'm currently working on a dropdown menu and I've encountered two issues. When I hover over the links in the main navigation bar (such as 'about' and 'connect'), only the actual words are clickable, not the entire area tha ...

"Fixing the position of a div on the Samsung Galaxy S8 navigation bar to

Here is the HTML code I am working with: <div class="app-bar"> <a href="#'>icon</a> <a href="#'>icon</a> <a href="#'>icon</a> <a href="#'>icon</a> </div>' ...

rxjs iterates through an array executing each item in sequential order

Is there a way to make observables wait until the previous one has completed when they are created from an array? Any help is appreciated! export class AppComponent{ arr: number[] = [5, 4, 1, 2, 3]; fetchWithObs() { from(this.arr) ...

Retrieve webpage content using an ajax request in JavaScript

I'm working on an HTML page with an Ajax call to load table content. <html> .... <script sec:haspermission="VIEW_NOTE" th:inline='javascript'> require(['app/agent/viewGlobalAgent'], function (){ ...

Ways to merge values across multiple arrays

There is a method to retrieve all unique properties from an array, demonstrated by the following code: var people = [{ "name": "John", "age": 30 }, { "name": "Anna", "job": true }, { "name": "Peter", "age": 35 }]; var result = []; people. ...

Display the React component following a redirect in a Next.js application that utilizes server-side rendering

Just starting out with next.js and encountering a problem that I can't seem to solve. I have some static links that are redirecting to search.tsx under the pages folder. Current behavior: When clicking on any of the links, it waits for the API respo ...

Is it possible to replicate the functionality of useGridApiRef() in mui/x-data-grid without the pro version?

Currently, I am incorporating a material ui data grid table into a larger react web application. The table's header lacks any interactive features such as sorting, so my goal is to prevent users from navigating it using the keyboard. While searching ...

Updating JSON data post XMLHttpRequest call

Currently experiencing a puzzling moment. I'm attempting to insert more information into my object after retrieving it from an external source (just for testing purposes, I intend to add random values). Without further ado: As an example, here is w ...

The router component in "react-router-dom" is not functioning properly

My goal is to explicitly utilize history in my project. While I am familiar with BrowserRouter, I prefer to use Route and make history one of its properties. Upon running the program, I encounter this page: enter image description here Below is my AppRout ...

Is there a way to verify if the jcrop widget (copping area) has been successfully initialized?

I am currently utilizing the library . This library provides four handlers to detect when a crop is activated, updated, changed, or removed. My task now is to determine when the cropping widget was initially created. However, I have noticed that there is ...

Exploring the power of Angular's ng-repeat to generate hierarchical lists

I am looking to display a structured list of layers and sublayers by looping through an object using ng-repeat. var lyrslist = [ { layername: "Base Maps", layertype: "layer" }, { layername: "Open Street Map", layertype: "sublayer" },    { layer ...

Every time I switch views using the router in vue.js, my three.js canvas gets replicated

After creating a Vue.js integrated with three.js application, I encountered an issue with the canvas getting duplicated every time I opened the view containing the three.js application. The canvas remained visible below the new view, as shown in this image ...

The CloudWatch logs for a JavaScript Lambda function reveal that its handler is failing to load functions that are defined in external

Hello there, AWS Lambda (JavaScript/TypeScript) is here. I have developed a Lambda handler that performs certain functions when invoked. Let me walk you through the details: import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda' ...

Create interfaces for a TypeScript library that is available on npm for export

I have a project in TypeScript that I am packaging as a library to be used by both JavaScript and TypeScript projects. After compiling, I upload the .js and .d.ts files to npm. The main.ts file exports the following: interface MyInterface{ // ... } clas ...

ReactJS Enhancements: Additional Selection Feature

Is there a way to access both {board.id} and {board.name} properties in my select value? I tried using example={board.name} but it didn't work. handleChange(event){ this.setState({value: event.target.value}); this.setState({examp ...