How to center an image within a viewport without worrying about the width of the viewport

I'm working on centering an image slideshow within the viewport, regardless of its width. It's easy to accomplish when the viewport is wider than the image by using margin: auto;. However, when the viewport is narrower than the image, such as on a tablet in portrait mode, the image ends up against the left margin and isn't centered.

Centered in landscape mode:

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

Centered in portrait mode:

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

This is the HTML:

    <div id="slidebound">
    <div class="slider">
        <img src="images/slider/slide04.png" alt=""/>
        <img src="images/slider/slide03.png" alt=""/>
        <img src="images/slider/slide02.png" alt=""/>
        <img src="images/slider/slide01.png" alt=""/>
    </div>
    </div>

This is the CSS:

    #slidebound {
        width: 100%;
        height: 300px;
        overflow: hidden;
    }
    .slider {
        width: 1024px;
        height: 300px;
        overflow: hidden;
        position: relative;
        margin: 0 auto;
    }
    .slider img {
        position: absolute;
        animation: slider 32s infinite;
        opacity: 0;
        width: 100%;
        height: auto;
    }
    @keyframes slider {25% {opacity: 1;} 40% {opacity: 0;}}
    .slider img:nth-child(4) {animation-delay: 0s;}
    .slider img:nth-child(3) {animation-delay: 8s;}
    .slider img:nth-child(2) {animation-delay: 16s;}
    .slider img:nth-child(1) {animation-delay: 24s;}

Answer №1

It seems like you are looking to center your image on the screen regardless of the size. You can achieve this by using the following code:

#slidebound {
        width: 100%;
        height: 300px;
        overflow: hidden;
      display: flex;
      justify-content: center;
    }
    .slider {
        width: 1024px;
        height: 300px;
        overflow: hidden;
        position: relative;
        margin: 0 auto;
    }
    .slider img {
        position: absolute;
        animation: slider 32s infinite;
        opacity: 0;
        width: 100%;
        height: auto;
    }
    @keyframes slider {25% {opacity: 1;} 40% {opacity: 0;}}
    .slider img:nth-child(4) {animation-delay: 0s;}
    .slider img:nth-child(3) {animation-delay: 2s;}
    .slider img:nth-child(2) {animation-delay: 3s;}
    .slider img:nth-child(1) {animation-delay: 4s;}
 <div id="slidebound">
    <div class="slider">
        <img src="http://abload.de/img/a6aawu.jpg" alt=""/>
        <img src="https://nxworld.net/example/css-image-hover-effects/pic01.jpg" alt=""/>
        <img src="http://abload.de/img/a6aawu.jpg" alt=""/>
        <img src="https://nxworld.net/example/css-image-hover-effects/pic01.jpg" alt=""/>
    </div>

Answer №2

If you're looking to manipulate elements on a webpage, consider using flexbox. However, another approach is to utilize positioning and negative margins by specifying the height and width:

position:absolute;
left:50%;
margin-left:-512px;
top:50%;
margin-top:-150px;

Take a look at this code in action on JSFiddle.

Answer №3

Are you considering using flex for your specific situation? The decision may depend on the web browsers you are targeting. To check browser compatibility, you can use tools like caniuse.

For a visual demonstration, you can view this sample at https://codepen.io/hellouniverse/pen/QxwNWv.

In this example, I have successfully centered an image both vertically and horizontally:

#slidebound {
    height: 100vh;
}

.slider {
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    margin: 0 auto;
    height: inherit;
}


<div id="slidebound">
    <div class="slider">
        <img src="https://naomisimson.com/wp-content/uploads/image-placeholder.jpg" alt="" />

    </div>
</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

The content of the DIV element is not displaying properly when trying to list items

