Reputation: 15
I have a situation I encounter frequently. I need to add spacing between elements within a wrapper div, the wrapper uses display flex and the elements are aligned using justify-content: center
, I want to add spacing between the elements within the wrapper, however, my options are justify-content:space-between
which isn't visually appealing since I want all my elements centered with more space from the ends. justify-content:space-around
doesn't look good either, cause I want more space from the ends to the border of the container, and a little space between elements.
What's the best way to approach this?
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="nums">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
</body>
</html>
style.css
*{
margin:0;
padding:0;
box-sizing: border-box;
}
.nums{
width:100px;
margin:0 auto;
display: flex;
justify-content: center;
/* padding:15px; */
}
/*
.nums div{
margin:10px;
}
*/
I've tried adding padding to my wrapper div, but that doesn't seem to add any space between my elements within the wrapper div, is the only way to solve this is using justify-content:center
to my wrapper class and adding a margin to children elements within wrapper?
or is there something I'm missing that's making padding not work?
Upvotes: 0
Views: 723
Reputation: 253486
The solution is to use gap
, as this is its purpose, to add spacing between adjacent elements:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.nums {
border: 1px solid #000;
inline-size: fit-content;
margin-block: 1em;
margin-inline: auto;
display: flex;
justify-content: center;
gap: 15px;
}
.nums > div {
background-color: hsl(35 95% 70% / 1);
}
<div class="nums">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
References:
Upvotes: 1