Search code examples
htmlcssalignment

Separate alignment for 2 div elements on the same line


I have the weather data, humidity, and wind speed set on the same line as min-, and max-, temps respectively, see below:

However, I tried to align the temps to the right, and the humidity and wind speed to the left, but it doesn't seem to let me.

.extra_info_1,
.extra_info_2 {
  text-align: left;
}

.min_temp,
.max_temp {
  display: inline;
  text-align: right;
}

.humidity,
.wind {
  display: inline;
}
<div class="extra_info_1">
  <div class="humidity">Humidity: N/A</div>
  <div class="min_temp">N/A</div>
  <br>
</div>

<div class="extra_info_2">
  <div class="wind">Wind speed: N/A</div>
  <div class="max_temp">N/A</div>
</div>

JS (I don't think this is needed but here you are anyway):

document.querySelector(".min_temp").innerText = "Min temp: " + temp_min + "°C";
document.querySelector(".max_temp").innerText = "Max temp: " + temp_max + "°C";

document.querySelector(".feels_like").innerText = "Feels like: " + feels_like + "°C" 
document.querySelector(".humidity").innerText = "Humidity: " + humidity + "%";

Solution

  • If you want to align 2 items to opposite sides of a div, you can utilize CSS Flexbox, or more specifically, the justify-content property of Flexbox.

    .extra_info_1, .extra_info_2 {
        display: flex;
        justify-content: space-between;
    }
    <div class="extra_info_1">
        <div class="humidity">Humidity: N/A</div>
        <div class="min_temp">Min temp: N/A</div>
    </div>
    
    <div class="extra_info_2">
        <div class="wind">Wind speed: N/A</div>
        <div class="max_temp">Max temp: N/A</div>
    </div>

    As you can see, I have targeted the 2 containers, and have applied display: flex, and justify-content: space-between. Let me explain each of these lines.

    In Flexbox, you have Flex containers and Flex items.

    In your case, since I have applied display: flex; to the .extra_info_1 and .extra_info_2 divs, I have made those Flex containers, and all their direct children elements are Flex items.

    Lastly, I used the justify-content: space-between to split the free space in the Flex containers between the Flex items, or the text, in your case.

    If you would like to read more about Flexbox, I recommend reading this article by the Mozilla Developer Network.