I have a div that is styled with the following CSS properties : HTML <div class="messageContainer"></div> CSS .messageContainer { margin-left: 2px; background-color: #F7F5F2; width: 100%; min-height: 50px; border: solid 1px silver ...

Is there a way to export the HTML table content to an Excel sheet that is compatible with browsers such as Internet Explorer, Mozilla Firefox, and others?

Welcome to my HTML Page! <html> <head> <title>Table </title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> <script> </script> </head> <body> <table ...

How can one set relative paths for links when including a file from a different directory that contains links?

My project directory is structured as follows: root css img src login login.php dashboard basic header.php footer.php profile.php manage.php department ...

`Changing the iframe content dynamically with next and previous buttons: a step-by-step guide`

function displayPDF(fileSlNo){ var data = { pageMode: "PDF_DISPLAY", fileSlno: fileSlNo }; var d = $.param(data); var request = $ .ajax({ type: "GET", url:"folderNavigation.do?"+d, dataType : "TEXT", success: functio ...

Tips for positioning an element at the bottom of columns using bootstrap

I'm having trouble aligning an image to the bottom of the page. Despite the column being the same height, the image just won't align all the way to the bottom. https://i.sstatic.net/0u9LH.jpg Check out the Codepen demo for reference: https://co ...

Guide on making a prev/next | first/last button functional in list.js pagination

Is there a way to enhance my paginated index by adding prev/next, first/last buttons? I am curious if anyone has implemented these features using List.js. <script src='//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js&ap ...

The website functions well in responsive design mode on an iPad screen, but encounters issues when viewed on an actual

The website is functioning well in responsive design mode on an iPad screen, however it seems to be having some issues specifically on iPad devices. I have tested it on all other devices and it works perfectly fine, but for some reason not on iPads. Feel ...

ng-model causing simultaneous changes to all selects

Check out this jsfiddle link Hello there, I'm encountering an issue with my application. I need to create multiple dropdowns using ng-repeat and have them all populated with the same options. The problem arises when one dropdown is changed, all ot ...

How do I modify the sidebar width with CSS code?

I am trying to adjust the width of the right sidebar on my website. The current layout leaves too much empty space on the right side and makes it appear crowded next to the main content and images in the center. Despite exploring various solutions provide ...

Ensuring the Angular Material bottom sheet (popover) stays attached to the button

Recently, I've been working on an Angular project where I successfully integrated a bottom sheet from Angular Material. However, I encountered an issue when trying to make the opened popup sticky to the bottom and responsive to its position, but unfor ...

Arrange information into sections

This Angular code is used to format text into profile page as blocks of data: <div class="element-box"> <div class="details-wrapper"> <p><b class="label">Remote IP</b>{{apiattempt.remote_ip}}</p> <p>< ...

Increase the size of the grid system column upon clicking on a Bootstrap icon

I am using Google Maps in a tab with Bootstrap, but the map is too small. I would like to change the Bootstrap grid system when I click on a FontAwesome icon: the first column should turn into col-md-8, and the second column should become col-md-4. Here i ...

Can the script be loaded into a TypeScript file?

I'm currently in the process of integrating this script tag into my Angular 2 project, but I'm searching for a way to incorporate it into the typescript file so that I can access its methods within the .ts file. <script type="text/javascript" ...

Show and hide a div with the click of a button

As I embark on rebuilding a website from the ground up, I find myself pondering how to achieve a specific functionality: My goal is for another view to appear when one of two buttons is clicked. How can this be accomplished? I attempted the following app ...

PHP method that invokes HTML code

I recently developed a registration and login system using object-oriented PHP. I am now looking to make the HTML code accessible from within a PHP method. Below is the View.php class that contains methods for creating the login and registration UI: < ...

What's up with the Twitter Bootstrap parameters?

As a beginner in the world of HTML5 and Twitter Bootstrap, I have been exploring some pre-built examples and now have a few questions... Consider this code snippet from the Fluid Layout Example: <div class="navbar navbar-fixed-top"> <div class ...

5 Bootstrap Popovers with Custom HTML Contents

I am having trouble separating the content of the bootstrap5 popover from the HTML attributes, unlike other components where it is achievable. var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]')) var ...

Ensure the heading expands to fit the container and include > at the conclusion

Could anyone help me create a heading effect link similar to the one on BBC's website at ? I'm specifically looking to achieve an effect where the heading text is on the left and an arrow is displayed on the right. Additionally, I would like both ...

External JavaScript functions remain hidden from the HTML page

Having issues with JavaScript functions. I created functions in a separate file named index.js, but when I use them in index.html like "onclick = function()", the file doesn't recognize the function. <!doctype html> <html lang="{{ app()-> ...

When floating divs with varying heights are wrapped, they may become stuck in place

Hey there! Let's tackle a challenge: I've got a few divs, each with varying heights. These divs contain portlets that can expand in height. Here's a basic example: .clz { float: left; } <div class="container"> <div class="cl ...