Align the image and caption at the center in Bootstrap 4

I am presenting a figure that includes an image along with a caption. Here is the code for reference:

<figure class="figure">
  <img src="../img/atmpressure.svg" class="figure-img img-fluid" alt="pressue plot">
  <figcaption class="figure-caption text-center">Plot of pressure at different altitudes.</figcaption>
</figure>

https://i.sstatic.net/hsWCT.png

While styling my webpage using Bootstrap 4, I encountered an issue with centering both the image and the caption within the figure element. Despite applying the text-center class to the caption, I faced challenges in horizontally centering the image itself. The classes mx-auto and text-center did not yield the desired result when used on the image within the figure (as demonstrated below).

<!DOCTYPE html>
<html lang="en>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Styles -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

  <!-- MathJax used to display equations -->
  <script type="text/x-mathjax-config">
    MathJax.Hub.Config({ tex2jax: {inlineMath: [['$','$'], ['\(','\)']]}, CommonHTML: {scale: 130} });
  </script>
  <script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML"></script>
</head>

<body>

  <div class="container">
    <div class="row">
      <div class="col">

        <p>In dolorum elit ratione velit nesciunt aliquid Vitae culpa exercitationem animi ex quis praesentium Fuga sapiente deserunt dignissimos quia nihil officiis. Labore quibusdam molestiae nostrum.</p>

        <figure class="figure text-center">
          <img src="http://kenwheeler.github.io/slick/img/lazyfonz2.png" class="figure-img img-fluid mx-auto d-block" alt="pressure plot">
          <figcaption class="figure-caption text-center">Plot of pressure at different altitudes.</figcaption>
        </figure>

      </div>
    </div>
  </div>
</body>

</html>

Do you have any suggestions on how to horizontally center the entire figure within the column?

Answer №1

The issue at hand has a two-fold solution. Initially, the problem was that you had only applied .text-center to the figcaption, causing the img and figcaption not to be centered in the figure. To rectify this, simply move .text-center to the parent figure element to horizontally center both the inline img and text within the figcaption.

Upon further examination with additional context from the surrounding page elements, it appears that you also want the figure itself to be centrally aligned relative to its neighboring content. By default, the figure is left-aligned within the .col due to the .figure class which adds display: inline-block; property. The easiest way to achieve the desired centered alignment is either by removing the .figure class to revert back to the native display: block, allowing .text-center to vertically align it, or by adding the .d-block class if retaining the .figure styling is necessary.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <!-- Styles -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="col">
        <p>Elit ratione dolorum velit nesciunt aliquid Vitae culpa exercitationem ex animi quis praesentium Fuga sapiente dignissimos deserunt quia officiis nihil. Vero dignissimos excepturi iste ut fugiat! Nostrum quibusdam labore molestiae.</p>
        <figure class="text-center">
          <img src="http://kenwheeler.github.io/slick/img/lazyfonz2.png" class="figure-img img-fluid" alt="pressure plot">
          <figcaption class="figure-caption">Plot of pressure at different altitudes.</figcaption>
        </figure>
      </div>
    </div>
  </div>
</body>

</html>

Answer №2

Experiment with using the w-100 text-center class within the figure tag.

Your updated code snippet will resemble the following:

<figure class="figure w-100 text-center">   <!-- include 'w-100 text-center' class here -->
  <img src="../img/atmpressure.svg" class="figure-img img-fluid" alt="pressure plot">
  <figcaption class="figure-caption text-center">Plot illustrating pressure changes at various altitudes.</figcaption>
</figure>

Answer №3

To customize the "figure" class, you can use the following CSS:

.figure {display: table;margin-right: auto;margin-left: auto;}

.figure-caption {display: table-caption;caption-side: bottom;text-align: center;}

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

Tips on implementing ng-template within an Angular application

I'm in the process of developing a client-side angular application and have encountered an issue regarding the implementation of angular's ng-template. Currently, I have a navbar set up as follows: <nav class="navbar navbar-inverse" > ...

Working with HTML5 canvas to draw multiple images

Here is the code I'm working with: http://jsfiddle.net/zyR9K/4/ var Enemies = { x: 25, y: 25, width: 20, height: 30, speed: 0.5, color: "#000", draw: function () { canvas.fillStyle = ...

The radar chart created with amchart.js disappears when placed within bootstrap columns

