How can you ensure an image is centered properly when padding is applied?

Is there a way to center an image without affecting padding around it?

Check out this sandbox for reference

HTML

<div class="imageParent">
            <figure id='img-div'>
                <img class='image card'
                    src='https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg'
                    alt='Cat sleeping' />
                <figcaption id='img-caption'>
                    <p class='centeredText'> Cat sleeping </p>
                </figcaption>
            </figure>
        </div>

CSS

.image {
        background: white;
        max-width: 100%;
        height: auto;
        display: block;
        margin: 0 auto;
        padding: 2em 2em 4em 2em;
      }

      @media (max-width: 500px) {
        .image {
          padding: 1em 1em 2em 1em;
        }
      }

Answer №1

To ensure the padding inside the container div does not affect the overall width of your image, use box-sizing: border-box;. This will keep the padding within the specified dimensions and prevent the image from overflowing outside the container.

Learn more here

The border-box property instructs the browser to include any border and padding in the specified width and height of an element. Therefore, if you set a width of 100 pixels for an element, it will account for any additional border or padding without expanding beyond the defined size.

.image {
  background: white;
  max-width: 100%;
  height: auto;
  display: block;
  margin: 0 auto;
  padding: 2em 2em 4em 2em;
  box-sizing: border-box;   
}

@media (max-width: 500px) {
  .image {
    padding: 1em 1em 2em 1em;
    box-sizing: border-box;       
  }
}
<div class="imageParent">
  <figure id="img-div">
    <img
      class="image card"
      src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg"
      alt="Cat sleeping"
    />
    <figcaption id="img-caption">
      <p class="centeredText">Cat sleeping</p>
    </figcaption>
  </figure>
</div>

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 steps can be followed to incorporate a loading gif into this popup and subsequently eliminate it?

These simple inquiries are starting to get on my nerves. I can't keep waiting around for my website designer to resolve this issue. It shouldn't be that difficult... I managed to figure out most of it by researching similar questions, but I could ...

Arranging SVG icons in a row within the navigation bar

Having trouble aligning the icons side by side? Even with margin and padding adjustments, I couldn't get it right. I've scoured multiple sites for a solution but couldn't find one. As an attempt to fix this, I created a bar with aligned butt ...

The utilization of local storage within Backgridjs

I am creating an app using Backbone.js (Marionette Framework) along with additional functionalities like Backgrid, Backbone local storage, Backbone Radio, epoxy, and Backbone relational model. Encountered Problem: An issue arises when utilizing the local ...

What causes the disparity in the rendering of iframe content height when using "src" compared to "srcdoc"?

After comparing the behaviors of iframes with src and srcdoc, I stumbled upon a puzzling difference: a div set to 100% height renders as the full height of the iframe when using src=[data uri], but not with srcdoc. The issue can be easily replicated with ...

Utilizing data attributes in E2E testing for optimal results

We have decided to transition from using tag and classname selectors to data attributes in Cypress for our E2E testing. This change is intended to make the selectors more robust and less prone to breaking. Specifically, Cypress recommends using data-cy, d ...

Tips for eliminating the border surrounding the entire table in Material-ui

Is there a way to edit a table in Material-ui without displaying it as a card? I'm looking to remove the border around the entire table, but I couldn't find any information on how to do that. Can someone help me out? Here is a link about the com ...

Tips for positioning two elements side by side in an li element without needing to clear each time

I'm struggling with a stacked list that involves floating an image (icon) alongside text. The constant need to clear after each list item is becoming cumbersome. Anyone have any suggestions for making this more streamlined and tidy? <ul> < ...

What is the best way to synchronize the scale of images with the tempo of a song?

I just started learning CSS, JS, and HTML and I have a question about scaling an image based on a song. Despite searching through YouTube and various forums, I still haven't found a solution. Any help would be greatly appreciated :) Here is the HTML ...

Preserving Scroll Location Through Back Button Usage and Ajax Manipulation of the Document Object Model

Currently, I am incorporating a feature where results are loaded in using ajax with an infinite scroll. However, there is an issue when a user clicks on an item in the list and navigates away from the page - upon returning by clicking the back button, they ...

Adjust CSS classes as user scrolls using skrollr

I am currently facing an issue with the prinzhorn/skrollr plugin when trying to use removeClass/addClass on scroll function. I have attempted to find a solution but unfortunately, nothing has worked for me. <li class="tab col s3"><a data-800="@cl ...

What is the process for extracting the time value from a jQuery timepicker?

I have been attempting to retrieve values from my time picker when a selection is made, but I am not seeing any values returned nor displayed in my HTML timepicker input field. Despite trying various methods, none have proven successful thus far. Method ...

Issue with SVG mask not functioning when transform is applied

I am struggling to apply a mask to a transformed SVG element. When I try to do this with a path, the structure is the same. If I apply the mask to an element outside of the transformed group, it works as expected. However, if I try to do the same inside, t ...

Ways to align text in the middle and shift it downward?

I'm currently attempting to center the bottom navigation bar using the following CSS code: #main-nav { margin-left: auto; margin-right: auto;} Unfortunately, this method is not achieving the desired result. I even tried adding <center></cen ...

When hovering over the menu list, the background-color of the text area remains the same

I am facing an issue with my list menu. The hover effect changes the background color only in the box area, but not in the text area. I would like to figure out a way to make both areas change color on hover: Here is the code snippet: <div class="se ...

JavaScript Subscribe / Unsubscribe Button

I am trying to create a simple JavaScript program that allows users to like and dislike content. However, I am new to JavaScript and finding it a bit challenging. Basically, when the user clicks on the Follow button, the "countF" variable should increase ...

The issue with ng-bind-html causing the disappearance of paragraph spaces

Is there a way to preserve paragraph breaks when using ng-bind-html to display text on the screen? I am having an issue where all the text appears as one big chunk if there are paragraph breaks in the data pulled from the database. Not sure what is causing ...

Are you looking for a demonstration of "Creative Loading Effects" that triggers when the page is loaded?

I came across this demo for a preloader on my website called Creative Loading Effects, specifically the "3D Bar Bottom" effect, which I find very exciting. However, I noticed that it only loads when we press the button, and not automatically when the page ...

What methods can I use to prevent columns from merging into a single column?

I am currently in the process of building a website using Bootstrap 3.1.1. The body tag is set with a min-width of 800px. The information that I want to showcase must be presented in a grid format, specifically resembling the layout of a parking lot. Dis ...

Verify if there is a date present within the JSON entity

I have a PHP array containing date strings and I want to validate them using a native HTML5 date input element. To achieve this, I have converted the date array into a JSON object for use with JavaScript: <script> var date_array = <?php echo json ...

Is there a way to showcase my information on flash cards using JavaScript?

Currently, I am developing a full stack application that utilizes JavaScript on both the front and back end. This application allows users to create their own flashcards set. Upon clicking "View Cards," the data is fetched and the question-answer pair is d ...