Position an image in the center and add a div below it

I am seeking guidance regarding two specific questions. My objective is to showcase an image in its true size while positioning it at the horizontal center of the screen (not the exact center), followed by a div containing text directly underneath the image. The code snippet I have implemented is displayed below:

<div class="figure">;
<img src="...">;
</div>';
<div class="text">
text here
</div>

The corresponding CSS used for this implementation is as follows:

.figure{
position:absolute;
margin:0 auto;
left:0;
right:0;
bottom:10px;
top:30px;
}

.figure img{
    margin-left: auto;
    margin-right: auto;
    display: block;
    height:100%;
    width:100%;
}

Now, I have encountered two key issues. Firstly, when the height of the image surpasses the height of the screen, no vertical scrollbar appears and instead the image is automatically resized to fit the screen. Secondly, I am unsure how to position the text beneath the image without prior knowledge of the image dimensions. I attempted using figcaption but unfortunately that solution did not prove successful.

Answer №1

For perfect centering, consider using min-height: 100vh; and min-width: 100vw; along with flex display to achieve the desired result. Otherwise, vertical centering may not be achieved.

It's also recommended to enclose your text block within a div that contains the image.

If you want the image to resize by default, specify it explicitly in the CSS.

The default behavior of a div is to take up the whole row. Adding text-align: center; will only center the text within the div.

.figure {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  min-width: 100vw;
}

.centered {
  text-align: center;
}

html,
body {
  padding: 0;
  margin: 0;
}
<div class="figure">
  <div>
    <img src="http://placehold.it/950x450">
    <div class="centered">
      text here
    </div>
  </div>
</div>

Answer №2

Initially, I assume this accomplishes what you are aiming for.

html

<img src="https://static.tumblr.com/07f1e3ffdfdd03631d00e7792ea3fa93/mja6mxp/AUUna8jev/tumblr_static_tumblr_static_88o50pnpc3k04gw0ck888o80o_640.jpg"/>
<div class="text">Isn't that lovely!</div>

CSS

body {
  color: #eee;
background-image: url("chrome://global/skin/media/imagedoc-darknoise.png");
}

img {
margin: 0 auto;
display: block;
}

.text {
margin: 0 auto;
display: table;
}

Regarding your first query about the image resizing when larger than the page, it is worth noting that in your CSS, you specified the image to take up 100% of the available width and height, causing the image to stretch to fit the element by default.

To address your second question, since your "figure" div with the img has an absolute position, it disregards the positions of other elements. Changing the position property to something like "position: relative" would allow it to align itself with other elements.

Although not incredibly confident in my html and css skills, I hope my insights provide some assistance as you move forward.

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

What is the best way to position an <a> tag in the top right corner of a card using Bootstrap?

I own a card that features an image in the background. <div class="col-12 col-sm-8 col-md-6 col-lg-4 mt-4"> <div class="card"> <img class="card-img" style=" filter: brightness(75%);" src=& ...

Retrieve the image information from a specified element in the Document Object Model

Is it possible to extract the image data of a DOM element using standard JavaScript or browser extensions? I'm considering scenarios where: Creating an offscreen DOM element Populating it with dynamically styled CSS content Retrieving its image dat ...

Arranging Check Boxes Side by Side

I am struggling to properly align the three checkboxes and tables next to each other. I have managed to get the checkboxes on the same row, but aligning them neatly has proven to be a challenge. Using Notepad++ as my development tool, I am facing formattin ...

Navigate through the items in my subnavbar by scrolling the content

