What is the best way to vertically center a div within another div when the height is not known?

I have a challenge with creating a div container that has a div for an image and a div for text. The height of the parent div is set to match the height of the text div automatically. I don't want to give the container an actual height. My goal is to vertically center the image div within the container and have the image adjust its size when the window size changes, while still remaining in the middle of the container. I've experimented with methods like 'table-cell', 'inline-block', 'vertical-align: middle', and 'position: absolute', but none of them were successful.

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
</head>
<body>
    <div class="container">
        <div class="img">
            <img src="img.jpg">
        </div>
        <div class="text">
            <h3>Heading</h3>
            <p>
                Bacon ipsum dolor amet leberkas pancetta porchetta tenderloin ground round, shoulder doner. Ribeye corned beef ground round tri-tip chicken kevin. Shankle burgdoggen ham hock t-bone brisket jowl pork chop tongue pork belly jerky ham tail venison. Filet mignon porchetta short loin swine fatback, turducken meatball ham hock tongue corned beef pancetta hamburger boudin tenderloin burgdoggen.
            </p>
            <br>
            <p>
                Strip steak landjaeger ham hock, pig picanha cow beef ribs drumstick prosciutto ball tip chicken cupim tongue salami. Cupim flank kielbasa, strip steak pork buffalo boudin. Turducken meatball sausage short ribs bacon pig venison t-bone hamburger. Strip steak alcatra boudin burgdoggen cupim. Leberkas frankfurter swine prosciutto hamburger ball tip.
            </p>
            <br>
            <p>
                Cupim buffalo pork loin, pork chop picanha corned beef turkey sausage cow chuck ham hock flank. Pork belly frankfurter meatloaf andouille spare ribs jowl leberkas venison salami capicola sausage kevin chuck. Flank beef ribs fatback, strip steak bresaola turducken biltong salami boudin tongue spare ribs pastrami shoulder frankfurter cupim.
            </p>
        </div>
    </div>
</body>
*{
    box-sizing: border-box;
}

.container{
    padding: 0 5vw;
    overflow: auto;
}

.img{
    width: 25%;
    float: left;
}

.img>img{
    width: 100%;
}

.text{
    width: 75%;
    float: left;
    padding: 0 0 0 2em;
}

Answer №1

Utilize display:flex for aligning items in the .container/.img

Achieve vertical alignment of img by using justify-content: center; and flex-direction: column;

*{
    box-sizing: border-box;
}

.container{
    padding: 0 5vw;
    overflow: auto;
       display: flex;
}

.img{
    width: 25%;
      display: flex;
    justify-content: center;
    flex-direction: column;
    text-align: center;
}

.img>img{
    width: 100%;
}

.text{
    width: 75%;
    float: left;
    padding: 0 0 0 2em;
}
<div class="container">
        <div class="img">
            <img src="https://i.sstatic.net/mSXoO.png">
        </div>
        <div class="text">
            <h3>Heading</h3>
            <p>
                Bacon ipsum dolor amet leberkas pancetta porchetta tenderloin ground round, shoulder doner. Ribeye corned beef ground round tri-tip chicken kevin. Shankle burgdoggen ham hock t-bone brisket jowl pork chop tongue pork belly jerky ham tail venison. Filet mignon porchetta short loin swine fatback, turducken meatball ham hock tongue corned beef pancetta hamburger boudin tenderloin burgdoggen.
            </p>
            <br>
            <p>
                Strip steak landjaeger ham hock, pig picanha cow beef ribs drumstick prosciutto ball tip chicken cupim tongue salami. Cupim flank kielbasa, strip steak pork buffalo boudin. Turducken meatball sausage short ribs bacon pig venison t-bone hamburger. Strip steak alcatra boudin burgdoggen cupim. Leberkas frankfurter swine prosciutto hamburger ball tip.
            </p>
            <br>
            <p>
                Cupim buffalo pork loin, pork chop picanha corned beef turkey sausage cow chuck ham hock flank. Pork belly frankfurter meatloaf andouille spare ribs jowl leberkas venison salami capicola sausage kevin chuck. Flank beef ribs fatback, strip steak bresaola turducken biltong salami boudin tongue spare ribs pastrami shoulder frankfurter cupim.
            </p>
        </div>
    </div>

Answer №2

To achieve the desired layout, implement display:flex for the parent class and apply align:self:center to the image class. This should address the alignment issue effectively.

* {
    box-sizing: border-box;
}

.container {
    padding: 0 5vw;
    overflow: auto;
    display: flex;
}

.img {
    width: 25%;
    float: left;
    align-self: center;
}

.img>img {
    width: 100%;
}

.text {
    width: 75%;
    float: left;
    padding: 0 0 0 2em;
}

.text h1 {
    margin: 0 0 20px;
}
<div class="container">
    <div class="img">
        <img src="https://via.placeholder.com/350x350">
    </div>
    <div class="text">
        <h3>Heading</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus euismod, lectus vitae rhoncus posuere, urna mi tristique justo, eu tincidunt risus nisl nec neque. Aenean posuere, diam nec ultrices tristique, metus felis tempus lectus.</p>
        <p>Nunc hendrerit viverra mauris, sit amet lacinia ante congue ac. Nulla facilisi. Morbi odio justo, condimentum eget vestibulum sit amet, semper nec est.</p>
        <p>Proin tempor luctus nibh, eget placerat magna pulvinar sit amet. Integer auctor massa quis libero pellentesque, ac rutrum sapien placerat.</p>
        <p>Duis quam ipsum, fermentum at lacinia vel, venenatis sit amet nulla. Integer hendrerit, diam eu ullamcorper vestibulum, justo tortor auctor mauris.</p>
        <p>Fusce lorem tortor, ultricies eget diam a, ultrices tristique tortor. Sed vehicula luctus congue. Aenean consequat ligula sit amet.

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 could be causing the mousewheel event in my code to remain active?

