Vertical and right alignment of image within a div.container

I am trying to center the image with the unique ID of "image" to the right and vertically on the page.

When using PHP, I generate my DIVs in the following way:

echo 
    "<div class=\"first\">
    <div id=\"second\"><label id=\"second_div_label\"></label>
    <img id=\"image\" src=\"images/my_image.png\"/>
    </div>
    <div id=\"third\"></div>
    </div>";

The CSS code I am using is:

.first {
    display: block;
    width: 50%;
    height: auto;
    margin: 0px auto;
    margin-bottom: 15px;
}

#second {
    margin-top: 5%;
    background-color: #3f51b5;
    border-radius: 5px;
    font-weight: bold;
    padding: 20px;
}

#third {
    margin-top: 15px;
    border-radius: 5px;
    padding: 20px;
}   

#image {
    width: 35px;
    height: 35px;
    float: right;
}

Even though I have used float:right for the image placement, it is not perfectly centered vertically and margin-bottom is not having the desired effect. Any suggestions on how to resolve this issue?

Answer №1

If you're looking to achieve vertical and right alignment, you can utilize the position:absolute method along with Sebastian Ekström's helpful code snippet. Remember, the parent element should have a position:relative property for this technique to work effectively.

With absolute positioning, there's no need to use float:right.

Here's an illustration:

.first {
    display: block;
    width: 50%;
    height: auto;
    margin: 0px auto;
    margin-bottom: 15px;
}

#second {
    margin-top: 5%;
    background-color: #3f51b5;
    border-radius: 5px;
    font-weight: bold;
    padding: 20px;
    position:relative;
}

#third {
    margin-top: 15px;
    border-radius: 5px;
    padding: 20px;
}   

#image {
    width: 35px;
    height: 35px;
    position:absolute;
    top: 50%;
    right:10px;
    transform: translateY(-50%);
}
<div class="first">
    <div id="second">
      <label id="second_div_label"></label>
      <img id="image" src="https://i.sstatic.net/CE5lz.png"/>
    </div>
    <div id="third"></div>
</div>

Remember to include vendor prefixes for the transform property:

  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);

Answer №2

Aziz's CSS solution is effective in modern web browsers. However, for a seamless experience across different browsers, you may want to consider incorporating jQuery with the following code snippet:

<script>
    $(document).ready(function(){
        $('#image').position({
            my: 'right center',
            at: 'right center',
            of: '.first'    //or any other container you prefer
        });
    });
</script>

By using jQuery in this manner, you can bypass the need for complex CSS rules involving floating and absolute positioning.

Answer №3

#image {
        width:35px;
        height:35px;
        float:right;
        position: relative;
        top: 50%;
        -webkit-transform: translateY(-50%);
        -ms-transform: translateY(-50%);
        transform: translateY(-50%);
  }

Apply the specified style to the image element. Additionally, ensure that the parent div (with id=second) has a height value that is greater than the height of the image.

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

Ways to make certain HTML elements stay fixed on a webpage while allowing others to be scrollable

In this layout, the page features a navbar at the top followed by a row with two columns. The left column displays the user's profile information (such as profile picture and short bio), while the right column shows other information. However, when a ...

Identifying various device platforms through CSS styling

After extensive research and testing, I have explored a variety of resources and solutions for implementing device-specific CSS on my webpage. Here are some of the references I've studied: Detect iPhone/iPad purely by css Detect Xoom browser (Andro ...

Show the selected checkbox options upon clicking the submit button

Having trouble setting up a filter? I need to create a feature where checked values from checkboxes are displayed in a specific div after submitting. The display should include a 'Clear All' button and individual 'X' buttons to remove e ...

Pass information from one .jsp file to a JavaScript function in another .jsp file

Here is the content of OneEmployee.jsp: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <form> <td> <c:out value="${emp.getEmpid()}"/></td> <td> <input type="text" id="fname" value="<c:out v ...

Display a preloader image while waiting for the content to load using jQuery or AJAX