HTML Code <div id="subnavigation"> <?php $verbindung = mysql_connect("host", "user" , "pw") or die("Verbindung zur Datenbank konnte nicht hergestellt werden"); mysql_select_db("db") or die ("Datenbank konnte nicht ausgewählt w ...

What is the method to choose an invisible link without an identifier using Selenium WebDriver?

I am attempting to click on the link labeled 'User Requested'. This link only appears when hovering over the menu. This is the HTML code: <ul class="k-widget k-reset k-header k-menu k-menu-horizontal" id="menu" data-role="menu" tabindex="0" ...

JavaScript form validation issue unresolved

When I attempt to validate form fields using Javascript functions, they seem to not load or check the field upon clicking the submit button. <html> <body> <?php require_once('logic.php'); ?> <h1>New Region/Entit ...

What is the process for updating the background image in Ionic?

Currently facing an issue with setting an image for background in Ionic. The code provided doesn't seem to be working as expected. It appears that the style sheet is not being applied correctly. Not sure where exactly to add the style sheet or how to ...

Experiencing an unexpected wait before the requestAnimationFrame?

Surprisingly, Internet Explorer is actually performing the way I want it to in this case :-) I developed a function for SVG animations using requestAnimationFrame (for simplicity, I left out the value calculations here ... but my initial test involved an ...

JavaScript decimal precision function malfunctioning with currency format conversion

My current snippet works perfectly with the currency format 249.00, but I need to adapt it for a site that uses euros with pricing in the format 249,00. When I make this change, the total calculation goes haywire and shows as 29.900,00. Can someone advise ...

I am interested in altering the font color

Hey there, I'm new to HTML and CSS and need some help changing the font color and size of my navbar. I've included my code below: HTML code: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <me ...

How can I display the value of a variable within an Angular 4 component directly from the console?

In my Angular 4 component, I store a simple key in a variable. However, I am aware that when the app is closed, all values within the variable are erased. Here is an example of this: export class LoginComponent implements OnInit { data : any; const ...

Choosing jQuery over JQuery Mobile for a standard web application to effectively manage different devices

Creating a Unique Web Application In the works is a unique web application, similar to Trello, that divides a page into columns where tasks/cards can be added and moved between them. This desktop-focused platform will feature an information column on the ...

Having issues with Angular Material, specifically with mat-list-item and routerLinkActive not functioning as expected

Currently, I am working with a navigation view that utilizes the MatSidenavModule. The issue I am encountering is on mobile screens. When I click a mat-list-item, the mat-sidenav closes as expected. However, upon opening the mat-sidenav again, Material alw ...

Tips for Customizing the Width of Your Material UI Alert Bar

At the moment, I have refrained from using any additional styling or .css files on my webpage. The width of the Alert element currently spans across the entire page. Despite my attempts to specify the width in the code snippet below, no noticeable change ...

Extracting Text from a Span Element Using XPath in Selenium

Here is the HTML code snippet: <div class="a-row a-spacing-small a-size-small"> <div class="a-row"> <a class="a-link-normal a-declarative g-visible-js reviewStarsPopoverLink" href="#" data-action="a-popover" data-a-popover="{"closeButton":" ...

Tips for enhancing the fluidity of animations after removing an item from a list

I'm working on a project where I have a list of elements that are removed with an animation when clicked. However, I noticed that when one element is removed, the rest of the elements just jump up instead of smoothly transitioning. Is there a way to m ...

Reacting to the dynamic removal of spaces

Is there a way to dynamically remove the space between removed chips and older chips in Material-UI when deleting one of them? <div className="row contactsContainer"> {contacts.map((contac ...

How can you determine if a DIV element is within view in HTML (without being overflowed)?

Is there a way to determine if a DIV is within its container and therefore visible? In this scenario, the active button (highlighted) can be seen because it is contained within the boundaries: However, in this case: The active button cannot be viewed as ...

Acquiring the PayPal callback variable with PHP

When using PayPal Standard HTML form, upon completion of the transaction, the user is directed to the return URL. To retrieve variables such as the user email, order number, and other available information using PHP, I need to utilize the GET method from t ...

Concealed Sub Menus Within a Vertical Navigation Bar

I've successfully created a Vertical Menu with hidden submenus, but I'm struggling to make the submenu appear on hover. Any suggestions on how to achieve this? Also, I'd like to align the text all the way to the left and remove the bullets f ...