4

I have a paragraph and an image side by side. I have used display:flex property for that. But in small devices, I don't want that property. Can anyone tell me how can I remove this property?

style.css

p, img {
  display: flex;
}
    
img {
  float: left;
  width: 45%;
  padding: 0;
  margin: 0;
}
    
p {
  float: right;
  text-align: justify;
  width: 50%;
  padding: 0;
  margin: 0;
  font-size: 20px;
}
roshnet
  • 1,695
  • 18
  • 22
  • I'd like to point out that `display: flex;` is added on the container of the elements that are to be kept side-by-side (or stacked), not the elements themselves. Consider wrapping 'p' and 'img' in a div which has `display: flex;` set. And, you really don't need to add `float` to either element. Flexbox does that for you. – roshnet Aug 16 '20 at 13:48

2 Answers2

2

The way to achieve this is by adding this:

@media only screen and (min-width: 600px){
 p, img {
  display: block;
 }
}

You should add a flex container that contains elements. And I recommend leaving display flex and using flex-direction: column when the media query is executed.

.flex {
  width: 100vw;
  display: flex;
  align-items: center;
}

img {
  padding: 0;
  margin: 0;
  background-color: red;
  width: 45%;
}

p {
  text-align: justify;
  padding: 0;
  margin: 0;
  font-size: 20px;
}

@media only screen and (max-width: 600px) { 
  .flex {
    flex-direction: column;
  }
}
<div class="flex">
  <img src="https://designshack.net/wp-content/uploads/placeholder-image.png" alt="" />
  <p>Hello</p>
</div>
MarkBurns
  • 438
  • 1
  • 5
  • 14
0

You should use media queries to target specific devices. The general schema for a media query is like below:

@media not|only mediatype and (expressions) {
  /* your css rules */
}

You can exclude screens smaller than a certain width from your CSS rules by setting them to their defaults,

p, img{
  display: flex;
}

img{
  float: left;
  width: 45%;
  padding: 0;
  margin: 0;
}

p{
  float: right;
  text-align: justify;
  width: 50%;
  padding: 0;
  margin: 0;
  font-size: 20px;
}

@media only screen and (max-width: 768px) {
  p {
    display: block;
  }
  img {
    display: inline-block;
  }

}

or you can write your rules such that they're only applied to screens larger than a certain width:

@media only screen and (min-width: 768px) {
  p, img {
    display: flex;
  }
}

img{
  float: left;
  width: 45%;
  padding: 0;
  margin: 0;
}

p{
  float: right;
  text-align: justify;
  width: 50%;
  padding: 0;
  margin: 0;
  font-size: 20px;
}

This reference should help for media queries: https://www.w3schools.com/css/css3_mediaqueries.asp

There is also a good resource on various ways to set a display property to default values which can be found here: Reset CSS display property to default value

nermitt
  • 127
  • 12
Ashish Yadav
  • 1,901
  • 2
  • 17
  • 23