Positioning a div on top of an image

After browsing through various solutions, I still can't seem to get my div and image layout to work as intended. I have a div with an image that fills the entire space (set to 100% for responsiveness). I'm trying to overlay some text on the image using an article element. However, I'm facing an issue where the text doesn't stay centered both horizontally and vertically when I resize the page. It aligns well horizontally but vertically it shifts out of place, affecting the content below (even though I haven't styled them yet). Any help or suggestions would be greatly appreciated. Thank you.

HTML:

<div class="featuredpost">
    <img src="images/forest.jpg">

    <div class="featured"> 
        <article>
            <header>
                <h1><a href="#">Featured Post Goes Here</a></h1>
            </header>

            <footer>
                <p class="postedby">Posted by User</p>
            </footer>

            <content>
                <p>"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
                <p>"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
            </content>

            <button type="button" onclick="alert('Hello world!')">Read More</button>
        </article>  
    </div>  
</div>

CSS:

.featuredpost{
width: 100%;
margin: 0 auto; 
}

.featuredpost img{
    width: 100%; 
    height: auto;
    position: relative;
}

.featured{
    margin: 0 auto;
    width: 80%; 
    background-color: rgba(0,0,0,0.5);  
    color: #fff;    
    top: 50%;
    position: absolute;
    left: 10%;
}

.featured article{
    padding: 10px 30px;
}

Answer №1

Web Development Topics

<div id="main-container">
  <div id="overlay-section"></div>
  <img id="image" />
</div>

CSS Styling

#main-container {
    position: relative;
}
#overlay-section, #image {
    position: absolute;
    top: 0px;
    left: 0px;
}
#overlay-section {
    z-index: 5;
}

Answer №2

To achieve a table-cell behavior, you can set the html/body elements accordingly.

Check out this example on CodePen

html {
  display: table;
  height: 100%;
  width: 100%;
  background-size: cover;
}
body {
  display:table-cell;
  vertical-align:middle;
}
.featured{
    margin: 0 auto;
    width: 80%; 
    background-color: rgba(0,0,0,0.5);  
    color: #fff;
  position:relative;
}
.featuredimg {
  position:absolute;
  top:0;
  left:0;
  width:100%;
}

You can also use an image as a background by following these steps:

View example with background image on CodePen

html {
  display:table;
  height:100%;
  width:100%;
  background:url(images/forest.jpg);
  background-size:cover;
}
body {
  display:table-cell;
  vertical-align:middle;
}

Answer №3

I encountered a similar problem and have found a solution that I believe will work for you.

  1. Start by creating a div with a background image (table)
  2. Add a box to contain the title (table-cell)
  3. Create another box to center #2 within (table)
  4. The content of the title will vary

Here is an example pseudo-code illustrating the nesting:

    <1 table>
     <3 table>
      <2 cell>title</2>
     </3>
    </1>

Since #2 is inside #3, and #3 is situated within #1, you end up with a table inside another table. You may need an additional wrapper surrounding #3 as a table cell in order to center #3 properly.

