What is the best way to show only a section of a background in CSS?

Being a novice in HTML and CSS, I am facing the challenge of displaying an image as a banner with text overlay. Despite trying various methods, it seems impossible to achieve this directly with an image element, so I resorted to using CSS's background feature. However, the issue I'm currently encountering is that only the top half of the image is being displayed.

Here is the image I'm attempting to showcase

This is my current setup:

https://i.sstatic.net/4LP21.jpg

Everything works well, including the aspect ratio of the image, but I now aim to center the display on the middle section, similar to this:

https://i.sstatic.net/GcRV7.jpg

I want less of the clouds and more focus on the mountains. How can I crop the background image to center it on the middle portion?

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

body,
html {
  width: 100%;
  height: 100%;
  font-family: "Lato";
  color: white;
  margin: 0;
  padding: 0;
}

h1 {
  font-weight: 700;
  font-size: 5em;
}

.content {
  padding-top: 10%;
  text-align: center;
  text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4), 0px 8px 13px rgba(0, 0, 0, 0.1), 0px 18px 23px rgba(0, 0, 0, 0.1);
}

.headerText {
  padding-top: 10%;
}

hr {
  width: 400px;
  border-top: 0.5px solid #f8f8f8;
  border-bottom: 1px solid rgba(0, 0, 0, 0.2);
}

p {
  color: blue;
}

#banner {
  width: 100%;
  background: url(https://images.unsplash.com/photo-1571847490051-491c12ff6540?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2550&q=80) no-repeat center top;
  background-size: cover;
}

#banner h4 {
  padding-bottom: 100px;
}
<html>

<head>
  <title>Website Sample Project</title>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="css/app.css">
</head>

<body>

  <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
  <span class="navbar-toggler-icon"></span>
</button>
    <a><img src="https://via.placeholder.com/100x40"></a>
    <ul class="navbar-nav ml-auto">
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Locations</a>
        <div class="dropdown-menu" aria-labelledby="dropdown01">
          <a class="dropdown-item" href="locations/narnia.html">Narnia</a>
          <a class="dropdown-item" href="#">Neverland</a>
          <a class="dropdown-item" href="#">Somewhere</a>
          <a class="dropdown-item" href="#">Nowhere</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">About</a>
      </li>
    </ul>
  </nav>

  <section id="banner">
    <div class="container">
      <div class="row">
        <div class="col-lg-12">
          <div class="content">
            <a><img src="https://via.placeholder.com/600x160"></a>
            <div class="headerText">
              <h3>Sample Text</h3>
            </div>
            <hr>
            <h4>Sample Text</h4>
          </div>
        </div>
      </div>
    </div>
  </section>

  <script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script>
  <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>


</body>

</html>

Answer №1