Whenever I try to scroll on Google Chrome, an error occurs on my website. jquery-3.3.1.min.js:2 [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See To resolve this issue: $(document).ready(f ...

Altering the display attribute cancels out any opacity transitions

When using JavaScript to change the opacity of an element with transition: opacity 1s, the expected duration of one second is met, as demonstrated here: onload = e => { var p = document.getElementsByTagName("p")[0]; p.style.opacity = 1; }; p { ...

How can I conceal text using css in specific situations without risking a penalty from search engines?

Currently, I'm developing an illustration tool that needs to be visually appealing to users, while also being accessible to screen readers and search engines. Below is the HTML code I'm working with: <span class="card">A new idea is presen ...

Creating a List Item with Equal Height as Its Parent Container

<nav> <ul id="navUl"> <li> <div class="settingsDiv"> hey </div> </li> </ul> </nav> I am trying to adjust the height of the div element to match the height of the nav. My g ...

laravel active li class dynamic

This is the route I have set up: <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web route ...

Can a ng-repeat value be assigned to a text input field?

<tr ng-repeat="person in users" ng-class="{'chosen': person.AdmissionID == currentSelection}" ng-click="selectRow(person.AdmissionID)"> <td>{{person.AdmissionID}}</td> <td>{{person.AdmissionNumber}}</td> ...

Problem encountered while attempting to sort a table with JavaScript and jQuery

Having trouble sorting my table by the content in the first column. I've tried implementing code similar to the one found in this ANSWER, but unfortunately, it's not working as expected for me. When you run the snippet, you can see that the table ...

Enhancing your Vue web application with Bootstrap: A guide to customization

Utilizing bootstrap-4 within my Vue web application has been challenging. I am unable to customize it as explained here. My index.html utilizes Bootstrap CDN, as shown below: <!DOCTYPE html> <html lang="en"> <head> <meta charse ...

Update the table contents smoothly using the html helper PagedListPager without having to reload the entire

I am struggling with a specific line of code that utilizes the html helper's PagedListPager: @Html.PagedListPager(Model.kyc_paged_list, page => Url.Action("ClientDetails", new { id = ViewBag.ID, kyc_page = page, transaction_page = Model. ...

How can the issue of the navbar color not being able to disappear or turn transparent be resolved, given its connection to the body color?

@import url('https://fonts.googleapis.com/css2?family=Bai+Jamjuree:wght@400;500;600;700&display=swap'); :root { --color-body: #b6cbce; --color-heading: #eef3db; --color-base: #033f47; --color-base2: #022a30; --color-brand ...

Utilizing conditional statements for confirming purchased orders with a pop-up confirmation box

function purchaseClicked() { var orders = prompt("Are you sure you want to buy these Items?"); if (orders != null) { alert('Please try selecting your items again!') } else { alert('Thank you for shopping ...

Position the typography component to the right side

Is there a way to align two typography components on the same line, with one aligned to the left and the other to the right? I'm currently using this code but the components are aligned next to each other on the left side. const customStyles = makeSt ...

What is the best way to utilize d3.domain for extracting both d3.min and d3.max values from various columns within a JSON dataset?

I have a JSON file that contains data from different years for "male," "female," and "both" categories. I want to set the minimum value in my domain to be the lowest value across all three columns and do the same for the maximum value. Is there a way for ...

Struggling with uploading files in AngularJS?

Below is the code snippet from my controller file where I aim to retrieve the values of various input elements (name, price, date, image) and store them in an array of objects... $scope.addBook = function(name, price, date, image) { name = $scope ...

"Enhance Your Form with Ajax Submission using NicEdit

Currently, I am utilizing nicEditor for a project and aiming to submit the content using jQuery from the plugin. Below is the code snippet: <script type="text/javascript"> bkLib.onDomLoaded(function() { new nicEditor().panelInstance('txt1' ...

Connecting a custom bootstrap stylesheet to WordPress

I'm having trouble linking my WordPress Stylesheet to a child theme in a different directory/subfolder. The code I placed in the functions.php file doesn't seem to be working correctly. Here is the code snippet: function theme_add_bootstrap() { ...

Triggering a sweet alert on a mouse click

Here is a code snippet I found on . It shows an alert box that doesn't disappear when clicked outside of it. swal({ title: "Are you sure?", text: "You will not be able to recover this imaginary file!", type: "warning", showCancelButton: true, ...

Utilizing jQuery to iterate over dynamically generated elements sharing a common class

Whenever I click a button, numerous div elements are dynamically created. <table> <tbody id="ProductDetail"></tbody> </table> These dynamically created divs have an associated Amount value that is added upon creation. funtion ...

Modify the styling of multiple divs using a loop when the page is first loaded

I am working on a loop that generates multiple boxes with masonry layout containing post excerpts. <div class="box"> <div class="image"> <img src="" /> </div> <div class="info"> <h3>//title output with ...

Reset input value when adding or removing inputs dynamically

Currently, I have an input element that has the capability to clear its value when a button is clicked. Additionally, this input can dynamically add or remove input elements. However, I am facing an issue where after adding an input element, the clear butt ...