Liz Nix

Third party code breaks layout, CSS to the rescue!

My friend messaged me today for help with a css problem. He has a third party form built in tables, and using dev tools we could see the form fields overlap the form container on mobile sizes.

before

Not only are the input fields overlapping the container, they are also overlapping the the required field indicator asterisks, which live in their own table cells. My first thought was that it would be nice have the inputs below the labels on mobile sizes. I achieve that by setting the table cells to display:block like so:

#tableId td{
display:block;
}

The result looked like this.

Form formatting solution, step one

Not very pretty, but a step in the right direction. Next I wanted to get the label and required field indicators up on the same line, which I did like this.

#tableId td:nth-child(-n+2){
	float:left;
	}

I had to refer to css-tricks.com/useful-nth-child-recipies/ to remember the nth child syntax. At first I was going to target those two elements with #tableId td:nth-child(2), #tableId td:first-child, but then I thought, “no! There’s a better way.” Why write extra code, right?

The result?
form-getting-close
Getting closer.

At this point I just want to tighten things up. Unfortunately there’s an inline declaration for width on the span holding the label (should be <label> not <span>, but I can’t change that either), so I have to use !important in my css solution. I also decided to decrease the height of the table cells holding the label and asterisk so they’re clearly grouped with their corresponding inputs, so I added a height declaration to the definition I made in the previous step, and a new definition for the span.

#tableId td:nth-child(-n+2){
	float:left;
	height:2em;
	}
#tableId td span{
	width:auto!important;
}

Now the form looks beautiful.
Beautiful Final Form

Of course, I wrapped the whole thing in a media query so these styles are only in play where the layout broke in the first place, which was right about 420px. Cool.

The final code I sent over to my friend looked like this.


@media (max-width: 420px){
	#tableId td{
		display:block;
	}
	#tableId td:nth-child(-n+2){
		float:left;
		height:2em;
	}
	#tableId td span{
       		width:auto!important;
   	}	
}

My friend said, “that worked like a dream,” and “if you’re blogging, this would make a great test case.” So here we are. He was using vanilla css, but if you want to use sass it’s even more succinct:

@media (max-width: 420px){
	#tableId td{
		display:block;
		&:nth-child(-n+2){
			float:left;
			height:2em;
		}
		span{
       			width:auto!important;
   		}
	}	
}

Well, there you have it. I hope you enjoyed reading about this as much as I enjoyed doing it. CSS is so much fun 🙂