article header h2:after{
content: "";
display: block;
border-bottom: 1px solid #3cc19c;
margin: 1em 45%;
}
.image-box { /*  BACKGROUND FOR HEADER */
background-image: url(https://placeholdit.imgix.net/~text?txtsize=83&txt=1000%C3%97500&w=1000&h=500);
background-size: cover;
background-repeat: no-repeat;
display: table;
width: 100%;
}
.title-container-frame{ /* BOX FOR TITLE TO SIT IN */
width: 300px;
height: 300px;
background: white;
display: table;
outline: 4px double white;
margin: 100px auto;
}
.title-container{ /* HOLDS THE TITLE TO BE CENTERED */
display: table-cell;
vertical-align: middle;
}
article{
  text-align:center;
}
<article>
<header>
<div class="image-box">

<div class="title-container-frame">
<div class="title-container">
<h2>Meet Shawn</h2>
<h3>A stand-up guy</h3>
</div>
</div>
</div>
</header>
<div class=bit-2>
<hr>
<p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Candid wedding photography is my passion. I can't imagine doing anything else for a living. The best wedding photography captures raw emotional moments that words cannot express.</p>
<p>True-to-life imagery is the new direction of wedding photography. We provide beautiful images to our clients on their wedding day while everyone is eager to see them.</p>
<p>"Lorem derit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Please feel free to contact me <a><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9efbf3fff7f2defbf3fff7f2b0fdf1f3">[email protected]</a></a> I would love to answer any questions you might have.</p>
</div>
</article>

View the live example at https://jsfiddle.net/0qa2g4b5/. I suggest breaking down the image into responsive parts first and then devising a CSS solution suitable for each part as the screen size changes. This approach can lead to a more efficient solution.

The best course of action depends on how you want the final result to adapt to smaller screens. Using @media queries in your CSS to adjust styles based on screen size could be the most elegant solution.

Other simpler but less elegant solutions exist, each with its own drawbacks. For instance, using background-size: cover; allows you to clip the background image but may crop certain parts. Alternatively, using background-size:contain ensures the entire image is displayed but may lead to height discrepancies when resizing the container.

If you want the title text to resize along with the container, you can set font-size:1em on one element and font-size:inherit on another. Utilizing viewport units like vh or vw for sizing can also help with responsiveness, although readability issues may arise on different devices.

To address these challenges, consider creating specific CSS rules within @media queries for various screen sizes. Use tools like Chrome Developer mode to test and fine-tune your design for optimal responsiveness.

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

When CSS card buttons are hovered over, padding or margin is applied to the entire card (as far as I know)

Hello fellow CSS learners! I am currently working on a frontend mentor exercise involving a 3-card preview. I noticed that after adding a hover state to the buttons, the entire card expands slightly when hovered over. The cards were created using fl ...

Ways to make an image wander aimlessly across a webpage while also spinning as it moves (with the help of jQuery or CSS)

I am working on making a div randomly move around a page. This is a related question Now, I have replaced the div with a picture like an "arrow" and I want it to randomly move while also pointing in the right direction by changing its rotation angle as i ...

When scrolling, the menu is being overlapped by the Carousel in HTML5, CSS3, and

I am currently working on a One Page HTML webpage that needs to be responsive, and the requirement is to use Bootstrap. I have gone through all the tags but can't seem to identify the issue. One problem I encountered is that when I scroll down the pa ...

Challenge with Hovering within Cufon Elements

When utilizing multiple lists and hover states, the parent Cufon style takes over the child. For instance, in the scenario below, when hovering over the Second Level link, it will switch to a different weight. Is there a setting I can adjust to keep the n ...

What is the best way to eliminate an unassigned margin from my layout?

The content of my css file is as follows: .menu { background-color: black; color: white; height: 100px; opacity: 0.5; } html { background-image: url('image.jpg'); background-size:cover; } Despite the lack of text ...

What could be causing my inability to accurately guess people's ages?

My latest project involves developing a game where players have to guess names from images. Each game consists of 10 rounds, followed by a bonus round where participants must wager their points on guessing the age of the person in the image within a 2-year ...

The use of @font-face in CSS seems to be malfunctioning

I am having trouble changing the font in my CSS to what I want it to be. body{ background-color:#a8a7a7; color:#C50909; font-family: main, Calibri; text-align:center; } @font-face{ font-family: main; src: url('fonts/RegencieLight.ttf'); } ...

XMLWorker: unable to align cell vertically properly

Upon reviewing this code snippet: <table> <tr> <td border="1"> <table> <tr><td>Blah</td></tr> <tr><td>Blah</td></tr> ...

Iterate over JSON dates in JavaScript

Trying to utilize JavaScript in looping through a JSON file containing time periods (start date/time and end date/time) to determine if the current date/time falls within any of these periods. The provided code doesn't seem to be working as expected. ...

How do I prevent a media query written for small screens from also affecting large screens?

@media only screen and (min-width: 320px), (min-width: 360px), (min-width: 375px), (min-width: 600px){ CSS properties for various screen widths are defined here } ...

The onblur event is triggering prior to the value being updated

There are two input fields within a <form> element. I am trying to retrieve the value of one input field (dpFin) once it has been changed. The issue is that when I attempt to get the new value inside the event using var endDt = document.getElementByI ...

Struggling to map JSON data (received from WCFRest) onto an HTML table

After creating a WCFRestful service that populates data in JSON format as shown below: {"GetEmployeesJSONResult":"[{\"Name\":\"Sumanth\",\"Id\":101,\"Salary\":5000},{\"Name\":\"Sumanth\",\"I ...

Identifying Touch Interaction exclusively on WebGL Canvas within threejs

Currently, I am developing a threejs application that requires input from HTML buttons and utilizes Raycast Detection on touch within threeJS. The issue I am encountering is that when the user clicks an HTML button, the Raycast function is triggered as we ...

Incorporating fresh components and newly defined attributes in Angular

Is there a way for me to click on a new component button, specify a name, description, select type, and add attributes such as default value and type? I need all this information to be saved and for the new button to appear in the drag-and-drop section. ...

Looking for a logo placed in the center with a top fixed navigation using Bootstrap

I am in need of a Centered Logo using Bootstrap fixed top navigation. The goal is to have the brand centered within the navigation. Check out my Sample Fiddle .LandPageNavLinks { list-style-type:none; margin:0; padding:0; } .LandPageNavLin ...

Why does the for loop function correctly with console.log but not with innerHTML?

Hello! I'm completely new to JavaScript, so please excuse any oversight... Below is the code that runs when a button on the page is clicked: function getNumbers() { var firstValue = document.getElementById("time_one").value; var ...

The CSS code designed to limit the display to only a two-line sentence is failing to work properly in Internet Explorer

I've implemented the following CSS code to ensure that the display sentence doesn't exceed 2 lines, with the remaining text being replaced by "...". .bell-notification-max-words-display { overflow: hidden; display: -webkit-box; ...

Creating collapsible column functionality for the <td> element within a <tr> in mobile view using React

Ensuring my websites have a consistent look across various devices is a top priority for me. I currently have a table that is displayed like this: https://i.sstatic.net/a91LL.png Is there a way to modify this table so that when viewed on mobile, the < ...

Extracting Data: Unlocking Information from Websites

My friend and I are working on a school project that involves creating a small application. The main goal of this app is to find pharmacies in our area. I am looking to extract information from two specific websites. gun = day/date lc = id of town ...

Tips for updating the color of carousel image slider indicators (arrows) specifically for the second slide

Is there a way to customize the carousel image slider indicator arrows for only the second image slide? For the first slide, I want the indicators to be black, but for the second slide, I would like them to be white. Can this be achieved? I attempted to ...