我寫過這樣的代碼:-
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
我想根據(jù)在類名中給出的div的大小來設(shè)置這個背景圖像,但是運行后出現(xiàn)的圖像是這樣的
我想要這樣的輸出
我可以制作文本,但不能制作背景圖像
可以在TailwindCSS中用任意值設(shè)置url,這樣就不必使用style對象和類的組合。正如評論中提到的,最好的方法是使用background-size屬性來覆蓋。
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>
對div使用下面的CSS屬性來顯示背景圖像的中心部分
{background-position:center;background-size:cover}
示例代碼
.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>