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

Utilize AJAX to connect to a remote domain from an extension

I am currently working on creating a Chrome extension that will utilize AJAX to fetch data from a specific webpage and then generate notifications based on the content of that page. The webpage I am targeting is a ticketing system, and my goal is to deter ...

Steps to assign a value to an input element using the state in a React application

Hey there, I hope everything is going well for you! I have a question regarding setting the value of an input field based on the state received from props. I've tried to populate the input with data from the "profile" state using placeholders, but it ...

Struggling with AngularJs as I attempt to retrieve my Twitter timeline. It's been a challenge

Currently, I am using the code below to fetch tweets for a timeline. This snippet was originally taken from an AngularJS tutorial and worked perfectly with Twitter's search API. angular.module( 'Twitter', [ 'ngResource' ]); func ...

Using the fetch method to consume a RapidAPI JSON response

Currently, I am in the process of learning React Native and have initiated a project for that purpose. In this project, I have integrated RapidAPI (link: ) to fetch necessary data. Upon hitting the API, I receive a 200OK status, but unfortunately, I am fa ...

When utilizing JavaScript's split method, an empty string returns an array size of one instead of zero

Is there a way to separate a string using commas to create an array in Node.js? exports.test = function(rq, rs){ var mailList = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="16657e7764777856627365623875797b">[email ...

The box on my form is leaking my background color outside the 1px border, but only in Internet Explorer

While experimenting with background gradients and borders one day just for the fun of it, I made an interesting observation in Internet Explorer. The issue I encountered was that the background color was overflowing outside the radius border, but this onl ...

Challenges in creating an alternative path in ExpressJS

I am currently working on a website for my studies. I decided to use nodejs/Express, as the technology is free. The first route /home was successful, but I am having trouble creating more routes. Although I thought I had a good understanding of the system ...

Issue with executing a server-side function in a Next.js application

I'm encountering an issue with my Next app. I have a method in my ArticleService class that retrieves all articles from my SQL database. async getArticles(): Promise<IArticle[] | ServiceError> { try { const reqArticles = await sql< ...

Unlocking the power of RXJS by de-nesting subscriptions

Trying to resolve the nested subscription issue has become a time-consuming puzzle. I've experimented with mergeMap, flatMap, and switchMap without success. Unfortunately, the examples I've come across don't quite fit my needs, leaving me wi ...

Expansive variety of icon buttons in MUI React with a wide selection radius

Struggling to remove the oversized selections on icon buttons, as shown here: See large selection I discovered a solution by adding: component="span" Why does this method work? Is it a glitch? Even when the icon button is standalone without any ...

Is it possible to integrate Material UI with Bootstrap 4?

I'm currently working on a web application using React JS and Material-UI for components. I've been feeling a bit unsure about the responsiveness of my web pages, so I was wondering if it's possible to use Bootstrap 4 alongside Material-UI. ...

Baffling Visibility Issue: iframe's Transparency Lost in Chrome and IE, Only Visible in Firefox

I have encountered a puzzling issue: http://jsfiddle.net/akosk/t2KvE/8/ HTML <div id='base'> <iframe id="myFrame" src="about:blank" frameborder="0" allowTransparency="true"></iframe> </div> <script id="conte ...

Is there a way for me to retrieve the text response of a fetch request from client-side JavaScript to fastify server?

In my fastify node.js application, I am encountering an issue where I can see the text results of a promise right before it is returned to the browser's JavaScript code. However, once the promise is returned to the browser JS, all I get is an empty st ...

What causes a slow disappearance of both the form element and its child elements when the visibility attribute is set to hidden on the

Have you ever noticed that the child elements of an element form hide slowly when using visibility:hidden, but hide quickly when using display:none? This slow hiding can negatively impact user experience. I tried to find information on this issue, but eve ...

Encountered 'Exceeded Maximum Call Stack Size' error with dotenv-expand while running React on CircleCI

I'm currently facing an error while attempting to build a react app on CircleCI. This issue has recently surfaced whenever I run the command npm run build in my circle.yml file: #!/bin/bash -eo pipefail npm run build > <a href="/cdn-cgi/l/ ...

The occurrence of an Error [ERR_HTTP_HEADERS_SENT] arises due to the inability to modify headers after they have already been sent to

I have set axios to use credentials globally: axios.defaults.withCredentials = true However, when using the following useEffect hook, an error in the title is raised: useEffect(() => { const initAuth = async (): Promise<void> => { ...

The error message "Error: cannot read property ‘setDirtyAttribute’ of null" may be encountered when attempting to use the method YourModel.create({...}) in ember-typescript-cli

Encountering the error cannot read property 'setDirtyAttribute' of null even when using YourModel.create({...}) in ember-typescript-cli to instantiate an EmberObject. Model: import DS from 'ember-data'; import {computed} from "@ember/ ...

The instance is referring to "close" as a property or method during render, but it is not defined. Ensure that this property is reactive and properly defined

Upon my initial foray into Vue.js, I encountered a perplexing warning: vue.runtime.esm.js?2b0e:619 [Vue warn]: Property or method "success" is not defined on the instance but referenced during render. Make sure that this property is reactive, e ...

Sharing data between view and controller in Laravel: a guide

Currently, I am developing a product cart feature that includes subtotal and grand total values displayed within <span> tags. My goal is to pass the grand total value to the controller for further processing. However, I encountered an issue where the ...

Generate a spreadsheet file in xlsx format by using the exceljs library in Node

I am currently working with exceljs 3.8 in an attempt to generate a new XLSX file, but unfortunately the code below seems to be malfunctioning. createNewExcelFile: function (excelFilePath) { //excelFilePath: Path and filename for the Exce ...