Hey there, I could really use some help with a little issue. I've been trying to use the click() and load() functions to bring my content into a specific CSS class. $("#feed").click(function(){ $(".homefeed").load("feedcontainer.php"); ...

Difficulty with Script Causing Margin Bottom to Fail

Check out my website at this link. Below is a div I have created: <div class="home" style="background-image: url(http://payload51.cargocollective.com/1/7/237315/3336908/HomeImage_o.jpg); background-attachment: fixed; height: 660px; width: 100%; opacit ...

When the width of a single table is large, Bootstrap tables can appear misaligned and not properly

I am facing an issue with displaying two tables side by side. Whenever the width of the first table is too large, the second table is pushed below it. https://i.sstatic.net/w8zwp.png https://i.sstatic.net/SZdZU.png Is there a way to make them stay side b ...

Tips for eliminating the pesky "ghost" line that appears in your coded HTML email

Check out this Sample Code: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"> <head> <title></title> & ...

The Bootstrap glyphicon content breaks when using ASP.NET MVC minification

When working with asp.net, I noticed that minification tends to disrupt the display of bootstrap UTF symbols. For example, here is what it looks like in the original file: .glyphicon-edit:before { content: "\e065"; } And here is how it appears in ...

Deactivate one select box depending on the value chosen in another select box

I am looking to disable one select box when the other select box equals 1, and vice versa. While I know how to achieve this with IDs, the challenge arises as the select boxes I want to target have dynamically generated IDs and names via PHP. Therefore, I n ...

Is your form complete?

Is there a way to determine if all required fields in the current form are correctly filled in order to disable/enable navigation? Are there any specific properties or JQuery functions that can be used to check for form completion status? ...

Don't forget to strip off the height attribute once the transform is

Utilizing the transform property: .parent { display: inline-flex; flex-direction: column; align-items: center; } .first { height: 100px; } .second { height: 100px; transform: translateY(-50%); } <div class="parent"> <div ...

Unable to assign a value to the HTMLInputElement's property: The input field can only be set to a filename or an empty string programmatically

When attempting to upload an image, I encountered the error message listed in the question title: This is my template <input type="file" formControlName="avatar" accept=".jpg, .jpeg .svg" #fileInput (change)="uploa ...

Activate the Bootstrap 5 responsive font sizing feature (RFS) for the base font elements

I'm attempting to utilize Bootstrap's RFS functionality in version 5.1.3 to apply font sizing globally. Within my SCSS file, I've defined some basic font sizes, imported the Bootstrap SCSS files, and configured the font size settings. Howev ...

centered text positioned perfectly on a dynamically adjusting background

Seeking help to center text both vertically and horizontally within a circle background link that needs to be responsive. Setting the line-height equal to the height of the link is not an option, here's my code: html <a class="Previous" href="#"& ...

Unable to toggle class feature

I have a trio of play buttons for a custom player setup, displayed like so: <div> <div class="gs-player"> <div id="gs1" onclick="play(309689093)" class="fa fa-3x fa-play"></div> </div> <div class="gs-player"> ...

"Exploring the process of utilizing AngularJS to open a .docx file in a new template

When attempting to open a .jpeg or .pdf file in a new template using an iframe, it was successful. However, the same approach failed when trying to open a .docx file. How can this issue be resolved? Angularjs code: $scope.openTemplate = function ($fpath ...

Display a specific tab section upon clicking using jQuery or JavaScript

Hello everyone! I am completely new to JavaScript. I have added a tab slider to my HTML with 3 categories in the tab menu: All, Creative, and Branding. How can I show a div after clicking on one of the list items? I have assigned classes to the list items ...

Using jquery/offset to position a div causes it to float, but it does not take

<script type="text/javascript"> $(document).ready(function () { var top = $('#rt_outer').offset().top - parseFloat($('#rt_outer').css('marginTop').replace(/auto/, 0)); $(window).scroll(function (event) { // det ...

Condense a lineup of names into only two rows

I have a challenge where I need to showcase a list of names separated by commas, pulled from an array in my React component. The HTML output should appear as follows: <div> <span>Liza</span>, <span>Eric</span>, <span>Mic ...