background: url(https://images.unsplash.com/photo-1571847490051-491c12ff6540?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2550&q=80) no-repeat center top;

swap with:

background: url(https://images.unsplash.com/photo-1571847490051-491c12ff6540?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2550&q=80) no-repeat center center;

UPDATE:

modify the vertical alignment percentage at the end of the line:

background: url(https://images.unsplash.com/photo-1571847490051-491c12ff6540?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2550&q=80) no-repeat center top;

for instance, you can use this as a reference

no-repeat center 35%;

and adjust the number to suit your needs.

Answer №2

To start, adjust the height of your image by cropping it to the desired size, approximately 3000px for example. Utilize CSS media queries to switch the background image at different breakpoints such as desktop (2500px) and tablet (900px).

Regarding image positioning:

background: url("yourpathtoimage.jpg") center center no-repeat;

This code horizontally and vertically centers the image while preventing it from repeating.

If you want to move the image slightly towards the top 1/3:

background: url("yourimagepath") 0 15% no-repeat;

The "0" and "15%" represent X and Y positions respectively. For more information, refer to this link: https://www.w3schools.com/cssref/pr_background-position.asp

Keep in mind that if you crop the image into multiple sizes as suggested earlier, adjusting the position settings may not be necessary.

Additional Resource: CSS media queries guide https://www.w3schools.com/css/css_rwd_mediaqueries.asp

Answer №3

To create a full background image, set the height of #banner.

#banner {
    width: 100%;
    background: url(https://images.unsplash.com/photo-1571847490051-491c12ff6540?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2550&q=80) no-repeat center top;
    background-size: cover;
    height: 100%;
}

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

body,
html {
  width: 100%;
  height: 100%;
  font-family: "Lato";
  color: white;
  margin: 0;
  padding: 0;
}

h1 {
  font-weight: 700;
  font-size: 5em;
}

.content {
  padding-top: 10%;
  text-align: center;
  text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4), 0px 8px 13px rgba(0, 0, 0, 0.1), 0px 18px 23px rgba(0, 0, 0, 0.1);
}

.headerText {
  padding-top: 10%;
}

hr {
  width: 400px;
  border-top: 0.5px solid #f8f8f8;
  border-bottom: 1px solid rgba(0, 0, 0, 0.2);
}

p {
  color: blue;
}

#banner {
  width: 100%;
  background: url(https://images.unsplash.com/photo-1571847490051-491c12ff6540?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2550&q=80) no-repeat center top;
  background-size: cover;
  height: 100%;
}

#banner h4 {
  padding-bottom: 100px;
}
<html>

<head>
  <title>Website Sample Project</title>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="css/app.css">
</head>

<body>

  <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
  <span class="navbar-toggler-icon"></span>
</button>
    <a><img src="https://via.placeholder.com/100x40"></a>
    <ul class="navbar-nav ml-auto">
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Locations</a>
        <div class="dropdown-menu" aria-labelledby="dropdown01">
          <a class="dropdown-item" href="locations/narnia.html">Narnia</a>
          <a class="dropdown-item" href="#">Neverland</a>
          <a class="dropdown-item" href="#">Somehere</a>
          <a class="dropdown-item" href="#">Nowhere</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">About</a>
      </li>
    </ul>
  </nav>

  <section id="banner">
    <div class="container">
      <div class="row">
        <div class="col-lg-12">
          <div class="content">
            <a><img src="https://via.placeholder.com/600x160"></a>
            <div class="headerText">
              <h3>Sample Text</h3>
            </div>
            <hr>
            <h4>Sample Text</h4>
          </div>
        </div>
      </div>
    </div>
  </section>

  <script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script>
  <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>


</body>

</html>

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

Having issues with Bootstrap customization in an Angular 7 project

I am currently working on customizing a Bootstrap 4 theme within an Angular 7 project. After installing Bootstrap, I updated my angular .json file to include the following: "styles": [ "./node_modules/@angular/material/prebuilt-themes/de ...

I am experiencing difficulty with playing my embed file on Chrome as the request for the audio file is consistently being "canceled."

I implemented a feature on my webpage that uses jQuery to play a sound whenever users make an error. Here is a snippet of the HTML code: <embed id="beepCache" src="sound/beep.wav" autostart="false" type ="audio/x-wav" width="0" height="0" hidden="hidd ...

What is the best way to create a <div> that will automatically start a new line based on the user's input?

Is it possible to create a div that automatically inserts a new line for each new line in the code it detects when typing? For example, if I type: <div> Hello, World! How are you doing today? </div> This would normally be displayed as ...

Obtain the value of a range using JQuery

I made an attempt to retrieve the value of JQuery's range slider when it changes. Here is how I tried: On the HTML/PHP page: <div class="total"> <label for="">Total</label> <p><span class="monthrc"></span ...

Difficulties encountered with CSS transitions when using the background

I stumbled upon some interesting examples on Stack Overflow about the fade effect on link hover. Curious, I decided to try it out myself and created this JSFiddle. <div class="fade"/> .fade { -o-transition: 0.3s; -moz-transition: 0.3s; -khtml-tran ...

Conceal the .dropdown-backdrop from bootstrap using solely CSS styling techniques

Is there a way to hide the .dropdown-backdrop element from Bootstrap for a specific dropdown on a webpage using only CSS? I found a solution that involves Javascript, you can view it on JSFiddle here. However, I am hoping to achieve this without relying o ...

Using jQuery and JSON data to dynamically populate a second dropdown menu with filtered options

I am working on a form with two drop-down menus and a text box. The first drop-down contains static values, while the second drop-down is populated dynamically from a JSON array. My goal is to filter the options in the second drop-down based on the selecti ...

How does the function window.open determine whether to open a new tab or switch to an existing tab based on specific criteria?

As I navigate through new tabs and existing tabs, I am curious about the criteria that determines whether a new tab is opened or if the browser simply reopens an existing tab with the same name. Could someone shed light on the specific parameters being co ...

Touchscreen feature enables elements to be pushed away with the mouseover effect

I have been using this code to create an effect where an object jumps away when the mouse comes close: $("button").mouseover(function(){ $(this).css({ left:(Math.random()*80)+"%", top:(Math.random()*80)+"%", }); }); Is there a way ...

What is the best way to overlay my slider with a div containing content?

In the hero section of my website, there is a slider with 3 slides. I am looking to add a div element that will display content over these slides at all times, regardless of which slide is currently showing. ...

CORS blocked the JavaScript Image's request

I am encountering an issue with my code that involves capturing selected divs using the HTML2Canvas library. However, when I try to download the captured image file, it is not working as expected. The error message I keep receiving is "Access to Image at ...

Learn how to efficiently transfer row data or an array object to a component within Angular by utilizing the MatDialog feature

My goal is to create a functionality where clicking on a button within a specific row opens up a matDialog box displaying all the contents of that row. Below is the HTML snippet: <tr *ngFor="let u of users"> <td data-label="ID& ...

Utilizing React to highlight buttons that share the same index value upon hover

I have some data in a JavaScript object from a JSON file, where certain entries have a spanid (number) while others do not. I've written React code to highlight buttons with a spanid on hover, but I'm looking for a way to highlight or change the ...

Determining the dimensions of a div once it has completed loading

Is there a way to retrieve the width and height of a div after it has fully loaded, rather than before? I am currently using JavaScript to get the dimensions, but it seems to be returning the values before the image has finished loading. How can I rectify ...

Which is the ideal library for creating this specific chart - shown in the image in the description - in reactjs?

After numerous unsuccessful attempts, I have finally decided to seek help in creating this chart. I would highly appreciate any assistance that can be provided. https://i.sstatic.net/jtQ3I.jpg ...

Is there a way to conceal the scrollbar in the mobile view (on a mobile device or emulator) in a React application without disrupting the scrolling functionality?

I am looking to conceal the scrollbar on mobile devices throughout my app while still allowing users to scroll. I have attempted to hide the scrollbar using CSS properties like scrollbar, scrollbar-thumb, scrollbar-thumb:hover, and scrollbar-track. This ...

Tips for aligning the elements in the navigation bar in the center

I am faced with a dilemma regarding my navbar design. Here is an image of my current navbar layout: I am attempting to align the components within the navbar to resemble the following design: Here is the HTML code I am using: <!-- Navbar --> < ...

The printing function for the window system can cause disruptions to the layout of the table

After creating a page with a simple table that can be filled in and printed, I noticed some issues with the table formatting after printing. The intended table design was supposed to look like this: https://i.stack.imgur.com/aAk89.png However, upon print ...

What is the best way to give this CSS button a "highlight" effect when it is clicked using either CSS3 or JavaScript?

In the HTML page, I have two buttons implemented with the following code: <!-- Button for WIFI projects: --> <a title="WIFI" href="javascript: void(0)" id="showWifi_${item.index}" class="showWifi"> <div class="news_box news_box_01 hvr-u ...

adjust the fixed div's width to match the percentage-defined width of its parent element

My goal is to make a div with the position: fixed property have the same width as its parent element, which is a td. However, I am having trouble achieving this. Here is my current code: HTML: <table style="width: 90%; border: 1px solid black;"> & ...