I'm encountering an issue while trying to display radar charts using amchart.js in bootstrap columns. The "amStockGraph" charts render perfectly, however, the radar charts appear blank with no errors in the console. Any advice on this matter would be ...

Column with space between arranged rows in a container

I have a container with multiple rows, each containing several columns. I am looking to adjust the spacing between each column <div class="main" style="margin-bottom:0px"> <div class="container"> <div class="row"> <div ...

What is causing me to have difficulty importing any of the images located in the public folder?

I'm currently tackling the NextJS framework, and I'm having trouble importing images that are stored in the public folder. Despite being able to navigate through folders, the images aren't displaying as expected. Here is the import line and ...

Arrange two div elements side by side so they remain adjacent even when you adjust the browser size

After years of success with my floated left and right divs, I am now facing a challenge with responsive design. No longer able to rely on fixed widths, I find that when the screen size decreases, the right div moves below the left one. I know that using f ...

The function .val() is not a recognized method

hello everyone here is the section of my HTML code: <div class="radio"> <input type="radio" name="certain" id="oui" value="oui"/> <label for="oui"> oui </label> <br /> <input type="radio" name="certain" id=" ...

Step-by-step guide on achieving 100% height for a child element within a parent using Flexbox

Currently facing an issue where trying to make a child element take up 100% of the remaining height of its parent container causes the child's height to go beyond the boundaries of the parent. HTML .container { height: 340px; /* background-i ...

Can HTML/CSS be used to specifically target handheld mobile devices?

I am looking to optimize my video display in HTML by only showing it on desktop browsers. The difference in bandwidth between desktop and mobile devices is affecting the performance of mobile browsers, so I want to target only desktop users. Is there a way ...

Are there ways to implement Vue.js transitions without directly setting the height in the code?

I'm having an issue with a Vue app I created where I need to make an element expand and collapse when a button is clicked. I want the effect to be smooth and animated, but using the <transition> tag alone isn't working as expected. The prob ...

Align the prices of products in a uniform position within each table cell

Apologies for the lengthy explanation. I am working with osCommerce and have a page that displays all our product specials in a 3 column table layout. My challenge is to align the price of each product so that they are aligned perfectly across the screen. ...

The two items are not situated side by side

Trying to make my page responsive, but when I inspect and look into mobile view, the elements do not align next to each other like they do on desktop. https://i.sstatic.net/8WhxD.png I want the shopping cart icon and button to be positioned next to each o ...

Utilizing the Bootstrap grid system allows for input fields to automatically expand to 100% width once they reach

I am encountering some challenges while attempting to develop a responsive form using bootstrap grids. The issue seems to arise when resizing the browser window, as the grid classes behave unexpectedly by expanding and taking up the entire page width at ce ...

The hover state of a div will not be lost if its parent element is not being hovered over

When hovering over the second, third, or fourth item, hidden text will appear on the left side. If you hover your cursor over the hidden text, it will disappear again. I want to be able to hover over the second item, move my cursor to "hide", and click o ...

Tips for combining dvloading and required functionalities on the submit button

My form has 2 fields that must be filled out, and I used the required attribute to enforce this rule. Enter A:<input type="text" name="a" required><br> Enter B:<input type="text" name="b" required><br> <button type="submit" cl ...

Ways to include scrolling specifically for one template

As a newcomer to frontend development, I have recently started learning Vue and the Quasar Framework. I am currently working on a table and trying to set a fixed table name with only the table items scrollable. <template> <q-table virt ...

My goal is to dynamically adjust the height of this section based on its content

I experimented with this code snippet: <section class="unique"> <div class="this d-flex pt-5"> <div class="leftside2 w-50 h-100"> <img src="images/twowomen.jpg" alt=" ...

Tips for defining CSS styles for the background color of <td> elements within a sitemap

I am facing a similar issue to the one discussed in this thread Possible to fill a table cell with a bg color?. The challenge I am encountering is related to applying CSS styles to the td tags within a sitemap structure. (Although it functions correctly ...

The data type 'Event' cannot be assigned to the data type 'string' in this context

Recently diving into Angular, I came across a stumbling block while working through the hero tutorial. The error message that popped up was: Type 'Event' is not assignable to type 'string' You can see the error replicated here. ...

Navigating Parent Menus While Submenus are Expanded in React Using Material-UI

My React application includes a dynamic menu component created with Material-UI (@mui) that supports nested menus and submenus. I'm aiming to achieve a specific behavior where users can access other menus (such as parent menus) while keeping a submenu ...